VBA对象需要运行时错误91

时间:2013-11-24 07:15:29

标签: vba excel-vba excel

我正在使用宏来查找不匹配。当发现不匹配时,在单元格中放置“x”。我的宏查找带有“x”的第一个单元格,然后打开一个msgbox,说有不匹配。如果没有发现不匹配,我希望它退出。但是,如果没有不匹配,我得到:运行时错误91:未设置对象变量(错误91)

这是错误的代码:

Range(Selection, Selection.End(xlDown)).Select

If Selection.Find(What:="x", After:=ActiveCell, LookIn:=xlValues, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=False).Activate = True Then


 MsgBox ("There is an issue with Validation for this file. Please open the xx_xxxx.csv file and verify that you are entering the correct data.")
Else: Exit Sub

End If

感谢您提出任何建议

1 个答案:

答案 0 :(得分:2)

你应该用这个:

Sub sof20172114Findx()
  Dim objRange

  Range(Selection, Selection.End(xlDown)).Select

  Set objRange = Selection.Find(what:="x", After:=ActiveCell, LookIn:=xlValues _
    , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext _
    , MatchCase:=False, SearchFormat:=False)

  If (objRange Is Nothing) Then
    'MsgBox "No x found."
    Exit Sub
  Else
    MsgBox "There is an issue with Validation for this file. Please open the xx_xxxx.csv file and verify that you are entering the correct data."
    objRange.Activate
  End If
  Set objRange = Nothing
End Sub

如果找不到 x stirng, Selection.Find()返回Nothing,因为 Nothing 没有.Activate方法,因此您的原始代码会出错。