VBAmacrossearch关键字的文件夹

我正在build立一个VBAmacros,它将'search'关键字术语'燃料'的文件夹,并从所有返回的文件中提取所有的信息,并把它们放入一个'数据'表。

例如,我有一个文件夹星期数(1 – 52跨年,所以在新的一年,这将只包含一个文件夹,但将build立和build设的一年),所以我search这个文件夹的所有.doc文件包含一词“燃料”。 您只需在顶部的searchfunction中input“fuel”,然后显示所有文件名,所有文件中包含“fuel”字样,就可以通过windowssearch来完成。

我目前有,但这只是寻找一个文件,在其名称“燃料”,而不是包含它的insisde。

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 

我已经做了一些寻找这个,但我不能得到任何东西的工作:(我的VB技能需要一个复习,我想。

先进的谢谢你。

JB

这不是特别漂亮,但认为这样的事情应该工作:

 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)并返回第一个匹配,如果没有find文件,则返回空string

以下@ BLUEPIXY的命令FINDSTR / M的function可以被replace为:

 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