Saving Information in a Text File

There may be times when you want a macro to save information to a text file. This is very easy to do. All you need is to open the file for output, and then start sending information to the file. The following code fragment writes a text file using this method.

Open "MyFile.Dat" For Output As #1
Print #1, NumValues
For J = 1 to NumValues
    Print #1, UserVals(J)
Next J
Close #1

The first thing written to the file is a numeric value indicating how many individual values will follow it (the code presumes that you set this value in the NumValues variable). Then a For … Next loop is used to create the balance of the file.

You should be aware that the code, as written, will overwrite any existing MyFile.Dat file. If you want to protect the file in some way, your code will need to check to see if it exists before opening it or you’ll need to set the attributes of the file to read-only.