这是我迄今为止查找文件夹中所有日志文件的代码。但我需要能够在每个文件中找到特定的字符串,如果在一个文件中找到它,则停止查找并退出循环并报告它所在的文件名。
打开文件和搜索文件的方法似乎有很多,我不知道哪种方法最好,而且我通常不使用 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/