Excel电子表格宏

时间:2019-09-27 11:50:06

标签: excel vba

我正在使用以下 excel宏

从Excel电子表格中生成文本文件
Option Explicit

Public Sub WriteToTextFile()
    Dim ws As Worksheet
    Set ws = ActiveSheet 'better by its name: ThisWorkbook.Worksheets("Sheet1")

    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim LastCol As Long
    LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    Open "C:\Users\Admin\Desktop\123.txt" For Output As #1

    Dim iRow As Long
    For iRow = 2 To LastRow
        Dim OutputLine As String

        Dim iCol As Long
        For iCol = 1 To LastCol
            If iCol = 1 Then 'first column (is different)
                OutputLine = ws.Cells(iRow, iCol).Text
            Else 'append other columns
                OutputLine = OutputLine & "," & ws.Cells(1, iCol).Text & ": " & ws.Cells(iRow, iCol).Text
            End If
        Next iCol
        'Debug.Print OutputLine
        Print #1, OutputLine 'output the full line to the text file
    Next iRow

    Close #1
    Shell "notepad.exe ""C:\Users\Admin\Desktop\123.txt""", vbNormalFocus
End Sub

按如下所示采样Excel电子表格数据

ID1 | ID2 |ID3
97  | 12  | 47
08  | 09  | 54
17  | 46  | 07

我的最终输出是

97,ID2: 12,ID3: 47
08,ID2: 09,ID3: 54
17,ID2: 46,ID3: 07

在我的最终输出中,我无法获取行数据(标题;请参阅下面的示例)。有人可以帮我吗?

ID1,ID2,ID3
97,ID2: 12,ID3: 47
08,ID2: 09,ID3: 54
17,ID2: 46,ID3: 07

谢谢!

1 个答案:

答案 0 :(得分:0)

编辑:已更新,因为先前的答案不能解决问题。

此循环已在示例数据上进行了测试,应能按预期工作:

    For iCol = 1 To LastCol
        If iRow = 1 Then
            If OutputLine = vbNullString Then
                OutputLine = ws.Cells(iRow, iCol).Text
            Else
                OutputLine = OutputLine & ", " & ws.Cells(iRow, iCol).Text
            End If
        ElseIf iCol = 1 Then 'first column (is different)
            OutputLine = ws.Cells(iRow, iCol).Text
        Else 'append other columns
            OutputLine = OutputLine & "," & ws.Cells(1, iCol).Text & ": " & ws.Cells(iRow, iCol).Text
        End If
    Next iCol