基于条件的Excel查找

时间:2014-05-02 04:37:48

标签: excel vba excel-vba

sheet1 sheet2  sheet3

 ---------
 |       |
 V       V      *  V-----
123  | A 123 | 456 C |  |
 *   | B 123 | 789 D |  |
     | C 123 | 345 E |  |
       ^                |
       |-----------------     

我可以从表1到表2中查找123以返回一个字母(但该字母必须出现在表3(C)中,查找表3中的字母并返回456?问题是有多个表2中的123;我只习惯处理唯一的数字。它可以去A不在表3中所以转到下一个字母直到达到C.然后查找值到左边是456。 感谢

2 个答案:

答案 0 :(得分:0)

让这是你的数据: 工作表Sheet:

enter image description here

Sheet2:

enter image description here

表3:

enter image description here

如果找到匹配项,下面的代码将遍历sheet2中的值,它将遍历sheet3中的值。如果找到匹配项,则会显示,否则它将继续循环显示。

Sub main()
Dim intValue As Integer
Dim i As Integer
Dim j As Integer

Dim strChar As String

intValue = Sheet1.Cells(1, 1)
For i = 1 To 3
    If intValue = Sheet2.Cells(i, 2) Then
        strChar = Sheet2.Cells(i, 1)
        For j = 1 To 3
            If strChar = Sheet3.Cells(j, 2) Then
                MsgBox (Sheet3.Cells(j, 1))
                Exit Sub
            End If

        Next j

    End If

Next i
End Sub

答案 1 :(得分:0)

在模块中使用VBA,编写这个新函数:

Public Function LookFx(Sh1 As Range, Sh2 As Range, Sh3 As Range) As String
Dim BaseVal As String
Dim FoundV As Boolean
Dim SecVal As String

Application.Volatile

BaseVal = Sh1.Value
FoundV = False

For Each xx In Sh2
    If xx.Value = BaseVal Then
        SecVal = xx.Offset(0, -1).Value
        For Each yy In Sh3
            If yy.Value = SecVal Then
                LookFx = yy.Offset(0, -1).Value
            End If
        Next
    End If
Next
End Function

要在函数中添加的值是:

enter image description here