如何使用VBA在许多文本.log文件中找到特定字符串?

Kai*_*ran 4 string vba find text-files

这是我到目前为止找到文件夹中所有日志文件的代码.但我需要能够在每个文件中找到一个特定的字符串,如果它在一个文件中找到,停止查找并退出循环并报告它所在的文件名.

似乎有很多不同的方法来打开文件并搜索它我不知道哪个是最好的,我通常不使用VBA但是我现在只能访问它.

另外,最多可以有36个日志文件,每个文件最多5MB.

Sub StringExistsInFile()
    Dim TheString As String

    TheString = "MAGIC"

    Dim StrFile As String
    StrFile = Dir("c:\MyDownloads\*.log")
    Do While Len(StrFile) > 0
        'Find TheString in the file
        'If found, debug.print and exit loop
    Loop
End Sub
Run Code Online (Sandbox Code Playgroud)

我找到了这个代码,但似乎在2007 +版本的Excel VBA Application.FileSearch被淘汰了:

Sub FindText()
'http://www.mrexcel.com/forum/excel-questions/68673-text-file-search-excel-visual-basic-applications.html

Dim i As Integer

'Search criteria
With Application.FileSearch
    .LookIn = "c:\MyDownloads" 'path to look in
    .FileType = msoFileTypeAllFiles
    .SearchSubFolders = False
    .TextOrProperty = "*MAGIC*" 'Word to find in this line
    .Execute 'start search

'This loop will bring up a message box with the name of
'each file that meets the search criteria
    For i = 1 To .FoundFiles.Count
        MsgBox .FoundFiles(i)
    Next i

End With

End Sub
Run Code Online (Sandbox Code Playgroud)

小智 5

这段代码:

  • 查找所有*.log文件扩展名 C:\MyDownloads\

  • 打开每个*.log文件并读取每一行

  • 如果找到MAGIC,则在(+ )中打印文件名theString   Immediate WidnowCTRLG

Sub StringExistsInFile()
    Dim theString As String
    Dim path As String
    Dim StrFile As String
    Dim fso As New FileSystemObject
    Dim file As TextStream
    Dim line As String

    theString = "MAGIC"
    path = "C:\MyDownloads\*.log"
    StrFile = Dir(path & "*.log")

    Do While StrFile <> ""

        'Find TheString in the file
        'If found, debug.print and exit loop

        Set file = fso.OpenTextFile(path & StrFile)
        Do While Not file.AtEndOfLine
            line = file.ReadLine
            If InStr(1, line, theString, vbTextCompare) > 0 Then
                Debug.Print StrFile
                Exit Do
            End If
        Loop

        file.Close
        Set file = Nothing
        Set fso = Nothing

        StrFile = Dir()
    Loop
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用`If Instr(1,file.ReadAll,theString,vbTextCompare)> 0然后Debug.Print StrFile`而不是`Do While`循环? (3认同)