[FONT=Fixedsys]Option Explicit[/FONT]
[FONT=Fixedsys][/FONT]
[FONT=Fixedsys]Public Sub ProcessTextFile()
Dim sFileName As String
Dim sBakFile As String
Dim iPtr As Integer
Dim iFHin As Integer
Dim iFHout As Integer
Dim sRecord As String
Dim iRecords As Long
Dim iChanged As Long
ChDrive Left(ThisWorkbook.Path, 2)
ChDir Mid(ThisWorkbook.Path, 3)
sFileName = Application.GetOpenFilename(FileFilter:= _
"CSV (Comma delimited) (*.csv), *.csv, Text (*.txt), *.txt, All files (*.*), *.*")
If sFileName = "False" Then Exit Sub
[COLOR=green] ' make a filename based on the name of the input file but with the extension BAK: we will use
' this as our input file, so if anything goes wrong the user still has a copy of his original
' file intact and unmodified
[/COLOR] iPtr = InStrRev(sFileName, ".")
If iPtr = 0 Then
sBakFile = sFileName & ".bak"
Else
sBakFile = Left(sFileName, iPtr - 1) & ".bak"
End If
FileCopy sFileName, sBakFile
iRecords = 0
iChanged = 0
Close
iFHin = FreeFile()
Open sBakFile For Input As iFHin
iFHout = FreeFile()
Open sFileName For Output As iFHout
[COLOR=green] ' get the header line and write it out unchanged
[/COLOR] Line Input #iFHin, sRecord
Print #iFHout, sRecord
Do Until EOF(iFHin)
Line Input #iFHin, sRecord
If Len(sRecord) > 1 Then
[COLOR=green] ' if there are at least two characters in the line, remove the last two
[/COLOR] sRecord = Left(sRecord, Len(sRecord) - 2)
iChanged = iChanged + 1
End If
Print #iFHout, sRecord
iRecords = iRecords + 1
Loop
Close iFHin
Close iFHout
MsgBox "Done!" & Space(10) & vbCrLf & vbCrLf _
& "Header plus " & Format(iRecords, "#,##0") & " records read" _
& Space(10) & vbCrLf & vbCrLf _
& Format(iChanged, "#,##0") & " records changed" & Space(10), _
vbOKOnly + vbInformation
End Sub[/FONT]