Access2000 VBA: writing an ASCII file

A

Arvi Laanemets

Hi

I had an app (Access97) quite some years ago, which did what requested in
subject, but I couldn't find it anymore, and I don't remember much about
writing it anymore too. Of-course I can find all info from Help, but maybe
someone has some code example to share.


Generally, I need a code to create a new text file in given location
(FilePath and FileName are given to procedure as parameters), then write
some info into it (row- and entry-wise, the number of entries in row, as
every entry length, may vary and are determined in procedure). And in end
the text file must be saved and closed.

The written text file (3rd party program import file) doesn't have any table
structure (fixed width or delimitted), so the only way to write it is to use
low-level file operations.


Thanks in advance for any help!
 
A

Allen Browne

This is the basic logic to write a text file:

Function WriteFile()
Dim strOutputFile As String
Dim iFileNum As Integer

strOutputFile = "C:\MyFolder\MyFile.txt"
iFileNum = FreeFile
Open strOutputFile For Output As #iFileNum
Print #1, "This is a test"
Close #iFileNum
Debug.Print "Wrote file " & strOutputFile
End Function

If you need help to loop through the records of a table so you can Print #1
each line, see:
http://allenbrowne.com/func-DAO.html#DAORecordsetExample
 
A

Arvi Laanemets

Hi

Thanks!

I myself did find those statements (Open, Print) too, but I decided for
FileSystemObject scripting operators (because it was for them I did found a
way to check for existence of file and delete it as first):

Sub WriteEDI(parPath, parFile, parEntry)
Dim fs, f, ts
Dim booFileExists As Boolean

Set fs = CreateObject("Scripting.FileSystemObject")

booFileExists = fs.FileExists(parPath & parFile)
If booFileExists Then fs.DeleteFile parPath & parFile, True

fs.CreateTextFile parPath & parFile
Set f = fs.GetFile(parPath & parFile)
Set ts = f.OpenAsTextStream(2, 0)
ts.WriteLine parEntry & " 1"
ts.WriteLine parEntry & " 2"
ts.Close
End Sub

Is there any fundamental difference between them?
 
A

Allen Browne

The difference is the libraries you need referenced.

Dir() tests for a file.
Kill gets rid of it.
 

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