简体   繁体   English

多个单元格或范围的 VBA Vlookup

[英]VBA Vlookup for multiple cells or Range

I don't have much knoledge of VBA.我对 VBA 了解不多。 And also weak in English.而且英文也很差。

The below code is for VLOOKUP result in same cell, which is working well, but now I also need VLOOKUP values for Range("B1:B10") (nearby column ).下面的代码适用于同一单元格中的 VLOOKUP 结果,效果很好,但现在我还需要 Range("B1:B10") (附近的列)的 VLOOKUP 值。

My VLOOKUP Table Is: - ThisWorkbook.Sheets("ItemName").Range("D2:G10001")我的 VLOOKUP 表是: - ThisWorkbook.Sheets("ItemName").Range("D2:G10001")

Column Index Number: 3列索引号:3

Result I Need: If i type sumthing in any cell in Range("A1:A10"), and if the value found in VLOOKUP Table, then The Third Column's Value from the VLOOKUP Table must be show in nearby cell in Range("B1:B10")我需要的结果:如果我在 Range("A1:A10") 中的任何单元格中键入 sumthing,并且如果在 VLOOKUP Table 中找到该值,则 VLOOKUP Table 中的第三列的值必须显示在 Range("B1 :B10")

For Example: If i type something in Range A3 the vlookup result must be show in Range B3.例如:如果我在范围 A3 中键入内容,则查找结果必须显示在范围 B3 中。

    Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngCell As Range, m, v
    Dim rngCell1 As Range, m1, v1
Check1:
    If Application.Intersect(Target, Range("A1:A10")) Is Nothing Then GoTo Check2:
    
    For Each rngCell In Range("A1:A10")
        v = rngCell.Value
        If Len(v) > 0 Then

            'See if the value is in your lookup table
            m = Application.VLookup(v, _
                 ThisWorkbook.Sheets("ItemName").Range("D2:G10001"), 2, False)

            'If found a match then replace wiht the vlookup result
            If Not IsError(m) Then rngCell.Value = m
End If
    Next
Exit Sub

Check2:
End Sub

Think this does what you want.认为这可以满足您的需求。 I also restructured the code to avoid the Gotos.我还重组了代码以避免 Gotos。

I also disabled events to avoid an infinite loop (not sure how you avoided that yourself).我还禁用了事件以避免无限循环(不确定你自己是如何避免的)。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngCell As Range, m1 As Variant, m2 As Variant

If Application.Intersect(Target, Range("A1:A10")) Is Nothing Then Exit Sub

For Each rngCell In Intersect(Target, Range("A1:A10"))
    If Len(rngCell.Value) > 0 Then
        m1 = Application.VLookup(rngCell.Value, Range("D2:G10001"), 2, False)
        m2 = Application.VLookup(rngCell.Value, Range("D2:G10001"), 3, False)
        If Not IsError(m1) Then
            Application.EnableEvents = False
            rngCell.Value = m1
            rngCell.Offset(, 1).Value = m2
            Application.EnableEvents = True
        End If
    End If
Next

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM