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

所以我想要做的是从我的Excel文件中的每个工作表创build一个文本文件,只导出列D

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

这是我目前的macros:

  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 

所以我在用户桌面上创build一个标题为“ Device configurations ”的文件夹,并将文本文件放到这个目录中。 该文本文件被称为“ test ”用于testing目的。 我想导出这些文本文件与他们各自的工作表的名称。

因此,例如,我想导出表15但仅从每个工作表的D列,每个都需要有自己的文本文件。 我想用一个单一的macros点击完成这个。

如果我理解正确,只需要在代码中添加一个循环:

 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