item not found in “Find” vba

后端 未结 4 644
长发绾君心
长发绾君心 2020-12-17 03:08

I\'m looking for user ID #s from a list. However some users no longer exist. I\'ve tried the test method, the on error go to method, and if

相关标签:
4条回答
  • 2020-12-17 03:46

    Try this

    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
    

    I also would recommend reading this link where I have covered .Find and .FindNext

    Topic: .Find and .FindNext In Excel VBA

    Link: http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/

    0 讨论(0)
  • 2020-12-17 03:49

    You will want to do something different than have message boxes, presumably.

    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
    
    0 讨论(0)
  • 2020-12-17 03:53

    I believe you'll need to restructure it just a little bit. It is not the best practice to handle errors with On Error Resume Next, but you could try this:

    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
    

    Does that work for your situation?

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

    0 讨论(0)
  • 2020-12-17 03:58

    Just for posterity, this is how you do it w/out error handling (from: 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
    
    0 讨论(0)
提交回复
热议问题