2014-01-28 47 views
2

我試圖使用range.find在列中查找值,並從下一列返回匹配值。Excel VBA range.find代理

我使用宏記錄器記錄了find(),它似乎在一段時間內工作正常,但由於某種原因它現在給我一個錯誤。據我所知,我沒有改變任何會影響這段代碼的東西。

這是我

Public Function look_up_id(id, table) 
    Worksheets(table).Activate 
    Cells.Find(What:=id, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ 
     :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
     False, SearchFormat:=False).Activate 

    look_up_id = ActiveCell.Offset(0, 1).Value 
End Function 

現在我得到的錯誤是:

對象變量或帶塊變量未設置

任何想法,這是爲什麼現在發生?

所有的資源我可以找到關於range.find()看起來像我這樣做是正確...

乾杯 - 大衛

回答

4

試試這個

Public Function look_up_id(id, table) As Variant 
    Dim ws As Worksheet 
    Dim aCell As Range 

    look_up_id = "Not Found" 

    Set ws = ThisWorkbook.Sheets(table) 

    With ws 
     Set aCell = .Cells.Find(What:=id, _ 
        LookIn:=xlFormulas, _ 
        LookAt:=xlPart, _ 
        SearchOrder:=xlByRows, _ 
        SearchDirection:=xlNext, _ 
        MatchCase:=False, _ 
        SearchFormat:=False) 

     If Not aCell Is Nothing Then _ 
     look_up_id = aCell.Offset(, 1).Value 
    End With 
End Function 

更多關於.FindHERE

4

嘗試使用此代碼,而不是(在Find不發現了什麼,它返回Nothing,然後你想做某事這樣Nothing.Activate,這觸發錯誤):

Dim res As Range 

Set res = Worksheets(table).Cells.Find(What:=id, LookIn:=xlFormulas, LookAt _ 
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
    False, SearchFormat:=False) 
If Not res Is Nothing Then 
    look_up_id = res.Offset(0, 1).Value 
End If 
+1

+ 1毆打!! :) –

+0

謝謝,這完美的作品。 究竟是你改變了那個導致我的錯誤? –

+0

我將'Find'的結果應用於'res'變量。然後我檢查'res'是否爲'Nothing'(如果是的話,'Find'找不到任何東西),如果它不是'Nothing',函數返回所需的值 –