Concat multiple MATCH criteria in Excel VBA

前端 未结 3 753
挽巷
挽巷 2020-12-18 15:06

So in Excel, we know it\'s possible to test against multiple criteria via concatenation, like this:

MATCH(criteria1&criteria2, Range(), 0)
相关标签:
3条回答
  • 2020-12-18 15:23

    This works:

    Sub dural()
        crit1 = "find "
        crit2 = "happiness"
        N = Application.WorksheetFunction.Match(crit1 & crit2, Range("A1:A10"), 0)
        MsgBox N
    End Sub
    

    with, say A3 containing:

    find happiness

    EDIT#1:

    Consider the case of multiple criteria in several columns. For example:

    demo

    and we want VBA to retrieve the name of a small, black, dog

    without VBA in a worksheet cell we can use:

    =INDEX(D1:D100,SUMPRODUCT(--(A1:A100="dog")*(B1:B100="small")*(C1:C100="black")*ROW(1:100)),1)
    

    to get the name Oscar

    we can use the same formula in VBA

    Sub luxation()
        Dim s As String, s2 As String
        s = "INDEX(D1:D100,SUMPRODUCT(--(A1:A100=""dog"")*(B1:B100=""small"")*(C1:C100=""black"")*ROW(1:100)),1)"
        s2 = Evaluate(s)
        MsgBox s2
    End Sub
    
    0 讨论(0)
  • 2020-12-18 15:37

    Doesn't readily map to a VBA implementation, but you can cheat a bit using Evaluate:

    Sub Tester()
    
        Dim v1, v2, f
    
        v1 = "y"
        v2 = 11
    
        Sheet1.Names.Add Name:="X", RefersTo:=v1
        Sheet1.Names.Add Name:="Y", RefersTo:=v2
    
        f = "MATCH(X&Y,$A$2:$A$5&$B$2:$B$5, 0)"
    
        Debug.Print Sheet1.Evaluate(f)
    
    End Sub
    

    or skipping the names:

    Sub Tester2()
    
        Const F_TEMPL As String = "MATCH(""{V1}""&""{V2}"",$A$2:$A$5&$B$2:$B$5, 0)"
        Dim v1, v2, f
    
        f = Replace(F_TEMPL, "{V1}", "x")
        f = Replace(f, "{V2}", 12)
    
        Debug.Print Sheet1.Evaluate(f)
    
    End Sub
    
    0 讨论(0)
  • 2020-12-18 15:43

    You still need to send the MATCH argument body as a string. The '+' does not concatenate.

    WorksheetFunction.Match(criteria1 & "&" & criteria2, Range(), 0)
    

    Should concatenate the two values and execute the match.

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