使用 VBA 使用多个 Excel 工作表创建多个文本文件

Create multiple text files using multiple Excel worksheets using VBA

所以我想做的是从我的 excel 文件中的每个工作表创建一个文本文件,仅导出列 D

到目前为止,我有一个导出列 D 的宏,但仅在活动工作表上。

这是我当前的宏:

 Private Sub CommandButton21_Click()

    Dim userName As Variant
    userName = InputBox("Enter your six character user ID")
    Dim userNamePath As String
    userNamePath = "C:\Users\" & userName & "\Desktop\Device Configurations\"
    MkDir userNamePath
    Dim filename As String, lineText As String
    Dim myrng As Range, i, j

    filename = userNamePath & "test.txt"

    Open filename For Output As #1

    Set myrng = Range("C1:C5, D1:D5")

    For i = 1 To myrng.Rows.Count

        For j = 1 To myrng.Columns.Count
            lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i

    Close #1
End Sub

所以我在用户桌面上创建了一个名为“Device configurations”的文件夹,并将文本文件放入该目录中。出于测试目的,该文本文件名为“test”。我想用各自工作表的名称导出这些文本文件。

例如,我想导出工作表 12345,但只导出第 [=13 列] =] 来自每个工作表,每个工作表都需要有自己的文本文件。我想通过单击一次宏来完成此操作。

你只需要在你的代码周围添加一个循环,如果我理解正确的话:

Sub t()
Dim ws      As Worksheet

Dim userName As Variant
userName = InputBox("Enter your six character user ID")
Dim userNamePath As String
userNamePath = "C:\Users\" & userName & "\Desktop\Device Configurations\"
MkDir userNamePath
Dim filename As String, lineText As String
Dim myrng   As Range, i, j

For Each ws In ActiveWorkbook.Sheets
    With ws
        filename = userNamePath & .Name & " - test.txt"    ' to add the worksheet name to the text file

        Open filename For Output As #1

        Set myrng = .Range("C1:C5, D1:D5")

        For i = 1 To myrng.Rows.Count

            For j = 1 To myrng.Columns.Count
                lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
            Next j
            Print #1, lineText
        Next i

        Close #1
    End With                 'ws
Next ws

End Sub