View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
GS[_2_] GS[_2_] is offline
external usenet poster
 
Posts: 3,514
Default Delete all, but the last 23 lines of an external text file

Another way that doesn't pad with empty lines...

Sub TrimLinesFromFile()
Dim vText, n&
vText = Split(ReadTextFileContents(sFile), vbCrLf)
If UBound(vText) < 23 Then Exit Sub

Const sFile$ = "C:\Temp\Test.txt" '//edit to suit
For n = 0 To UBound(vText) - 22
vText(n) = "~"
Next 'n
vText = Filter(vText, "~", False)
WriteTextFileContents Join(vText, vbCrLf), sFile
End Sub

...which uses the following reusable helper routines to read from and
write back to text files the entire contents in one shot. The loop
assumes your file gets the daily input 'appended' to existing content
and so removes the oldest entries (at the top of the file). If
UBound(vText) does not exceed 22 then there's nothing to do so the code
below that line will only run when the file contains more than 23
lines.

*It's very important that there are no empty lines at the end of the
file for this to work! Also, as written there will never be more than
23 lines in the file.*


<Helper routines

WriteTextFileContents does not insert a line feed so your file contains
no blank lines at the end.

Function ReadTextFileContents(Filename As String) As String
' Reads large amounts of data from a text file in one single step.
Dim iNum As Integer
On Error GoTo ErrHandler
iNum = FreeFile(): Open Filename For Input As #iNum
ReadTextFileContents = Space$(LOF(iNum))
ReadTextFileContents = Input(LOF(iNum), iNum)

ErrHandler:
Close #iNum: If Err Then Err.Raise Err.Number, , Err.Description
End Function 'ReadTextFileContents()

Sub WriteTextFileContents(TextOut As String, _
Filename As String, _
Optional AppendMode As Boolean = False)
' Reusable procedure that Writes/Overwrites or Appends
' large amounts of data to a Text file in one single step.
' **Does not create a blank line at the end of the file**
Dim iNum As Integer
On Error GoTo ErrHandler
iNum = FreeFile()
If AppendMode Then
Open Filename For Append As #iNum: Print #iNum, vbCrLf & TextOut;
Else
Open Filename For Output As #iNum: Print #iNum, TextOut;
End If

ErrHandler:
Close #iNum: If Err Then Err.Raise Err.Number, , Err.Description
End Sub 'WriteTextFileContents()

</Helper routines

--
Garry

Free usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion