Excelでフォルダ内文字列検索ソフトを作ってみよう

Step 5 ファイルを開き、検索文字の有無検索

初めに、ファイルを開き一気に読みます。
読み込んだ内容に入力された検索文字が含まれているか調べます。
もし、含まれない場合は次のファイルへ移動し、含まれていると1行づつ読みます。


Homeへ > Excelでアプリケーションソフト2 > フォルダ内文字列検索ソフト

コード

下記のVBAコードを追加してください。

'ファイルを開き読む
Private Function MyFileRead(fname As String) As Boolean
    Dim fn As Long
    Dim buf As String
    Dim tmp As String
    
    '一気に読み込みチェック
    fn = FreeFile
    buf = Space(FileLen(fname))
    Open fname For Binary As #fn
        Get #fn, , buf
    Close #fn
    
    If InStr(1, buf, TextBox1.Value) = 0 Then
        MyFileRead = False
        Exit Function
    End If
    
    MyFileRead = True
    fn = FreeFile
    'ファイルを開く
    Open fname For Input As #fn
        
        Do Until EOF(fn)
            '一行読込み
            Line Input #fn, tmp
        Loop
    Close #fn

End Function



下記のVBAコードに変更してください。

Private Sub ExFolderSearchSub(ByVal tPath As Folder, ByRef lrow As Long, ByVal lCol As Long)
    Dim tInPath As Folder
    Dim tFile As File
    Dim s1 As String
    Dim s2 As String
    Dim sPush As String
        
    lPathCount = lPathCount + 1
    
    'サブフォルダ内の探索
    For Each tInPath In tPath.SubFolders
        '再帰呼び出し
        Call ExFolderSearchSub(tInPath, lrow, lCol)
    Next tInPath
    
    'フォルダ内のファイルを表示
    For Each tFile In tPath.Files
        s1 = LCase(ExGetExt(tFile.Name))
        If s1 = "txt" Or s1 = "html" Or s1 = "htm" Then
            s2 = tPath.Path
            If Right(s2, 1) <> "\" Then s2 = s2 & "\"
            MyFileRead s2 & tFile.Name
            
            If sPush <> tPath.Name Then
                lrow = lrow + 1
                Cells(lrow, lCol).Value = tPath.Path
                sPush = tPath.Name
            End If
            lrow = lrow + 1
            lFileCount = lFileCount + 1
            'セル内右寄せ
            Cells(lrow, lCol).HorizontalAlignment = xlHAlignRight
            Cells(lrow, lCol) = "∟"
            Cells(lrow, lCol + 1) = tFile.Name & " (" & tFile.DateLastModified & ")"
        End If
    Next tFile
    Set tPath = Nothing
End Sub


Homeへ > Excelでアプリケーションソフト2 > フォルダ内文字列検索ソフト

■■■
このサイトの内容を利用して発生した、いかなる問題にも一切責任は負いませんのでご了承下さい
■■■
当ホームページに掲載されているあらゆる内容の無許可転載・転用を禁止します


Copyright (c) Excel-Excel ! All rights reserved