Writing Text Files

The code for writing text files is similar to reading text files. You need to open a specific file for output as #1. Then, as you loop through various records, you write them to the file using the Print #1 statement.

Before you open a file for output, you should make sure that any prior examples of the file have been deleted. You can use the Kill statement to delete a file. Kill returns an error if the file wasn't there in the first place, so you will want to 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 = Range("A65536").End(xlUp).Row ' Write out the file For j = 1 To FinalRow

0 0

Post a comment