Excel VBA worksheetfunction索引与数组匹配

时间:2020-05-05 19:09:52

标签: arrays excel vba match worksheet-function

使用.worksheet函数时,是否可以通过INDEX MATCH将VBA移至除数组公式之外的其他位置?

我的第一个公式起作用了,因为它不是我假定的数组?

此代码有效

Dim VType As string
VType = Application.WorksheetFunction.Index(Sheets(sheetname).Range("$B:$B"), Application.WorksheetFunction.Match("*" & VendorCode & "*", Sheets(sheetname).Range("$A:$A"), 0), 1)

但是当我添加第二个匹配项时,我得到了一个错误:类型不匹配

Dim RetORWaste As String
RetORWaste = Application.WorksheetFunction.Index(Sheets(wsMaster.Name).Range("$F:$F"), Application.WorksheetFunction.Match(("*" & VendorCode & "*") & ("*" & VRegion & "*"), (Sheets(wsMaster.Name).Range("$B:$B")) & (Sheets(wsMaster.Name).Range("$C:$C")), 0), 1)

sheetname和wsMaster.name都是字符串。 wsMaster.Name也将获取正确的工作表名称。所以它一定是数组吗?

1 个答案:

答案 0 :(得分:2)

如果我正确理解您要进行“两列匹配”,例如:https://www.excel-easy.com/examples/two-column-lookup.html

Sub tester()

    Dim RetORWaste As String, wsMaster As Worksheet, m, f
    Dim VendorCode, VRegion

    Set wsMaster = ActiveSheet

    VendorCode = "A"
    VRegion = "B"

    f = "=MATCH(""*{vend}*""&""*{region}*"",B:B&C:C,0)"
    f = Replace(f, "{vend}", VendorCode)
    f = Replace(f, "{region}", VRegion)

    m = wsMaster.Evaluate(f) '<<do not use Application.Evaluate here, or the
                             '  formula will evaluate in the context of the 
                             '  active sheet, which might not be wsMaster

    If Not IsError(m) Then
        'got a match so get the value from col F
        RetORWaste = wsMaster.Cells(m, "F")
        Debug.Print RetORWaste
    End If

End Sub