简体   繁体   中英

Concat multiple MATCH criteria in Excel VBA

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

MATCH(criteria1&criteria2, Range(), 0)

where criteria1 and criteria2 are 2 separate criteria.

I'm trying to automate this thing in Excel VBA, like this:

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

My question is, how do I replicate the same concatenation of criteria with the ampersand, in VBA form? In the version above, Excel keeps telling me it can't use the Match function of the WorkSheetFunction class, which I'm attributing to the failed concatenation attempt above. Any suggestions or advice would be greatly appreciated.

Oh, and here's a link to a Microsoft Knowledge Base article about using multiple criteria in MATCH() : http://support.microsoft.com/kb/59482

EDIT: I realized I wasn't putting 2 ranges to correspond with my 2 criteria. The problem is I don't know how to concatenate 2 ranges, because mine are in the form:

Range(Cells(1,columnIndex),Cells(rowCount,columnIndex))

as opposed to A1:A200 . Any ideas on how to convert, or to concat the ranges in their current form?

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:

演示

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

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

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.

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