exception – vba错误:对象variables或未设置块variables

现在我意识到,这个错误的许多问题已经被问及过去的答案,但这个案件有点危险,我不知道是什么原因造成的问题。

我已经写了一些代码,通过excel文件search关键字,然后返回关于它在哪里find关键字的信息。 该代码工作正常,我input的大多数关键字,但有一些当我运行macros产生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 

在循环中发生错误,而strFirstAddress <> rFound.Address行

即使没有find任何东西,您的代码也会进入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使用也是如此),因此,如果忽略它们,将永远无法使用哪些值。