How to edit a text file from vba (1 Viewer)

AccessKid

Registered User.
Local time
Today, 19:32
Joined
Jun 26, 2002
Messages
36
I need to edit a text file by reading it line by line and replacing certain strings with "".

How do I setup the i/o section of my code? Pls. help.
 

ritchieroo

Registered User.
Local time
Today, 19:32
Joined
Aug 2, 2002
Messages
80
Traditional VB I/O method...


Dim hFile as Long
Dim sLine as String

hFile = FreeFile

Open "c:\Whatever.txt" For Random As #hFile

Do Until EOF(hFile)
Line Input #hFile, sLine

'... Process sLine

Loop

Close #hFile




There are also more up to date methods such as TextStream objects whixh are a little easier to use, but no more efficient on the whole.

You can get a TextStream object by setting a reference to the "Microsoft Scripting Runtime" library. After creating a new FileSystemObject, use the OpenTextFile method to open and manipulate your file.

If you're used to using ADO, it offers a Stream object that can be used to do the same sort of things. It's character set aware, and can fix issues such as Chr(13) being used to end lines rather than Chr(13) & Chr(10) automatically. But all this added functionality can make it trickier to use.
 

AccessKid

Registered User.
Local time
Today, 19:32
Joined
Jun 26, 2002
Messages
36
Thanks for the suggestion. I will try this today.
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 14:32
Joined
Feb 19, 2002
Messages
43,461
You can't update a sequential file. You can only add records to the end of it.

To modify a sequential file, you will need to read it and write each record to a new copy of the file, making changes as you go.
 

AccessKid

Registered User.
Local time
Today, 19:32
Joined
Jun 26, 2002
Messages
36
Thanks, Pat. I haven't tried the previous suggestion as yet but I already had a workaround to the original problem and it was like what you said.
 

Users who are viewing this thread

Top Bottom