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.
Does anyone know how to output a string of several lines to a file?
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.
Examples (All 3 Produce The Same Result):
"First Line" & Chr(13) & Chr(10) & "Second Line"
"First Line" & vbCrLf & "Second Line"
"First Line" & vbNewLine & "Second Line"
Output:
"First Line"
"Second Line"
I recommend using the TextStream object (via FileSystemObject's CreateTextFile method) instead. This will give you the ability to separate lines out as needed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With