2017-07-14 30 views
0

我敢打賭,這是簡單的。即使我已經研究了很多,並嘗試了幾種方法,但仍然出現運行時錯誤424.VBA發現問題 - 當沒有發現錯誤

代碼是查找用戶輸入的數字。如果數字在數據集中,我想做一件事,但如果數字不在數據集中,我想做其他事情。

代碼如下。

Sub Test() 

Dim Material As String 
Dim cell As Range 

    Material = InputBox("Enter BIS # for material type") 

    Range("A7:a40").Select 

     Set cell = Selection.Find(What:=Material, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _, SearchFormat:=False).Activate 
    If cell Is Nothing Then 
     MsgBox "Boo" 

    Else 
     MsgBox "Great" 

End If 

End Sub 

回答

2

不能調用Activate如果Find回報什麼,這樣會導致錯誤。此外,Activate是一個子函數,而不是函數,所以您不能將cell設置爲其返回值。

注意:有沒有必要SelectRange("A7:A40")Find功能工作。您可以完全限定的Find功能是通過Range("A7:A40").Find...

搜索的特定值的Range試試這個:

Sub Test() 
    Dim Material As String 
    Dim cell As Range 

    Material = InputBox("Enter BIS # for material type")  
    Set cell = Range("A7:A40").Find(What:=Material, LookIn:=xlValues, LookAt:=xlWhole, _ 
         SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)    
    If cell Is Nothing Then ' <-- this lines checks if Find failed to find a match 
     MsgBox "Boo" 
    Else 
     cell.Activate 
     MsgBox "Great" 
    End If 
End Sub 
+0

不錯,我已經編輯你的答案,因爲沒有必要'Select'查找功能的'範圍'工作 –

+0

有時選擇是用戶體驗的一部分,所以我沒有碰它。但我確定OP可以弄清楚你做了什麼,現在他們有了選擇。 –

+0

工程就像一個魅力。非常感謝! –