首页 > 解决方案 > Excel VBA - 具有多个条件的 Xlookup

问题描述

我觉得这是一件非常简单的事情,但我一直在谷歌搜索和试验一段时间,似乎空手而归(对我来说也很晚了)。我的猜测是我正在搜索错误的术语/单词。无论如何,让我解释一下。

在 Excel 中,使用 Xlookup 功能时可以有多个条件。

“正常”的 Xlookup 看起来像这样:

=xlookup("ThingToLookFor", "Search Range", "Return Range")

多条件 Xlookup 看起来像这样:

=xlookup("ThingToLookFor" & "OtherThingToLookFor", "Search Range 1" & "Search Range 2", "Return Range")

我正在尝试在 VBA 中执行多个标准 Xlookup,但我一生都无法弄清楚如何写出来。使用“&”将两个字符串组合在一起,所以这不好。我尝试了一些不同的东西,但它似乎不喜欢我扔给它的任何东西。

那么在 VBA 中正确的版本是什么:

WorksheetFunction.Xlookup("ThingToLookFor" & OtherThingToLookFor", "Search Range 1" & "Search Range 2", "Return Range")? 

注意:在搜索时,我确实发现了“Evaluate”,它非常简洁。我可以让它工作,但我不确定我是否喜欢它。我真的希望找到一种方法来使 WorksheetFunction 工作。

编辑 我在这里尝试做的更具体的例子:

Sub xlookup_test()

    Dim Lookup_Value_1 As String
    Lookup_Value_1 = "My Document"
    
    Dim Lookup_Value_2 As String
    Lookup_Value_2 = "Sales"
    
    Dim Search_List_1 As Range
    Set Search_List_1 = Document_Control.Range("DC_Document_Type")
    
    Dim Search_List_2 As Range
    Set Search_List_2 = Document_Control.Range("DC_Document_Name")
    
    Dim Return_List As Range
    Set Return_List = Document_Control.Range("DC_Document_ID")
    
    Dim Return_Value As String

    ' this is the problem line    
    Return_Value = WorksheetFunction.XLookup(Lookup_Value_1 & Lookup_Value_2, Search_List_1 & Search_List_2, Return_List)
    
    Debug.Print (Return_Value)
    
End Sub

然而,如前所述,使用“&”只是将两个字符串组合在一起形成一个字符串,而不是告诉它它需要寻找两个不同的东西。

标签: excelvbaxlookup

解决方案


不幸的是,我无法XLOOKUP在我的 Excel 版本中访问它,所以我无法测试。"但我认为问题在于您在搜索范围内使用引号 ( )。

您说:“使用“&”将两个字符串组合在一起”。这正是正在发生的事情,除了您正在组合地址的字符串而不是那些地址处的字符串。

试试这个(您需要调整搜索范围和条件以适应):

WorksheetFunction.Xlookup("ThingToLookFor" & "OtherThingToLookFor", A1:A3&B1:B3, C1:C3)

如果“ThingToLookFor”和“OtherThingToLookFor”也是单元格引用,请记住也将其"从这些引用中删除。


推荐阅读