[英]Excel VBA | Matching Values Between Sheets
我需要從 sheet2 的列中提取一個值,其中 sheet1 中的單元格值與工作表中的列值完全匹配。 如果有匹配,則檢索該值。 如果沒有,顯示“未找到”
這是單元格公式中的解決方案。 我只是不知道如何在 VBA 中做到這一點。
=INDEX(Sheet2!D:D,MATCH(Sheet1!C5,Sheet2!E:E,0))
使用Range.Find()
:
Sub findmatch()
Dim rng As Range
Set rng = Sheet2.Range("B:B").Find(Sheet1.Cells(4, 2).Value, , xlValues, xlWhole)
If Not rng Is Nothing Then
Sheet1.Cells(10, 2).Value = rng.Offset(0, 1).Value
Else
Sheet1.Cells(10, 2).Value = "No Match Found"
End If
End Sub
您可能希望找到最后一行並限制范圍,盡管無論如何它應該非常快。
使用Application.Vlookup
:
Sub vlookupmatch()
If IsError(Application.VLookup(Sheet1.Cells(4, 2), Sheet2.Range("B:C"), 2, False)) Then
Sheet1.Cells(10, 2).Value = "No Match Found"
Else
Sheet1.Cells(10, 2).Value = Application.VLookup(Sheet1.Cells(4, 2), Sheet2.Range("B:C"), 2, False)
End If
End Sub
使用字典:
Sub dictmatch()
Dim i As Long
Dim lr As Long
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
With Sheet2
lr = .Cells(.Rows.Count, 2).End(xlUp).Row
For i = 4 To lr
'I'm assuming there are no duplicates you will need to check for that if it is a possibility.
dict.Add .Cells(i, 2).Value, .Cells(i, 3).Value
Next i
End With
With Sheet1
If dict.exists(.Cells(4, 2).Value) Then
.Cells(10, 2).Value = dict(.Cells(4, 2).Value)
Else
.Cells(10, 2).Value = "No Match Found"
End If
End With
End Sub
可能對你正在做的事情有點矯枉過正,但為什么不呢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.