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

时间:2016-04-20 15:25:33

标签: excel vba export range worksheet

所以我要做的是从我的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,但只导出列D从每个工作表,每个都需要有自己的文本文件。我想通过一次宏观点击来实现这一目标。

1 个答案:

答案 0 :(得分:1)

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

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