Alex Rivera | Logout

How can I write to a text file reliably from Excel VBA?

Asked 2010-06-21T14:41:09.490
13

I'm trying to use Excel VBA to write to a text file. I'm doing a few of these:

MyFile1 = "C:\outputFromExcel1.txt"
fnum1 = FreeFile()
Open MyFile1 For Output As fnum1

and then writing to them like this:

Print #fnum1, text

All variables in the above are declared just with Dim. I'm writing hundreds of lines to the files and, very rarely, lines are being truncated -- i.e. the ends are being chopped off. Is there a better way to write to a file in Excel VBA?

EDIT: I've just realized that it's always the last lines to be written that are truncated. So I guess I need to close or flush the files somehow?

Edit
Report

1 Answer

15

You can use Close #fnum1 to close the file handle and it should flush the remaining buffer contents.

answered 2010-06-21T14:49:11.503

Your Answer