如何使用 VBA 在多个文本 .log 文件之一中找到特定字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17860618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find a specific string in one of many text .log files using VBA?
提问by Kairan
This is the code I have so far to find all the log files in a folder. But I need to be able to find a specific string in each file, if it is found in one file, stop looking and exit the loop and report back what filename it was in.
这是我迄今为止在文件夹中查找所有日志文件的代码。但是我需要能够在每个文件中找到一个特定的字符串,如果在一个文件中找到它,停止查找并退出循环并报告它所在的文件名。
There seems to be so many different ways to open a file and search it that I do not know which is the best and I do not typically use VBA but it is all I have access to at the moment.
似乎有很多不同的方法可以打开和搜索文件,我不知道哪种方法最好,而且我通常不使用 VBA,但目前我只能使用 VBA。
On a side note, there would be a max of 36 log files and each file max of 5MB each.
附带说明一下,最多有 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
I had found this code but seems in 2007+ versions of Excel VBA Application.FileSearch was eliminated:
我找到了这段代码,但似乎在 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
回答by
This code:
这段代码:
looks for all
*.log
file extensionsC:\MyDownloads\
opens each
*.log
file and reads each lineif
theString
MAGICis found, then it prints the file namein theImmediate Widnow
(CTRL+G)
查找所有
*.log
文件扩展名C:\MyDownloads\
打开每个
*.log
文件并读取每一行如果找到MAGIC,则在( + ) 中打印文件名
theString
Immediate Widnow
CTRLG
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
回答by David Zemens
Application.FileSearch
was removed in 2007+ versions of Excel. A while back, I found this function which replicates it. I have used it on occasion, but ordinarily I think I just use FileSystemObject
or Dir
.
Application.FileSearch
已在 2007+ 版本的 Excel 中删除。不久前,我发现了这个复制它的功能。我偶尔使用过它,但通常我认为我只是使用FileSystemObject
or Dir
。
Sub FileSearch()
'
' Example of FileSearchByHavrda procedure calling as replacement of missing FileSearch function in the newest MS Office VBA
' 01.06.2009, Author: P. Havrda, Czech Republic
'
Dim sDir As String
sDir = Range("K3").Value
Dim FileNameWithPath As Variant
Dim ListOfFilenamesWithParh As New Collection ' create a collection of filenames
Dim rCount As Long 'row counter
' Filling a collection of filenames (search Excel files including subdirectories)
Call FileSearchByHavrda(ListOfFilenamesWithParh, sDir, "*.xls", False)
' Print list to immediate debug window and as a message window
For Each FileNameWithPath In ListOfFilenamesWithParh ' cycle for list(collection) processing
Debug.Print FileNameWithPath & Chr(13)
'MsgBox FileNameWithPath & Chr(13)
rCount = Application.WorksheetFunction.CountA(Range("A:A")) + 1
ActiveSheet.Cells(rCount, 1).Value = FileNameWithPath
Next FileNameWithPath
' Print to immediate debug window and message if no file was found
If ListOfFilenamesWithParh.Count = 0 Then
Debug.Print "No file was found !"
MsgBox "No file was found !"
End If
End Sub
'//------------------------------------------------------------------------------------------------
Private Sub FileSearchByHavrda(pFoundFiles As Collection, pPath As String, pMask As String, pIncludeSubdirectories As Boolean)
'
' Search files in Path and create FoundFiles list(collection) of file names(path included) accordant with Mask (search in subdirectories if enabled)
' 01.06.2009, Author: P. Havrda, Czech Republic
'
Dim DirFile As String
Dim CollectionItem As Variant
Dim SubDirCollection As New Collection
' Add backslash at the end of path if not present
pPath = Trim(pPath)
If Right(pPath, 1) <> "\" Then pPath = pPath & "\"
' Searching files accordant with mask
DirFile = Dir(pPath & pMask)
Do While DirFile <> ""
pFoundFiles.Add pPath & DirFile 'add file name to list(collection)
DirFile = Dir ' next file
Loop
' Procedure exiting if searching in subdirectories isn't enabled
If Not pIncludeSubdirectories Then Exit Sub
' Searching for subdirectories in path
DirFile = Dir(pPath & "*", vbDirectory)
Do While DirFile <> ""
' Add subdirectory to local list(collection) of subdirectories in path
If DirFile <> "." And DirFile <> ".." Then If ((GetAttr(pPath & DirFile) And vbDirectory) = 16) Then SubDirCollection.Add pPath & DirFile
DirFile = Dir 'next file
Loop
' Subdirectories list(collection) processing
For Each CollectionItem In SubDirCollection
Call FileSearchByHavrda(pFoundFiles, CStr(CollectionItem), pMask, pIncludeSubdirectories) ' Recursive procedure call
Next
End Sub
回答by rajjain4900
i didnt go thro the second ans, but in the first ans, something is flawed! in the line
我没有通过第二个答案,但是在第一个答案中,有些东西是有缺陷的!在行中
path = "C:\MyDownloads\*.log"
path = "C:\MyDownloads\*.log"
dont use the "*.log" thing, the path should be just "C:\MyDownloads\"
不要使用“*.log”的东西,路径应该只是“C:\MyDownloads\”
回答by FreeSoftwareServers
Try this:
尝试这个:
来源:https: //social.msdn.microsoft.com/Forums/en-US/62fceda5-b21a-40b6-857c-ad28f12c1b23/use-excel-vba-to-open-a-text-file-and-search- it-for-a-specific-string?forum=isvvba
Sub SearchTextFile()
Const strFileName = "C:\test.txt"
Const strSearch = "TEST"
Dim strLine As String
Dim f As Integer
Dim lngLine As Long
Dim blnFound As Boolean
f = FreeFile
Open strFileName For Input As #f
Do While Not EOF(f)
lngLine = lngLine + 1
Line Input #f, strLine
If InStr(1, strLine, strSearch, vbBinaryCompare) > 0 Then
MsgBox "Search string found in line " & lngLine, vbInformation
blnFound = True
Exit Do
End If
Loop
Close #f
If Not blnFound Then
MsgBox "Search string not found", vbInformation
End If
End Sub