Your code is only programmed to find the first instance and then read the following line, hence your observation.
If you want to read all the values and then read the values on the lines that reflect the 'WhatToFind' text then you need a different and simpler approach e.g.
Code:
Option Explicit
'Graham Mayor - https://www.gmayor.com - Last updated - 12 Jan 2021
Private Sub UserForm_Initialize()
Dim WhatToFind As String, FromFile As String
WhatToFind = "DOB"
FromFile = "C:\Working with Textfiles\Original2-Name-Age.txt"
MsgBox FileSearch(WhatToFind, FromFile)
'''''MSGBOX DISPLAYS DATES OF BIRTH
End Sub
Private Function FileSearch(ByVal WhatToFind As String, ByVal FromFile As String) As String
Dim FileNum As Integer
Dim DataLine As String
Dim strFound As String
Dim vLine As Variant
Dim strList As String
FileNum = FreeFile()
Open FromFile For Input As #FileNum
Do While Not EOF(FileNum)
Line Input #FileNum, DataLine ' read in data 1 line at a time'
If InStr(1, DataLine, WhatToFind) > 0 Then 'the string is found'
If InStr(1, DataLine, Chr(34)) > 0 Then
strFound = DataLine
vLine = Split(strFound, Chr(34)) 'split the line at the " symbol'
strList = strList & vbCr & vLine(1) 'read and output the second value'
End If
End If
Loop
If strList = "" Then
FileSearch = "Not Found"
Else
FileSearch = strList
End If
Close #FileNum 'close the file
lbl_Exit:
Exit Function
End Function
Given the reference to a userform then surely this code is intended to do something more useful than pop up a message box e.g. list the items in a list box? In that case set the FileSearch to output the items directly to a list box (here ListBox1) e.g.
Code:
Option Explicit
'Graham Mayor - https://www.gmayor.com - Last updated - 12 Jan 2021
Const FromFile As String = "C:\Working with Textfiles\Original2-Name-Age.txt"
Const WhatToFind As String = "DOB"
Private Sub UserForm_Initialize()
ListBox1.Clear
FileSearch WhatToFind, FromFile
End Sub
Private Function FileSearch(ByVal WhatToFind As String, ByVal FromFile As String)
Dim FileNum As Integer
Dim DataLine As String
Dim strFound As String
Dim bFound As Boolean
Dim vLine As Variant
FileNum = FreeFile()
Open FromFile For Input As #FileNum
Do While Not EOF(FileNum)
Line Input #FileNum, DataLine ' read in data 1 line at a time'
If InStr(1, DataLine, WhatToFind) > 0 Then 'the string is found'
If InStr(1, DataLine, Chr(34)) > 0 Then
strFound = DataLine
vLine = Split(strFound, Chr(34)) 'split the line at the " symbol'
ListBox1.AddItem vLine(1) 'read and output the second value to the listbox'
End If
End If
Loop
Close #FileNum 'close the file
lbl_Exit:
Exit Function
End Function