2016-04-20 92 views
1

所以我想要做的是從我的excel文件中的每個工作表中創建一個文本文件,只導出欄D使用VBA使用多個Excel工作表創建多個文本文件

到目前爲止,我有一個宏導出列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

你只需要周圍添加代碼迴路,如果我理解正確的話:

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 
+1

BruceWayne這是我一直在尋找的答案。我會更多地考慮添加循環以供將來參考。感謝您的及時回覆! – finessefitness73

相關問題