VBA宏搜索文件夹中的关键字

Jam*_*ieB 6 excel vba excel-vba

我正在构建一个VBA宏,它将"搜索"一个文件夹中的关键字术语"fuel",并从所有返回的文件中提取所有信息并将它们放入"数据"表中.

例如,我有一个文件夹周数(1 - 52年跨越,所以在新的一年,这将只包含一个文件夹,但随着年份的推移将构建和构建)所以我在这个文件夹中搜索所有.doc文件包含单词'燃料'.您只需在顶角的搜索功能中键入"fuel"即可通过Windows搜索执行此操作,它将显示所有文件名,所有文件中都包含"燃料"字样.

我目前有,但这只是搜索一个在其名称中有"燃料"的文件,而不是包含它的内容.

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
Run Code Online (Sandbox Code Playgroud)

我已经做了一些搜索,但我无法得到任何工作:(.我认为我的VB技能需要复习.

先谢谢你.

JB

JDu*_*ley 6

这不是特别漂亮,但想想这样的事情应该有效:

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
Run Code Online (Sandbox Code Playgroud)

使用FIND命令行然后读取输出(因此需要使用Wscript.Shell)并返回第一个匹配,如果没有找到文件则返回空字符串

按照@ BLUEPIXY的命令FINDSTR/M,该函数可以替换为:

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
Run Code Online (Sandbox Code Playgroud)