method range of object _global failed in excel macro

前端 未结 2 1911
北荒
北荒 2021-01-28 16:02

This is my code for finding a value in excel.if Paint Shop is not found then it will get the method range of object _global failed. I\'m new to excel m

相关标签:
2条回答
  • 2021-01-28 16:25

    Try this:

    Dim Result As Variant
    If Not VBA.IsError(Application.Match(...)) Then
        Result = Application.Match(...)
    End If
    

    This tries the match and if there is an error on the function it will not assign a result.

    Alternatively:

    Dim rng As Range: Set rng = Sheet1.Range("A2:A10")
    Dim Result As Variant
    
    Result = Application.Match("A", rng, 0)
    If Not VBA.IsError(Result) Then
        Debug.Print (Result)
    End If
    

    Note: be sure to use Application.Match rather than Application.WorksheetFunction.Match for this to work.

    WorksheetFunction.Match Method (Excel)

    0 讨论(0)
  • 2021-01-28 16:44

    To handle this scenario, try this:

    Dim myvalue
    
    On Error Resume Next
    myvalue = WorksheetFunction.Match("Paint Shop", Range(col & x, col & y), 0)
    On Error Goto 0
    
    If Not IsEmpty(myvalue) Then
       paint = myvalue
    Else
       paint = 2000
    End If
    

    You incorporate Error Handling routine OERN to check if the worksheet function fails.
    If it does, myvalue will not be initialized and you can check if it is empty or not.
    Also take note that i declared myvalue as Variant data type.
    Reason is for IsEmpty to evaluate it correctly.

    0 讨论(0)
提交回复
热议问题