Edit *.txt file programatically

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Thanks for taking the time to read my question.

I am wondering if it is possible to open a text file and edit the contents,
save it and close it.

What commands would I use to open it, and then edit it, then save it, then
close it?

Thanks again,

Brad
 
You can use the Open statement to open the file (use the FreeFile to get a
file handle, rather than hard-coding to #1, like most people do!). You can
use Line Input# statement to read the text in line-by-line (or the Input#
statement, but it can be problematic). Use the Write # statement to write
the text back out, and then the Close statement.
 
Thanks for taking the time to read my question.

I am wondering if it is possible to open a text file and edit the contents,
save it and close it.

What commands would I use to open it, and then edit it, then save it, then
close it?

Are you doing this from Access? How are you determining which file to
open? Do you want to open an editor and let the user type, or do you
want to programmatically edit the file?


John W. Vinson[MVP]
 
I'm assuming you mean open a text file from a program, not simply open
NotePad or some other text application.

Using VBA, one way to do it is to open the file and read the entire contents
of the file into a string variable.

Dim N as Integer, St as String
n=freefile
open "c:\filename.txt" for read as #n
St=input lof(#N),#n 'this ready the whole file
close #n

Then you can do whatever you want with the string, edit it any way you wish.
when you're done simply open the file again for writing and write the string
out to it.

Dim N as Integer
Open "C;\filename.txt" for write as #n
Pirnt #n, St
close

This is an old method, VBA provides with FileStream and TextStream objects
as well as many new string change operations including regular expressions.
They are a lot for powerful but more complex as well.

Spence
 
Back
Top