string - 如何使用 VBA 在众多文本 .log 文件之一中查找特定字符串?

标签 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

我找到了这段代码,但似乎在 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

最佳答案

这段代码:

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

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

  • 如果theString   MAGIC 被发现,则打印文件名立即窗口 (CTRL+G)

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

关于string - 如何使用 VBA 在众多文本 .log 文件之一中查找特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860618/

相关文章:

Java 字符串到 SHA1

python - 如何在 Python 中查找非字母数字字符并将其移动到字符串的末尾

linux - 如何grep两个时间范围之间的日志

linux - 在 bash 脚本中查找命令导致目录出现 "No such file or directory"错误?

c - 如何在 C 中将一个字符串分成多个其他特定长度的字符串?

C++字符串UTF-8编码

Python - 从字符串中删除停用词

excel - VBA Countif 大写

excel - 使用 selenium 检查域

vba - 使用VBA复制垂直列并沿对角线粘贴