解决VBA崩溃后的运行时错误“ 91”,该崩溃在崩溃前有效

时间:2020-04-30 21:53:30

标签: excel vba

我希望有人能帮助我。几乎一切都做完了,我的Excel崩溃了。崩溃之前,一切正常。现在,在此行“ ActiveCell.Find(i).Select”上收到运行时错误。 ---下面是我的过程,该过程在文件中搜索特定的值,找到它,然后转到包含该值的最后一行。

Sub FindValue_Raw()

Dim Value As Variant
Dim Sheetname As String
Dim lastCell As String
Dim x As Integer
Dim iVal As Integer
Dim i As Variant

Value = InputBox("Enter Value:", "Input")

Sheetname = "Sheet2"

Dim Cell As Variant

    'Search in Column A | MatchCase True = case sensitive of raw file
    Set Cell = Sheets(Sheetname).Columns("C:C").Find(What:=Value, After:=Sheets(Sheetname).Range("C1"), LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=True, SearchFormat:=False)

If Not Cell Is Nothing Then
    'Find how many rows have this value
     iVal = Application.WorksheetFunction.CountIf(Range("C1:C480000"), Cell)
    'find the last line with this value
     Do While x < iVal
        'Set where the curse is after it finds value
         i = Cell
        **'Select first instance of that value -THIS IS WHERE THE ERROR IS
         **ActiveCell.Find(i).Select****
         'Finds the last Reference address
         lastCell = ActiveCell.Address(False, False)
         'Highlights cell
        ' ActiveCell.Interior.ColorIndex = 4
          x = x + 1
    Loop
    ' Next
     ActiveCell.Offset(1, 0).Select
    'Value is found, Highlight Cell
    'Sheets(Sheetname).Range(Cell.Address).Interior.ColorIndex = 4
Else
    'Value Not found
    MsgBox "Not Found"

End If

End Sub

1 个答案:

答案 0 :(得分:1)

您正在根据Range.Find的结果进行成员调用。当Range.Find找不到要查找的内容时,它将返回Nothing-并且您无法在.Select上调用Nothing

这正是您要防止的事情:

Set Cell = Sheets(Sheetname).Columns("C:C").Find(...)
If Not Cell Is Nothing Then
    '...
End If

您需要在这里做同样的事情:

ActiveCell.Find(i).Select

也就是说,声明一个局部变量并验证Range.Find是否成功

Dim somethingMeaningful As Range
Set somethingMeaningful = ActiveCell.Find(i) '<~ TODO recondiser whether ActiveCell is really needed
If Not somethingMeaningful Is Nothing Then
    somethingMeaningful.Select '<~ TODO reconsider whether this is really needed
End If

旁注Rubberduck(由我管理的免费开放源代码VBE外接程序项目)可以警告此类未经保护的Range.Find调用(尽管它们必须提前绑定),隐式{ {1}}和ActiveSheet参考以及其他代码问题。

相关问题