[英]Excel VBA - Custom Function; #VALUE error; VLOOKUP on different worksheet
[英]Excel 2007 VBA - Use VLOOKUP to find value in different worksheet and store result in active sheet
我是這個小組和VBA的新手。
我有一個工作表'T2',行數可變。 從第3行開始,我想查找“E”列中找到的項目編號並搜索工作表“支持”。 項目編號可以在“支持”中的“A”列中的某處找到。 我需要將支持中的列'B'中的值(與該項目編號相關)並將其存儲在工作表'T2'中的列'A'中。 然后我想對'T2'中的每一行重復這個過程,直到並包括最后一行。
任何人都可以幫助,因為我根本無法讓它工作。
謝謝
對於Vlookup部分,這應該是您需要的。
Sub with_some_name
Dim result As String
With Worksheets("T2")
result = Application.WorksheetFunction.VLookup(.Range("e3"), Worksheets("support").Range("A:B"), 2, False)
Range("A3").Value = result
End With
end sub
變體使用詞典:
Sub Test1()
Dim Dic As Object, key As Variant, oCell As Range, i&
Dim w1 As Worksheet, w2 As Worksheet
Set Dic = CreateObject("Scripting.Dictionary")
Set w1 = Sheets("Support")
Set w2 = Sheets("T2")
i = w1.Cells(Rows.Count, "A").End(xlUp).Row
For Each oCell In w1.Range("A1:A" & i)
If Not Dic.exists(oCell.Value) Then
Dic.Add oCell.Value, oCell.Offset(, 1).Value
End If
Next
i = w2.Cells(Rows.Count, "E").End(xlUp).Row
For Each oCell In w2.Range("E3:E" & i)
For Each key In Dic
If oCell.Value = key Then
oCell.Offset(, -4).Value = Dic(key)
End If
Next
Next
End Sub
使用vlookup的變體:
Sub Test2()
Dim oCell As Range
Dim w1 As Worksheet, w2 As Worksheet
Set w1 = Sheets("Support")
Set w2 = Sheets("T2")
i = w2.Cells(Rows.Count, "E").End(xlUp).Row
On Error Resume Next
For Each oCell In w2.Range("E3:E" & i)
oCell.Offset(, -4).Value = WorksheetFunction.VLookup(oCell.Value, w1.[A:B], 2, 0)
Next
End Sub
使用find方法的變體:
Sub Test3()
Dim oCell As Range
Dim w1 As Worksheet, w2 As Worksheet
Set w1 = Sheets("Support")
Set w2 = Sheets("T2")
i = w2.Cells(Rows.Count, "E").End(xlUp).Row
On Error Resume Next
For Each oCell In w2.Range("E3:E" & i)
oCell.Offset(, -4).Value = w1.Cells(w1.Columns(1).Find(oCell.Value).Row, 2).Value
Next
End Sub
輸出結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.