简体   繁体   中英

Export each column using VBA to unique txt file

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM