문제

Im trying to use range.find to look up a value within a column, and return the matching value from the next column.

I recorded the find() using the macro recorder, which seemed to work fine for a while, but for some reason it's now giving me an error. As far as I can tell I haven't changed anything that should affect this bit of code.

This is what I have

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

The error I'm now getting is:

Object variable or With block variable not set

Any idea why this is now happening?

All the resources I can find on range.find() look like I'm doing it right...

Cheers - David

도움이 되었습니까?

해결책

Try this

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

More on .Find HERE

다른 팁

Try to use this code instead (when Find doesn't find anything, it returns Nothing and then you tried to do sth like this Nothing.Activate, and this triggers an error):

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top