|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
跪求各位老師教下小弟字典用法~~~實在不明白以下兩個程序,為什麼結果會不一樣?
Sub 重覆1()
Dim d, k, t, arr
Dim i As Integer
Range("J:K").ClearContents
Set d = CreateObject("scripting.dictionary")
arr = Range("A1").CurrentRegion
For i = 2 To UBound(arr)
d(arr(i, 3)) = d(arr(i, 3)) + 1 '<<--具體只有這行不同
Next
k = d.keys
t = d.items
Range("J1:K1") = Array("姓名", "重覆個數")
Range("J2:J" & d.Count + 1) = Application.Transpose(k)
Range("k2:K" & d.Count + 1) = Application.Transpose(t)
Set d = Nothing
End Sub
Sub 重覆2()
Dim d, k, t
Dim rng As Range
Set d = CreateObject("scripting.dictionary")
Range("N:O").ClearContents
For Each rng In Range("C2:C" & Range("C2").End(xlDown).Row)
d(rng) = d(rng) + 1 '<<--具體只有這行不同
Next
k = d.keys
t = d.items
Range("N1:O1") = Array("姓名", "重覆個數")
Range("N2:N" & d.Count + 1) = Application.Transpose(k)
Range("O2:O" & d.Count + 1) = Application.Transpose(t)
Set d = Nothing
End Sub
如圖所示,結果是程序:重覆1()那個才正確的,我有以下3個問題:
(一) 明明arr(i,3) 應該等於 rng,我實在不明白為何會有出入?
(二) 字典裏不是不能夠含有重覆的Key嗎?為什程序:重覆2() 仍然能運行?
(三) d(arr(i, 3)) = d(arr(i, 3)) + 1 <--這句真心不能理解,各位老師能多作解釋嗎?(平時用字典都要add方法加Key的,這句什麼時候讓字典加Key了?)
|
|