excel 为什么我的应用程序.XLookup在VBA给出“类型不匹配”错误?

kxe2p93d  于 2023-04-22  发布在  其他
关注(0)|答案(2)|浏览(167)

编辑:我的代码改为使用布尔逻辑而不是连接,但我仍然得到相同的错误。
我尝试在vba中使用application.xlookup,并通过在此代码中连接公式来添加额外的条件。

Sub employeelookup()
 SalesForm.BHSDEMPLOYEETD.Value = Application.XLookup(1, (Worksheets("TELEDATA").Range("E:E") = SalesForm.BHSDMAINNUMBERLF.Value) * (Worksheets("TELEDATA").Range("AI2:AI5") = SalesForm.BHSDRECORDTD.Value), Worksheets("TELEDATA").Range("F:F"))
End Sub

我试着改变括号和混乱的顺序,但我得到语法错误。上面的代码应该在理论上工作,但我不能找出类型不匹配错误是从哪里来的。

rsaldnfx

rsaldnfx1#

你可以把所有的东西放在数组中,然后循环它们来找到值:

Sub employeelookup()
    Dim mn_num As Double
    mn_num = Val(SalesForm.BHSDMAINNUMBERLF.Value)
    Dim rec As String
    rec = SalesForm.BHSDRECORDTD.Value
    
    Dim lkpmnArr As Variant
    lkpmnArr = Intersect(Worksheets("TELEDATA").UsedRange, Worksheets("TELEDATA").Range("E:E")).Value
    
    Dim lkprecArr As Variant
    lkprecArr = Intersect(Worksheets("TELEDATA").UsedRange, Worksheets("TELEDATA").Range("AI:AI")).Value
    
    Dim lkotArr As Variant
    lkotArr = Intersect(Worksheets("TELEDATA").UsedRange, Worksheets("TELEDATA").Range("F:F")).Value
    
    Dim otpt As String
    otpt = "Not Found"
    
    Dim i As Long
    For i = LBound(lkpmnArr, 1) To UBound(lkpmnArr, 1)
        If lkpmnArr(i, 1) = mn_num And lkprecArr(i, 1) = rec Then
            otpt = lkotArr(i, 1)
            Exit For
        End If
    Next i
    
    
    SalesForm.BHSDEMPLOYEETD.Value = otpt
End Sub
dsf9zpds

dsf9zpds2#

可以使用Evaluate

Sub employeelookup()
    'Whether v1 and/or v2 are quoted depends on if numeric or text
    '  here <v1> is numeric and <v2> is not
    Const FRM As String = "XLOOKUP(<v1>&<v2>,E:E&AI:AI,H:H)"
    Dim res, f
    
    'replace the placeholders in the formula with values from your form
    f = Replace(FRM, "<v1>", val(SalesForm.BHSDMAINNUMBERLF.value))
    f = Replace(f, "<v2>", SalesForm.BHSDRECORDTD.value)
    
    'evaluate in context of sheet TELEDATA
    res = Worksheets("TELEDATA").Evaluate(f)
    
    If IsError(res) Then  'if got an error then no match was made
        Debug.Print "No match"
    Else
        Debug.Print res
    End If
End Sub

相关问题