[英]Looping Through EXCEL VBA Dictionary
我有一個VBA詞典,其中包含以下數據:
ID NAME POSITION
5008004 John Doe 00120096
5008002 John Doe2 00117886
5010010 John Doe3 00117886
我有一個包含以下單元格的Excel文檔:
POSITION SUPERVISOR_NAME
00117886 John Doe
00117886 John Doe2
00117886 John Doe3
當前的Excel VBA代碼以以下方式在字典中循環:
If SUPERVISOR_NAME <> "" Then
For Each myKey In superDictionary.Keys
If superDictionary(myKey) = SUPERVISOR_NAME Then
SUPERVISOR_NAME = myKey
Exit For
End If
Next
End If
無論如何,都會用其關聯的ID替換JOHN DOE名稱。
問題:僅當EXCEL中的POSITION和SUPERVISOR_NAME與Dictionary匹配或ELSE不提交任何內容時,如何使用相關的ID BUT替換JOHN DOE名稱。
似乎您沒有適當地利用Scripting.Dictionary對象的最強大功能之一; 那是它的快速檢索功能。 本質上,您希望使用兩列條件執行查找,因此請使用兩列作為鍵 ,將ID用作Item 。
Option Explicit
Sub supervisorIDs()
Dim d As Variant, dict As Object
Dim v As Long, vVALs As Variant
Set dict = CreateObject("Scripting.Dictionary")
dict.comparemode = vbTextCompare 'default is vbbinarycompare
With Worksheets("Sheet4")
'get values from worksheet
vVALs = .Range(.Cells(2, 1), .Cells(Rows.Count, 3).End(xlUp)).Value2
'build dictionary
For v = LBound(vVALs, 1) To UBound(vVALs, 1)
'overwrite method - faster (no error control)
'writes name&position as key, ID as item
dict.Item(Join(Array(vVALs(v, 2), vVALs(v, 3)), ChrW(8203))) = vVALs(v, 1)
Next v
'loop through the second table
For v = 2 To .Cells(Rows.Count, 6).End(xlUp).Row
d = Join(Array(.Cells(v, 6).Value2, .Cells(v, 5).Value2), ChrW(8203))
If dict.exists(d) Then _
.Cells(v, 7) = dict.Item(d)
Next v
End With
End Sub
你是這個意思嗎
假設您的主管姓名在B欄中,從第2行開始:
Dim r As Long
Dim supervisorName As Range
For Each supervisorName In Range("B2:B" & Cells.(Rows.Count, 2).End(xlUp).Row).Cells
If superDictionary.Exists(supervisorName.Value) Then
r = 2 '// First row with data in
For Each key In superDictionary.Keys
If superDictionary(key) = supervisorName.Value And supervisorName.Row = r Then
supervisorName.Value = key
Exit For
Else
r = r + 1
End If
Next
End If
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.