基本上,我尝试使用VBA在文件夹和子文件夹中的word文件中搜索字符串。
我找到了下面的宏,但它引发了这个错误。
运行时错误“5”:无效的过程调用或参数
调试后发现错误就在这一行
subFolder = Dir
Option Explicit
Option Compare Text
Sub SearchWordFilesInFolder(ByVal folderPath As String, ByVal searchText As String)
Dim ws As Worksheet: Set ws = ActiveSheet
Dim wordApp As Object, wordDoc As Object
Dim subFolder As String, myFile As String, i As Long
' Initialize Word application
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = False ' Set to True if you want to see Word
' Loop through each file in the folder
myFile = Dir(folderPath & "*.doc*")
i = 1
Do While myFile <> ""
' Open the Word file
Set wordDoc = wordApp.Documents.Open(folderPath & myFile)
' Search for the text
With wordDoc.Content.Find
.Text = searchText
If .Execute Then
ws.Cells(i, 1).Value = folderPath & myFile: i = i + 1
End If
End With
' Close the Word file
wordDoc.Close False
' Get the next file in the folder
myFile = Dir
Loop
' Close Word application
wordApp.Quit
' Loop through each subfolder and call the function recursively
subFolder = Dir(folderPath & "*", vbDirectory)
Do While subFolder <> ""
If subFolder <> "." And subFolder <> ".." Then
If (GetAttr(folderPath & subFolder) And vbDirectory) = vbDirectory Then
SearchWordFilesInFolder folderPath & subFolder & "\", searchText
End If
End If
subFolder = Dir
Loop
End Sub
Sub StartSearch()
Dim folderPath As String, searchText As String
' Set the folder path where your Word files are located
folderPath = "\\Path of Parent Folder\"
' Set the search text
searchText = "Converted"
' Call the search function
SearchWordFilesInFolder folderPath, searchText
End Sub
这是搜索子文件夹的非递归方法,使用
Dir()
和集合作为队列:
'Return a collection of file objects given a starting folder and a file pattern
' e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetMatches(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Collection
Dim f, fldr, colFiles As New Collection, colSub As New Collection
colSub.Add startFolder
Do While colSub.Count > 0
fldr = colSub(1) 'next folder to process
colSub.Remove 1 'remove from queue
If Right(fldr, 1) <> "\" Then fldr = fldr & "\"
'Debug.Print "Processing: " & fldr
f = Dir(fldr & filePattern, vbNormal)
Do While Len(f) > 0
'Debug.Print , fldr & f
colFiles.Add fldr & f
f = Dir()
Loop
f = Dir(fldr & "*", vbDirectory)
Do While Len(f) > 0
If f <> "." And f <> ".." Then
If (GetAttr(fldr & f) And vbDirectory) = vbDirectory Then
colSub.Add fldr & f
End If
End If
f = Dir()
Loop
Loop
Set GetMatches = colFiles
End Function
我认为它比使用 FilesystemObject 更快...