I was recently working on a project where I needed to create a few lines of text based on the data in an Access database. I could have just written the data to a TextBox, but to save some cutting and pasting, I had the code write it directly to a file.
The method is easy enough, if a bit obscure. Unlike most of VBA, this is not done with a function call or through an object; it is done using a statement, the Print # statement. The Print # statement goes back to the original BASIC compilers and their GOTOs, GOSUBs and line numbers. I wrote code in BASIC using Print # 30 years ago.
First step is to open the file. To do this, get a handle (an integer) to a file and use it to open the file for writing.
FileHandle = FreeFile() Open Filename For Output As FileHandle
Then write to the file with the print statement.
Print #FileHandle PrintParamaters
Then close the file.
Close Filename
There are other optional parameters for the Open & Close functions, but these are sufficient for this case. Here is a example subroutine that writes part of an Excel worksheet to a CSV (comma-separated value) file.
Public Sub WriteToCSV()
Dim fnum As Integer
Dim cell As Range
Dim outLine As String
Dim row As Integer
Dim col As Integer
fnum = FreeFile()
Open "C:\region.csv" For Output As fnum
For row = 1 To 5
outLine = ""
For col = 1 To 5
outLine = outLine & Chr(34) & Cells(row, col).Value & Chr(34) & ","
Next col
Print #fnum, Left(outLine, Len(outLine) - 1)
Next row
Close #fnum
End Sub
RSS feed for comments on this post · TrackBack URI
Leave a reply
You must be logged in to post a comment.