SoftTimur
SoftTimur

Reputation: 5520

Write a string of several lines to a file

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?

Upvotes: 5

Views: 66481

Answers (3)

B Hart
B Hart

Reputation: 1118

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"

Upvotes: 8

Daniel Luevano Alonso
Daniel Luevano Alonso

Reputation: 331

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:

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.

Upvotes: 0

Jenothy
Jenothy

Reputation: 123

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

Upvotes: 1

Related Questions