代码之家  ›  专栏  ›  技术社区  ›  Wizhi

使用VBA将每个列导出为唯一的txt文件

  •  -1
  • Wizhi  · 技术社区  · 6 年前

    我一直在努力跟着汤姆·厄蒂斯 example 将数据导出到txt文件,在该文件中,他将每一行提取为唯一的txt文件。 Toms代码:

    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
    

    我想将每一列提取为一个txt文件,而不是每一行。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wizhi    6 年前

    经过几次调整,我终于实现了我想要的。 第一行将是输出txt文件的头。

    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