vba 将多行的字符串写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19282401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a string of several lines to a file
提问by SoftTimur
I have a piece of code as follows:
我有一段代码如下:
Open "output.txt" For Output As #1
s = "abc" & chr(10) & "def"
Msgbox s
print #1, s
When I run this code, the Msgbox
does print 2 lines. However, in output.txt
, abcdef
is printed.
当我运行此代码时,Msgbox
确实会打印 2 行。但是,在output.txt
,abcdef
被打印。
Does anyone know how to output a string of several lines to a file?
有谁知道如何将多行的字符串输出到文件中?
回答by B Hart
For it to appear on separate lines within a text file you will need Chr(13) & Chr(10)
or vbCrLf
or if you're in excel vba vbNewLine
. All of which will provide the needed carriage return Chr(13)
and line feed Chr(10)
characters to produce a line break.
为使其在不同的行文本文件中出现,你需要Chr(13) & Chr(10)
或者vbCrLf
或者如果您在Excel VBA是vbNewLine
。所有这些都将提供所需的回车Chr(13)
和换行Chr(10)
字符以产生换行符。
Examples (All 3 Produce The Same Result):
示例(所有 3 个产生相同的结果):
"First Line" & Chr(13) & Chr(10) & "Second Line"
"First Line" & vbCrLf & "Second Line"
"First Line" & vbNewLine & "Second Line"
Output:
输出:
"First Line"
"Second Line"
回答by Jenothy
I recommend using the TextStream object (via FileSystemObject's CreateTextFile method) instead. This will give you the ability to separate lines out as needed.
我建议改用 TextStream 对象(通过 FileSystemObject 的 CreateTextFile 方法)。这将使您能够根据需要将行分开。
For example, your situation would instead be:
例如,您的情况将是:
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 has this covered: http://msdn.microsoft.com/en-us/library/office/gg264514.aspx
MSDN 涵盖了这一点:http: //msdn.microsoft.com/en-us/library/office/gg264514.aspx
回答by Daniel Luevano Alonso
This was my solution: Add extra string instead of the line breaker. For example the value of my cell is "testing#BR#jump#BR#lines" Then I used a split function and use a for loop to write line by line into the file:
这是我的解决方案:添加额外的字符串而不是换行符。例如我的单元格的值是“testing#BR#jump#BR#lines”然后我使用了一个split函数并使用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
The result was the file line by line.
结果是一行一行的文件。