Forum Discussion
learnerjane
Jul 15, 2022Copper Contributor
Excel VBA code to break and read text file line by line
Hello, I have a requirement. The below is a text file data. In this, I have to ignore the lines starting with HEAD and count the number of lines starting with DET for each data group. Eg....
- Jul 15, 2022
Here you go.
Sub ProcessTextFile() Dim sFile As String Dim f As Integer Dim sLines As String Dim aLines() As String Dim aLine() As String Dim i As Long Dim n As Long Dim sTitle As String ' *** Change sFile to the correct path and filename *** sFile = "Test.txt" f = FreeFile Open sFile For Input As #f sLines = Input(LOF(f), #f) Close #f aLines = Split(sLines, vbCrLf) For i = 0 To UBound(aLines) If aLines(i) <> "" Then aLine = Split(aLines(i), "|") Select Case aLine(0) Case "HEAD" If n > 0 Then Debug.Print "Group " & sTitle & " has " & n & " items" End If sTitle = aLine(1) n = 0 Case "DET" n = n + 1 End Select End If Next i Debug.Print "Group " & sTitle & " has " & n & " items" End Sub
HansVogelaar
Jul 15, 2022MVP
Here you go.
Sub ProcessTextFile()
Dim sFile As String
Dim f As Integer
Dim sLines As String
Dim aLines() As String
Dim aLine() As String
Dim i As Long
Dim n As Long
Dim sTitle As String
' *** Change sFile to the correct path and filename ***
sFile = "Test.txt"
f = FreeFile
Open sFile For Input As #f
sLines = Input(LOF(f), #f)
Close #f
aLines = Split(sLines, vbCrLf)
For i = 0 To UBound(aLines)
If aLines(i) <> "" Then
aLine = Split(aLines(i), "|")
Select Case aLine(0)
Case "HEAD"
If n > 0 Then
Debug.Print "Group " & sTitle & " has " & n & " items"
End If
sTitle = aLine(1)
n = 0
Case "DET"
n = n + 1
End Select
End If
Next i
Debug.Print "Group " & sTitle & " has " & n & " items"
End Sublearnerjane
Jul 23, 2022Copper Contributor
Worked like a charm Thanks a lot!