Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a string of several lines to a file

Tags:

excel

vba

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?

like image 625
SoftTimur Avatar asked Oct 09 '13 20:10

SoftTimur


2 Answers

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"
like image 129
B Hart Avatar answered Nov 15 '22 23:11

B Hart


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

like image 26
Jenothy Avatar answered Nov 15 '22 23:11

Jenothy