Excel 2010 Macro Write to a Text File

 

 

The code for writing text files is similar to reading text files. You need to open a specific file for output as #1. As you loop through various records, write them to the file using the Print #1 statement. Before opening a file for output, make sure that you delete any previous examples of the file. Use the Kill statement to delete a file. Kill will return an error if the file was not there in the first place. In this case, use On Error Resume Next to prevent an error.

The following code writes out a text file for use by another application:

Sub WriteFile()

    ThisFile = “C:\Results.txt”

‘ Delete yesterday’s copy of the file

    On Error Resume Next

    Kill ThisFile

    On Error GoTo 0

‘ Open the file

    Open ThisFile For Output As #1

    FinalRow = Cells(Rows.Count, 1).End(xlUp).Row

‘ Write out the file

    For j = 1 To FinalRow

        Print #1, Cells(j, 1).Value

    Next j

End Sub

 

Use this method to write out any type of text based file.