2012-08-15 41 views
1

我在查找用戶ID列表。但是有些用戶不再存在。我試過test方法,on error go to方法和if err.number<> 0 then方法。我仍然收到Run-time error '91': object variable or with block variable not set。該號碼不存在於列表中。下面是我的代碼,有幾個沒有結果的嘗試項目找不到「查找」vba

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 ...」

回答

3

我相信你需要重新調整它只是一點點。這是不是最好的實踐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

+0

如果我在for循環中,「on error resume next」是否恢復for循環的下一步? – orangehairbandit 2012-08-15 17:08:23

+1

正確 - 它基本上就像一切都好,這是你需要小心使用它的一個原因。有關處理錯誤的不同方法的一個很好的解釋,請查看http://www.cpearson.com/excel/errorhandling.htm。 – RocketDonkey 2012-08-15 17:12:21

+0

非常感謝! – orangehairbandit 2012-08-15 17:15:33

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/

+0

你發佈了這個完全符合我開始寫同樣的... :-) – enderland 2012-08-15 16:13:37

9

你會想要做一些不同於有消息框的東西,據推測。

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