[オリジナル] VBAの研究ノート(313)VBAの辞書関連:キーアプローチで項目をチェックし、キーチェック項目と辞書を、トラバース

 

1つの辞書トラバーサル方法

  • でも後半バインディング、あなたも使用することができます 
  • それぞれ本明細書(使用dict1.keys()「dict1.keysにおいてI)ではなくdict1.keysための式(I)であります
Sub test_dict11()

Dim dict1 As Object
Set dict1 = CreateObject("scripting.dictionary")


dict1.Add 1, "h"
dict1.Add 2, "e"
dict1.Add 3, "l"
dict1.Add 4, "l"
dict1.Add 5, "o"
dict1.Add 6, "world"

For Each I In dict1.keys()
   Debug.Print I & "," & dict1(I)
Next
Debug.Print
'知道key 去查item

Debug.Print dict1(1)
Debug.Print dict1.Item(2)
Debug.Print



End Sub

 

検索キーアイテム、通常動作と2

  • dict1(キー)
  • dict1.items(キー)

 

型破りなキー項目検索操作と3

3.1私自身の考え:dict1.keys()とdict1.items()相当のペアです

  • キーを使用して、アイテムのデザインは、辞書ペアリングされています
  • 項目が繰り返されていない場合、インデックスは、インデックスのキー項目で、インデックスが同期されています
  • 繰り返しアイテムは、画面はループインデックスの複数であってもよいです
  • 注意は、しかし、この方法を有効にするには、早期にバインドする必要があります。このサイクルのためだけ早期バインディングサポートされていますdict1.keys(I)

 

  • 1エラーの衰えない、match関数の問題は、ワークシート関数であるため、
  • dict1.keys(インデックス)を直接予備結合しなければならないので、このようなAの試合、または早期バインディングをサポートする必要性を見つけます
Sub test_dict1()

Dim dict1 As New Dictionary

dict1.Add 1, "h"
dict1.Add 2, "e"
dict1.Add 3, "l"
dict1.Add 4, "l"
dict1.Add 5, "o"
dict1.Add 6, "world"

'方法1
'下面的反查方法要生效,必须是前期绑定!!!
'知道item去查key
'利用key,item 应该是成对的,也就是分别在 keys() items()的index是一样的。
For J = LBound(dict1.Items()) To UBound(dict1.Items())
    If dict1.Items(J) = "world" Then
'     If dict1(J) = "h" Then
       Debug.Print J             'keys(),items()数组没定义,index是从0开始的
       Debug.Print dict1.Keys(J)
    End If

Next
Debug.Print

'方法2,也只有前期绑定支持
'不减1就出错,因为match函数的问题,是工作表函数
'这样用match查找,还是需要前期绑定的支持,因为 dict1.keys(index) 直接用必须前期绑定
Debug.Print dict1.Keys(Application.Match("world", dict1.Items(), 0) - 1)


End Sub

 

 

4方法2は、遅延バインディングはまた、活性であります

  • 後期も確認することができますバインディング
  • あなたは後半に結合されている場合
  • あなたは直接dict.keys()dict.items()を使用することはできません
  • しかし、あなたはトランジットを見て回るために、配列を使用することができます
arr1=dict.keys()
arr1(index)
arr2=dict.items()
arr2(index)

 

Sub test_dict22()
'后期绑定各种测试


Dim dict1 As Object
Set dict1 = CreateObject("scripting.dictionary")


dict1.Add 1, "h"
dict1.Add 2, "e"
dict1.Add 3, "l"
dict1.Add 4, "l"
dict1.Add 5, "o"
dict1.Add 6, "world"


'后期绑定,为什么又可以使用dict1.keys()? for each可以使用? 不能用index方式使用这2个数组?
For Each I In dict1.Keys()
    Debug.Print I & " ";
    Debug.Print dict1(I)
Next
Debug.Print



'数组中转
'dict1.keys()  dict1.items() 都可以使用,但不能做index for i 的这种遍历,中转的数组可以
'dict1里 key-item同步,只要item不重复,可以用相同的变量循环

arr1 = dict1.Keys()
arr2 = dict1.Items()
For I = LBound(arr2) To UBound(arr2)
    If arr2(I) = "world" Then
       Debug.Print arr1(I) & "," & arr2(I)
    End If
Next
Debug.Print
End Sub

 


 

公開された370元の記事 ウォン称賛45 ビュー90000 +

おすすめ

転載: blog.csdn.net/xuemanqianshan/article/details/103916083