Export each column using VBA to unique txt file

故事扮演 提交于 2020-12-08 05:17:28

问题


I've been struggling to follow Tom Urtis example of export data to txt file, where he extracts each row to a unique txt file. Toms code:

Sub TextExport()
Dim strPath$, x&, i%, txt$
strPath = ThisWorkbook.Path & "\"
For x = 1 To Cells(Rows.Count, 1).End(xlUp).Row 'From row 1 to last row
Open strPath & Cells(x, 1).Value & ".txt" For Output As #1
txt = ""
For i = 1 To 3 'From Column 1 to 3
txt = txt & Cells(x, i).Value & vbTab
Next i
Print #1, Left(txt, Len(txt) - 1)
Close #1
Next x
MsgBox "The text files can be found in " & strPath & ".", 64, "Complete"
End Sub

I want to extract each column to an txt file, instead of each row.


回答1:


After a couple of tweaks I've managed to achieve what I want. The first row will be the headers of the output txt files.

Sub TextExportCol()
Dim strPath$, x&, i%, txt$
strPath = ThisWorkbook.Path & "\"
For x = 1 To Cells(1, Columns.Count).End(xlToLeft).Column 'Loop from  column 1 to end column
    Open strPath & Cells(1, x).Value & ".txt" For Output As #1
    txt = ""
        For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row 'How many rows to include, from row 1 to end
        txt = txt & Cells(i, x).Value & vbNewLine
        Next i
    Print #1, Left(txt, Len(txt) - 1)
    Close #1
    Next x
MsgBox "The text files can be found in " & strPath & ".", 64, "Complete"
End Sub


来源:https://stackoverflow.com/questions/51687643/export-each-column-using-vba-to-unique-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!