Search code examples
vbastringloopstextdirectory

Error62: Input Past End of File on VBA Script to Search Directory for Files Containing Keyword


Hoping someone might be able to point out where I've gone astray.

I created a script to search through all files within a directory and return the file path and file name of any that contain a particular keyword, which has been entered into a cell. The script seems to work on a test folder I set up on my desktop, but when I try to search another directory that contains far more files, then I get the "Input Past End of File" error.

Can anyone see where I've gone wrong here? Script is below:

Sub findfiles()

    Dim startpath As String 'this is the starting directory path
    startpath = Cells(1, 2).Value
    Dim keyword, text As String
    keyword = Cells(2, 2).Value
    Dim returnpatharr() As Variant 'array containing the filepaths for files containing the keyword
    Dim returnfilearr() As Variant 'array containing the filenames for files containing the keyword
    Dim i As Integer
    i = 0
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Set objFolder = fso.GetFolder(startpath)
    
    Set objSubFolders = objFolder.Subfolders
    
    For Each SubFolder In objSubFolders
        Set objFolderFiles = SubFolder.Files
        For Each File In objFolderFiles
            Dim txt As Byte
            txt = FreeFile
            Open File For Input As #txt
            text = Input(LOF(txt), txt)
                If InStr(1, text, keyword, 1) > 0 Then
                ReDim Preserve returnpatharr(i)
                returnpatharr(i) = File.Path
                ReDim Preserve returnfilearr(i)
                returnfilearr(i) = File.Name
                Debug.Print i
                Debug.Print File.Name
                Debug.Print File.Path
                i = i + 1
                End If
            Close #txt
        Next File
    Next SubFolder

Dim last As Integer
last = 4 + i
On Error GoTo msg

Range("A5:A" & last).Value = Application.WorksheetFunction.Transpose(returnfilearr)
Range("B5:B" & last).Value = Application.WorksheetFunction.Transpose(returnpatharr)

Done:
Exit Sub

msg:

MsgBox ("No Results")

End Sub

Solution

  • My guess is that a file may contain characters, such as Null characters, that LOF() counts, but Input() ignores. And so it tries to read past the end of the file, since the number of total bytes specified by LOF() include those characters. Try the following instead...

        '
        '
        '
    
        Dim fileNum As Long
        Dim text As String
        
        fileNum = FreeFile
        
        Open File For Binary Access Read As #fileNum
            text = Space$(LOF(fileNum))
            Get #fileNum, , text
                'etc
                '
                '
        Close #fileNum
        
        '
        '
        '