0

我试图找出基于两列标准查找单元格信息的最佳方法。例如,我的 A 列包含一组数字,B 列包含另一组数字,C 列包含我要提取的单元格信息。单元格信息必须与我在用户表单中提供的 A 列和 B 列信息匹配,然后当我单击“搜索”时,我希望用户表单填充 C 列的信息。用户表单编码很好——我只是在“查找”方面遇到了麻烦。如果我不是在 vba 中编写这段代码,而只是作为一个数组,它看起来像这样:

={INDEX(A1:C20,MATCH(1,(A:A=ColumnAItem)*(B:B=ColumnBItem),0),3)}

到目前为止,这基本上是我自己在 VBA 中发现的:

Private Sub SearchButton_Click()

Dim SAP_A As Variant, SAP_B As Variant
Dim ws As Worksheet, mA, mB


Set ws = Sheets("Database Entry Sheet")


SAP_A = Trim(textbox5.Value)
SAP_B = Trim(textbox8.Value)

    mA = Application.Match(CLng(SAP_A), ws.Range("A:A"), 0)
    mB = Application.Match(CLng(SAP_B), ws.Range("B:B"), 0)

    If Not IsError(mA) And IsError(mB) Then
        textbox1.Text = ws.Cells(mA, "C")

End Sub
4

2 回答 2

0

尝试这个

Private Sub SearchButton_Click()

Dim SAP_A As Variant, SAP_B As Variant
Dim ws As Worksheet, mA, mB


Set ws = Sheets("Database Entry Sheet")


SAP_A = Trim(textbox5.Value)
SAP_B = Trim(textbox8.Value)

    mA = Application.Match(CLng(SAP_A), ws.Range("A:A"), 0)
    mB = Application.Match(CLng(SAP_B), ws.Range("B:B"), 0)
    
    '* Added Not before IsError(mB)
    If Not IsError(mA) And Not IsError(mB) Then
        '* Make sure they correspond to the same row
        If mA = mB Then   
            textbox1.Text = ws.Cells(mA, "C")
        End If
    End If '* End the if statement
End Sub

请注意我的评论以'*

但是,如果值在同一列上重复,则此处的逻辑存在一个微妙的问题:以这个例子为例

A  B  C
1  2  V1
5  1  V2
9  4  V3
3  1  V4
2  7  V5

现在,如果用户搜索SAP_A = 3然后搜索,SAP_B = 1那么代码不会像你期望的那样给你。这是因为为您提供了第一个匹配值的索引。因此,如果您在任一列中有重复的值,那么最好循环 A 和 B 列并检查两个值是否匹配并返回 C 列中的值。(编辑:或者甚至更好,将整个范围读入一个变体数组,因此,在内存中循环而不是一个范围:正如@BigBen在评论中建议的那样)mA = 4mB = 2V4Match

于 2020-07-17T19:12:43.823 回答
0

另一种方法:

Private Sub SearchButton_Click()

    Dim A As Variant, B As Variant
    Dim ws As Worksheet, f, m

    Set ws = ActiveSheet

    A = "B"
    B = "F"

    'Note: whether or not you need quotes in the formula around
    '  A and B will depend on the expected datatypes
    f = "=(A1:A20=""{A}"")*(B1:B20=""{B}"")"
    f = Replace(f, "{A}", A)
    f = Replace(f, "{B}", B)
    Debug.Print f
    
    m = Application.Match(1, ws.Evaluate(f), 0)
    
    If Not IsError(m) Then
        Debug.Print ws.Cells(m, "C")
    Else
        Debug.Print "no match for", A, B
    End If

End Sub
于 2020-07-17T21:14:03.673 回答