现在我知道过去已经询问并回答了许多与此错误有关的问题,但这种情况有点奇怪,我无法弄清楚是什么导致了问题。
我编写了一些代码,通过 excel 文件搜索关键字,然后返回有关在何处找到关键字的信息。该代码适用于我输入的大多数关键字,但有些关键字在我运行宏时会产生 91 错误消息。如果有人能弄清楚为什么那会很棒!
代码是:
Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String ' Keyword to search for
Dim strPath As String ' Filepath of folder to search
Dim strFile As String ' current file that the loop is searching through
Dim wOut As Worksheet ' Worksheet to display results
Dim wbk As Workbook ' Workbook to be searched
Dim wks As Worksheet ' Worksheet to be searched
Dim lRow As Integer
Dim rFound As Range
Dim strFirstAddress As String
Application.ScreenUpdating = False
'Change as desired
strPath = "\\ant\dept-eu\LTN1\Techies Information\aa Eng daily log"
strSearch = InputBox("Insert Keyword to search")
Set wOut = Sheet1
lRow = 1
With wOut
Sheet1.Cells.Clear
.Cells(lRow, 1) = "Workbook"
.Cells(lRow, 2) = "Worksheet"
.Cells(lRow, 3) = "Text in Cell"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(strPath)
strFile = Dir(strPath & "\*.xls*")
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "\" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)
For Each wks In wbk.Worksheets ' for each worksheet
Set rFound = wks.UsedRange.Find(strSearch) ' setting variable to first result in find function
If Not rFound Is Nothing Then ' if something is found
strFirstAddress = rFound.Address ' set first address to that cell's address
End If
Do
If rFound Is Nothing Then ' if nothing was found
Exit Do ' exit loop
Else ' if something was found then add the details to the table
lRow = lRow + 1
.Cells(lRow, 1) = wbk.Name
.Cells(lRow, 2) = wks.Name
.Cells(lRow, 3) = rFound.Value
End If
Set rFound = wks.Cells.FindNext(After:=rFound) ' sets rfound vaiable to next found value
Loop While strFirstAddress <> rFound.Address ' once the find function gets back to the first address then exit the loop
Next ' next worksheet in file
wbk.Close (False)
strFile = Dir
Loop
.Columns("A:D").EntireColumn.AutoFit
End With
MsgBox "Done"
ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub
错误发生在循环 While strFirstAddress <> rFound.Address 行
最佳答案
您的代码输入 Do
即使什么也没找到也循环。
尝试类似:
Set rFound = wks.UsedRange.Find(what:=strSearch, lookat:=xlWhole, lookin:=xlValues)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
Do
lRow = lRow + 1
.Cells(lRow, 1) = wbk.Name
.Cells(lRow, 2) = wks.Name
.Cells(lRow, 3) = rFound.Value
Set rFound = wks.Cells.FindNext(After:=rFound)
Loop While strFirstAddress <> rFound.Address
End If
最好指定
Find()
的附加参数。 ,因为它们的值将在使用之间保持不变(即使是通过 Excel UI 使用),所以如果你忽略它们,你永远不能依赖将使用的值。
关于vba - 异常 - vba 错误 : object variable or with block variable not set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39252534/