5

我有一段代码如下:

Open "output.txt" For Output As #1
s = "abc" & chr(10) & "def"
Msgbox s
print #1, s

当我运行此代码时,它Msgbox会打印 2 行。但是,在output.txtabcdef打印。

有谁知道如何将多行的字符串输出到文件中?

4

3 回答 3

8

要让它出现在您需要的文本文件中的单独行上,Chr(13) & Chr(10)或者vbCrLf如果您在 excel vbavbNewLine中。所有这些都将提供所需的回车符Chr(13)和换行符Chr(10)来产生换行符。

示例(所有 3 产生相同的结果):

"First Line" & Chr(13) & Chr(10) & "Second Line"
"First Line" & vbCrLf & "Second Line"
"First Line" & vbNewLine & "Second Line"

输出:

"First Line"
"Second Line"
于 2013-10-09T21:47:15.477 回答
1

我建议改用 TextStream 对象(通过 FileSystemObject 的 CreateTextFile 方法)。这将使您能够根据需要将行分开。

例如,您的情况将是:

Dim fso As FileSystemObject ' Declare a FileSystemObject.
Set fso = New FileSystemObject ' Create a FileSystemObject.
Dim stream As TextStream ' Declare a TextStream.

Set stream = fso.CreateTextFile("C:\output.txt", True)
stream.WriteLine "abc"
stream.WriteLine "def"
stream.Close

MSDN 涵盖了这一点:http: //msdn.microsoft.com/en-us/library/office/gg264514.aspx

于 2013-10-09T20:56:07.283 回答
0

这是我的解决方案:添加额外的字符串而不是换行符。例如,我的单元格的值是“testing#BR#jump#BR#lines”然后我使用了拆分函数并使用 for 循环逐行写入文件:

For xrow = 2 To 10
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = fso.CreateTextFile("C:\test\History_" & Cells(xrow , 1) & ".txt")
    matLines = Split(Cells(xrow, 2), "#BR#")
    For line = 0 To UBound(matLines)
        oFile.WriteLine matLines(line)
    Next line
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing
Next xrow

结果是文件一行一行。

于 2016-05-03T18:11:33.257 回答