excel vba write to text file code example

Example 1: vba write text file

Open ThisWorkbook.Path & "\log.txt" For Append As #1
Write #1, "Here is my text."
Write #1, "Another line."
Close #1

Example 2: excel vba save file txt

' Needs to add "Microsoft Scripting Runtime" reference to your file
Public Sub SaveTextToFile(ByVal pFile As String, ByVal pText As String)
    Dim fso As FileSystemObject
    Dim fileStream As TextStream

    Set fso = New FileSystemObject
    Set fileStream = fso.CreateTextFile(pFile)
    fileStream.WriteLine pText
    fileStream.Close
End Sub
' -----------------------------------------------------------------------
Sub TestMe()
      SaveTextToFile "C:\Temp\export.txt", "A sentence to be saved..."
End Sub

Tags:

Vb Example