这是我迄今为止查找文件夹中所有日志文件的代码。但我需要能够在每个文件中找到特定的字符串,如果在一个文件中找到它,则停止查找并退出循环并报告它所在的文件名。
打开文件和搜索文件的方法似乎有很多,我不知道哪种方法最好,而且我通常不使用 VBA,但目前我只能使用 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
文件并读取每一行
if theString
MAGIC is found, then it prints the file name in the Immediate Widnow
(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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)