Write to a file

J

Judy Ward

I searched for help in the Microsoft Visual Basic window and came up with the
code below. I am hoping to adapt this simple example to meet my needs. But
one big problem is that I don't want to see quote marks around my text (Hello
World, in this example) in the file that is created.

Sub WriteToFile()
Dim myText As String
myText = "Hello World"
Open "C:\TESTFILE.txt" For Output As #1
Write #1, myText
Close #1
End Sub

I need to output many lines to a text file, static data mixed in with
variables from a recordset. There must be a way to do this.

Can anyone provide sample code or point me to an article to read?
Thank you for your help,
Judy
 
J

Judy Ward

Thank you for responding!

For anyone else who might have the same question, the answer is as simple as
changing this line:
Write #1, myText
to
Print #1, myText

Problem solved. Thanks again,
Judy
 
D

Douglas J. Steele

Glad you got your problem solved, but I thought I'd point out that you
should never hard-code the file handle number, as in

Print #1, myText

That's because you can never be sure that some other application won't be
open at the same time, and that it might be using file handle 1.

What you should do is use the FreeFile function to return a handle to use:

Sub WriteToFile()
Dim intFile As Integer
Dim myText As String

myText = "Hello World"
intFile = FreeFile()
Open "C:\TESTFILE.txt" For Output As #intFile
Print #intFile, myText
Close #intFile

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top