在文件夹中搜索关键字 [英] Search a folder for keyword
问题描述
我想在文件夹中搜索关键字燃料",以将信息从返回的文件中拉到数据"表中.
I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.
例如,我有一个文件夹的星期编号(跨年1到52,因此在新的一年中将包含一个文件夹,但是会随着年份的推移而建立).
我在此文件夹中搜索所有包含单词"fuel"的.doc文件.
您可以通过Windows搜索输入"fuel"来完成此操作.在右上角的搜索功能中,它将显示所有文件名和所有包含燃料"一词的文件.
For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.
我用它来搜索名称中带有"fuel"但内部没有"fuel"的文件.
I have this for searching for a file that has 'fuel' in its name, but not inside it.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "fuel") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub
推荐答案
虽然不是特别漂亮,但是认为这样应该可以:
It isn't particularly pretty, but think something like this should work:
Sub loopThroughFiles()
Dim file As String
file = FindFiles("C:\TestFolder", "fuel")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Sheell Command And Get Output
Dim files As String
Dim lines
files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files, vbCrLf)
' Look for matching files
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (line = target) Then
FindFiles = curFile
Exit Function
End If
Next
FindFiles = ""
End Function
使用FIND命令行,然后读取输出(因此需要使用Wscript.Shell)并返回第一个匹配项;如果找不到文件,则返回空字符串
Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found
在@BLUEPIXY的命令FINDSTR/M之后,该函数可以替换为:
Following @BLUEPIXY's command FINDSTR /M the function can be replaced by:
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function
这篇关于在文件夹中搜索关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!