Delete lines from txt file

  • Thread starter Thread starter Lars Brownies
  • Start date Start date
L

Lars Brownies

With code like the following:

Open "c:\MyLog.txt" For Output As #1
Write #1, strError
Close #1

I log the errors users encounter. However I don't want this file to become
bigger than about 250 lines.

So I am thinking of a cleaning routine which runs when the first user of
that day logs in, and deletes the oldest lines, so that that are only 250
lines left.

How would I go about this or are there better approaches / other ideas?

Thanks,

Lars
 
One approach would be to read the entire content of the file into a
variable, use the Split function to split it into individual lines
(splitting on vbCrLf), and then write the last 250 entries out.
 
Thanks Doug. Good idea!

I found that, before writing the values back to the text file, I can easily
empty the text file by:
Open "c:\Test.txt" For Output As #1
Close #1
 
Even easier would be

Kill "C:\Test.txt"

Incidentally, it's generally not considered a good idea to use a hard-coded
file handle (as in For Output As #1) just in case there are other
applications running at the same time which are using #1 as well. Far better
is to use the FreeFile function:

Dim intFile As Integer

intFile = FreeFile()
Open "c:\Test.txt" For Output As #intFile
Close #intFile
 
Thanks again.
I already implemented the FreeFile() since Dirk Coldgar recently pointed me
to it as well.
 
Douglas J. Steele said:
Even easier would be

Kill "C:\Test.txt"

Incidentally, it's generally not considered a good idea to use a
hard-coded file handle (as in For Output As #1) just in case there are
other applications running at the same time which are using #1 as well.
Far better is to use the FreeFile function:

Dim intFile As Integer

intFile = FreeFile()
Open "c:\Test.txt" For Output As #intFile
Close #intFile
 
Back
Top