View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
Auric__ Auric__ is offline
external usenet poster
 
Posts: 538
Default Delete all, but the last 23 lines of an external text file

GS wrote:

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

*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.*


This version ignores empty lines at the end of the file, makes it easier to
change the number of lines that are kept, and fixes a couple bugs. ;-)

Sub TrimLinesFromFile()
Dim vText, n&, fnum&
Const sFile$ = "C:\Temp\Test.txt" '//edit to suit
Const maxLines = 23
vText = Split(ReadTextFileContents(sFile), vbCrLf)
For n& = UBound(vText) To 0 Step -1
If "" < vText(n&) Then
If n& < UBound(vText) Then ReDim Preserve vText(n&)
Exit For
End If
Next
If n& < 1 Then Exit Sub 'text file only contains blank lines
If UBound(vText) < maxLines Then Exit Sub 'text file is < 23 lines long

For n& = 0 To UBound(vText) - maxLines
vText(n&) = "~"
Next 'n
vText = Filter(vText, "~", False)
WriteTextFileContents Join(vText, vbCrLf), sFile
End Sub

--
Awesome thing #1