View Single Post
 
Old 01-11-2021, 03:57 AM
SamDsouza SamDsouza is offline Windows 10 Office 2013
Advanced Beginner
 
Join Date: Aug 2019
Posts: 71
SamDsouza is on a distinguished road
Default Subscript out of Range Error when searched for string and its line number in Text File

Hello

Am Getting Subscript out of Range Error using the following code

if the below defined in Function FileSearch(.........
WhatToFind = "Age"
FromFile = "C:\Working with Textfiles\Original2-Name-Age.txt"
Msgbox FileSearch(WhatToFind, FromFile)

I get Error Subscript out of Range Error

if used in UF_Initialize then
Msgbox FileSearch(WhatToFind, FromFile) displays blank


Code:
Private Sub UserForm_Initialize()
Dim WhatToFind As String, FromFile As String

WhatToFind = "Age"
FromFile = "C:\WOrking with Textfiles\Original2-Name-Age.txt"
MsgBox FileSearch(WhatToFind, FromFile)
'''''MSGBOX IS DISPLAYED BLANK

End Sub

Private Function FileSearch(ByVal WhatToFind As String, ByVal FromFile As String) As String
Dim objFSO As Object
Dim objTextFile As Object
Dim lngCount As Long, i As Long
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)
        lngCount = lngCount + 1    'increment a counter'
        Line Input #FileNum, DataLine    ' read in data 1 line at a time'
        If InStr(1, DataLine, WhatToFind) > 0 Then    'the string is found'
            bFound = True    'set a boolean value to true'
            Exit Do    'and stop the loop'
        End If
    Loop
    Close #FileNum    'close the file
    If bFound = True Then    'The text string was found'
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set objTextFile = objFSO.OpenTextFile(FromFile, 1)
        'Read through the file line by line to the line after the found line'
        For i = 1 To lngCount + 1
            strFound = objTextFile.ReadLine    'and note the content of the line'
        Next i
        vLine = Split(strFound, Chr(34))    'split the line at the " symbol'
        FileSearch = vLine(1)    'read and output the second value'
        objTextFile.Close    'close the file'
        Set objFSO = Nothing
        Set objTextFile = Nothing
    Else    'The text was not found'
        FileSearch = "Not found" 'tell the user'
    End If
lbl_Exit:
    Exit Function
End Function
Will appreciate your help in correcting my mistake
Thanks
SamD
Reply With Quote