我有一段代码如下:
Open "output.txt" For Output As #1
s = "abc" & chr(10) & "def"
Msgbox s
print #1, s
当我运行此代码时,它Msgbox
会打印 2 行。但是,在output.txt
中abcdef
打印。
有谁知道如何将多行的字符串输出到文件中?
要让它出现在您需要的文本文件中的单独行上,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"
我建议改用 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
这是我的解决方案:添加额外的字符串而不是换行符。例如,我的单元格的值是“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
结果是文件一行一行。