簡體   English   中英

多個單元格或范圍的 VBA Vlookup

[英]VBA Vlookup for multiple cells or Range

我對 VBA 了解不多。 而且英文也很差。

下面的代碼適用於同一單元格中的 VLOOKUP 結果,效果很好,但現在我還需要 Range("B1:B10") (附近的列)的 VLOOKUP 值。

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

列索引號:3

我需要的結果:如果我在 Range("A1:A10") 中的任何單元格中鍵入 sumthing,並且如果在 VLOOKUP Table 中找到該值,則 VLOOKUP Table 中的第三列的值必須顯示在 Range("B1 :B10")

例如:如果我在范圍 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

認為這可以滿足您的需求。 我還重組了代碼以避免 Gotos。

我還禁用了事件以避免無限循環(不確定你自己是如何避免的)。

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