简体   繁体   中英

Excel VBA - Match function error (Unable to get match property)

I'm trying to do a match search to filter out rows where certain data is matched. For example, I have "ButtonName" which shows which column filter has to be put and " DataRange.Rows(1) " is the range on which it tries to search for the match. Sometimes when I do some editing, it shows:

object defined error

And now it is showing:

Unable to get the match property

Please somebody tell me what is the error in the code?

Private Sub CommandButton21_Click()

    Dim myButton As OptionButton
    Dim SearchString As String
    Dim ButtonName As Variant
    Dim sht As Worksheet
    Dim myField As Long
    Dim DataRange As Range
    Dim mySearch1, mySearch2, mySearch3 As Variant

    'Load Sheet into A Variable
      Set sht = ActiveSheet
      Set a = ActiveSheet
    'Unfilter Data (if necessary)
      On Error Resume Next
      sht.ShowAllData
      On Error GoTo 0

    'Filtered Data Range (include column heading cells)
       Set DataRange = sht.Range("A13:AL3000") 'Cell Range

    'Retrieve User's Search Input

    mySearch1 = sht.Range("D4").Text 'Control Form     ''Contains data entered in D4cell

     ButtonName = sht.Range("M12").Text     

     If Not IsError(WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0))          Then

        myField = WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
     Else
       MsgBox "no match is found in range(" & rngToSearch.Address & ")."
     End If


    'Filter Data
       DataRange.AutoFilter _
       Field:=myField, _
       Criteria1:="=*" & mySearch1 & "*", _
       Operator:=xlAnd, _
       Criteria2:="=*" & mySearch2 & "*", _
       Operator:=xlAnd, _
       Criteria2:="=*" & mySearch3 & "*", _
       Operator:=xlAnd

End Sub

The Error occurs on this line:

If Not IsError(WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0))

Make the following changes:

Dim myField As Variant   'IMPORTANT

myField = Application.Match(ButtonName, DataRange.Rows(1), 0)

If IsError(myField) Then
    MsgBox "no match is found in range(" & rngToSearch.Address & ")."
Else
    'Filter Data
    DataRange.AutoFilter _
    Field:=myField, _
    Criteria1:="=*" & mySearch1 & "*", _
    Operator:=xlAnd, _
    Criteria2:="=*" & mySearch2 & "*", _
    Operator:=xlAnd, _
    Criteria2:="=*" & mySearch3 & "*", _
    Operator:=xlAnd
End If

尝试对表达式求值:

If Evaluate("ISERROR(MATCH(""" & ButtonName & """," & Selection.Rows(1).Address & ",0))") Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM