项目未找到"查找" VBA

时间:2012-08-15 16:03:17

标签: vba excel-vba find excel

我正在寻找列表中的用户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 ...”之前和之后尝试过它。

4 个答案:

答案 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

这对你的情况有用吗?

来源http://www.mrexcel.com/forum/excel-questions/143988-check-if-value-exists-visual-basic-applications-array.html

答案 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