5

我正在从列表中查找用户 ID #s。然而,一些用户不再存在。我试过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

4 回答 4

13

大概你会想做一些与消息框不同的事情。

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
于 2012-08-15T16:12:36.713 回答
5

我相信你需要稍微重组它。使用 处理错误不是最佳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

于 2012-08-15T16:08:32.087 回答
5

尝试这个

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

主题: Excel VBA 中的 .Find 和 .FindNext

链接https ://web.archive.org/web/20160316214709/https://siddharthout.com/2011/07/14/find-and-findnext-in-excel-vba/

于 2012-08-15T16:09:42.477 回答
1

只是为了后代,这就是你如何在没有错误处理的情况下做到这一点(来自:http ://www.mrexcel.com/forum/excel-questions/519070-visual-basic-applications-error-handling-when-dealing-细胞-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
于 2014-12-09T09:49:46.037 回答