写入文本格式

时间:2020-07-10 09:54:51

标签: excel vba

我在Excel中有一堆需要写入txt的数据,我必须将其导入其他程序。该软件具有非常特定的格式,我不知道如何创建可以完全按照我的需要执行的代码。

Excel:

Excel

这只是一个示例,有更多列,实际版本和行数也有所不同。 在结果文本文件中,应如下所示:

txt:

txt

因此,在此示例中,它需要第2行的ID,然后是括号中的行号,然后是等号以及相关的名称或日期。

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

您可以在Excel工作表中使用一些循环单元格以及一些VBA文件输入/输出来实现此目的。以下是一些可在提供的示例数据上正常工作的代码,应该使您指向正确的方向:

Sub sExportPersonData()
    On Error GoTo E_Handle
    Dim ws As Worksheet
    Dim intFile As Integer
    Dim strFile As String
    Dim lngLastRow As Long
    Dim lngLastCol As Long
    Dim lngRowLoop As Long
    Dim lngColLoop As Long
    Dim strOutput As String
    intFile = FreeFile
    strFile = "J:\downloads\person.txt"
    Open strFile For Output As intFile
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lngLastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    lngLastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    For lngRowLoop = 3 To lngLastRow
        For lngColLoop = 2 To lngLastCol
            strOutput = ws.Cells(2, lngColLoop) & "[" & ws.Cells(lngRowLoop, 1) & "]=" & ws.Cells(lngRowLoop, lngColLoop)
            Print #intFile, strOutput
        Next lngColLoop
    Next lngRowLoop
sExit:
    On Error Resume Next
    Close #intFile
    Set ws = Nothing
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "sExportPersonData", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub

此致