Excel VBA 在其他 sheet 中查找值并复制它们

Excel VBA look for values in other sheet and copy them

我有两个 excel 工作表:"Sheet1" 和 "Sheet2"。

工作表 1 包含 3 列,行数为 N。 示例:

x     y     result

A     b
B     m
L     a
A     b
B     b

Sheet2 也包含 3 列,但结果是每个 x 和 y 组合的解释。

示例:

x     y      result

A     a        1
A     b        2
A     c        3
B     a        4

请注意,A != a,结果并不总是数值。

所以基本上我需要从 Sheet1 的值中搜索 Sheet2 的给定组合,并将结果从 Sheet2 复制到 Sheet1。

你能给我示例 VBA 如何实现这一点的代码吗? 可能 Excel 公式甚至可能吗?可能是INDEX和MATCH?反正我自己也想不通。

谢谢

首先添加另一列,其中包含用于创建唯一键的公式:

Sheet1:
   A       B       C       D
1  x       y       result  key 
2  A       b               =A2&B2
3  B       m               =A3&B3
4  L       a               =A4&B4
etc...

Sheet2:
   A       B       C       D     
1  x       y       result  key
2  A       a       1       =A2&B2
3  A       b       2       =A3&B3
4  A       c       3       =A4&B4
etc...

然后试试这个:

Sub FindResult()

Dim XY As String
Dim S1 As Object, S2 As Object
Dim ResultCell As Range, ResultValue As String

    Set S1 = Worksheets("Sheet1")
    Set S2 = Worksheets("Sheet2")

    Calculate
    For Rr = 2 To 6
        XY = S1.Cells(Rr, 4).Value
        Set ResultCell = S2.Range("D:D").Find( _
                                              What:=XY, _
                                              After:=S2.Range("D1"), _
                                              LookIn:=xlValues, _
                                              LookAt:=xlWhole, _
                                              SearchOrder:=xlByRows, _
                                              SearchDirection:=xlNext, _
                                              MatchCase:=True, _
                                              SearchFormat:=False _
                                             )
        If ResultCell Is Nothing Then
            ResultValue = "Not found"
        Else
            ResultValue = ResultCell.Offset(0, -1).Value
        End If
        S1.Cells(Rr, 3) = ResultValue
    Next Rr

End Sub

您可以使用公式本身来完成此操作。在您的工作表1中,请将以下公式粘贴到C2单元格中。

=IF(SUMPRODUCT((--EXACT(Sheet2!A:A,A2))*(--EXACT(Sheet2!B:B,B2))*(--(Sheet2!A:A<>""))*(--(Sheet2!B:B<>"")),ROW(Sheet2!A:A))=0,"",INDEX(Sheet2!C:C,SUMPRODUCT((--EXACT(Sheet2!A:A,A2))*(--EXACT(Sheet2!B:B,B2))*(--(Sheet2!A:A<>""))*(--(Sheet2!B:B<>"")),ROW(Sheet2!A:A))))

并将其复制到其他单元格。它会起作用。

请查看以下图片: