我正在寻找列表中的用户ID#。但是有些用户不再存在。我尝试了test
方法,on error go to
方法和if err.number<> 0 then
方法。我仍然收到Run-time error '91': object variable or with block variable not set
。该号码不存在于列表中。下面是我的代码,有几个徒劳无功的尝试
On Error GoTo errorLn
If Err.Number <> 0 Then
GoTo errorLn
End If
Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Select
还有哪些其他选择?或者我错放了“错误”的界限?我在“cells.Find ...”之前和之后尝试过它。
答案 0 :(得分:10)
你可能想要做一些不同于消息框的事情。
Dim myCell As Range
Set myCell = Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If (Not myCell Is Nothing) Then
MsgBox "something!"
Else
MsgBox "nothing"
End If
答案 1 :(得分:4)
我相信你需要重新调整它一点点。使用On Error Resume Next
处理错误不是最佳做法,但您可以尝试这样做:
On Error Resume Next
Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Select
If Err.Number <> 0 Then
'''Do your error stuff'''
GoTo errorLn
Else
Err.Clear
End If
这对你的情况有用吗?
答案 2 :(得分:4)
试试这个
Sub Sample1()
Dim oSht As Worksheet
Dim uSSO As String
Dim aCell As Range
On Error GoTo Whoa
'~~> Change this to the relevant sheet
Set oSht = Sheets("Sheet1")
'~~> Set User ID here
uSSO = "User ID"
Set aCell = oSht.Cells.Find(What:=uSSO, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> Check if found or not
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address
Else
MsgBox "Value Not found"
End If
Exit Sub
Whoa:
MsgBox Err.Description
End Sub
我还建议您阅读我已涵盖.Find
和.FindNext
主题:.Find和.FindNext在Excel VBA中
链接:http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/
答案 3 :(得分:0)
为了后人,这就是你如何处理错误处理(来自:http://www.mrexcel.com/forum/excel-questions/519070-visual-basic-applications-error-handling-when-dealing-cells-find.html)。
Dim rngFound As Range
Set rngFound = Sheets("WhateverSheet").UsedRange.Find(What:="SoughtValue",LookIn:=xlFormulas)
If Not rngFound Is Nothing Then
'you found the value - do whatever
Else
' you didn't find the value
End if