【问题标题】:Excel VBA output multiple columns to text fileExcel VBA将多列输出到文本文件
【发布时间】:2014-12-23 00:36:00
【问题描述】:

我正在尝试创建一个 Excel VBA 脚本,它将 2 列作为输入并将 的值输出到文本文件中。

例如

A1:123 B1:大道

A2:231 B2:另一条车道

我正在寻找一个看起来像这样的 txt 文件中的输出:

门牌号:123 街名:大道

----.

门牌号:231 街道名称:另一条车道

----.

基本上我正在寻找的是: "门牌号:"+A1+ "街道名称:"+B2 “-----”

我只能使用 1 列,但我坚持要添加第二列。

Sub CreatetestScript()

    If Dir("C:\test.txt") <> "" Then
     Kill ("C:\test.txt")
    End If

    Sheets("test").Select
    Dim acolumn As String

    r = 2
    Do While Cells(r, 1) <> ""
        acolumn = Cells(r, 1).Value
        run (Cells(r, 1))
        r = r + 1
    Loop

End Sub
Sub run(ByVal acolumn As String)

Dim fileName As String
fileName = "C:\test.txt"

Open fileName For Append As #1

    Print #1, ""
    Print #1, "House Number = " + acolumn
    Print #1, "--------------"

Close #1

End Sub

任何帮助将不胜感激

【问题讨论】:

    标签: excel vba output


    【解决方案1】:

    你可以有很多方向,一种方法是创建一个 bcolumn 变量并将其设置为行中下一个单元格的索引:

    Sub CreatetestScript()
    
        If Dir("C:\test.txt") <> "" Then
         Kill ("C:\test.txt")
        End If
    
        Sheets("test").Select
        Dim acolumn As String
        Dim bColumn As String
        r = 2
        Do While Cells(r, 1) <> ""
            acolumn = Cells(r, 1).Value
            bColumn = Cells(r,2).value
            run (Cells(r, 1), Cells(r,2))
            r = r + 1
        Loop
    
    End Sub
    Sub run(ByVal acolumn As String, ByVal Bcolumn As String)
    
    Dim fileName As String
    fileName = "C:\test.txt"
    
    Open fileName For Append As #1
    
        Print #1, ""
        Print #1, "House Number = " + acolumn
        Print #1, "--------------"
        Print #1, ","
        Print #1, "Street = " + Bcolumn
        Print #1, "--------------"
    Close #1
    
    End Sub
    

    您的输出可能需要采用不同的格式,但这应该能让您走上正轨。为了一点可重用性,您也可以设置函数来获取这些字符串的数组。

    【讨论】:

    • 您好,感谢您的回答,我收到编译错误 Argument not optional 错误消息
    • 我没有为 run 函数提供新值。请查看我的更改,如果我们在正确的轨道上,请告诉我:)
    • 你太快了。刚试过。感谢您的帮助
    猜你喜欢
    • 2018-11-25
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多