A variety of methods [original] VBA study notes (312) VBA generation dictionary, and best practices

Generating a plurality of dictionary methods

1.1 add method to generate dictionary

  • Add one by one
  • Cycle, add, necessary to determine whether to repeat

1.2 Add the entire keys () items (), to generate the entire array

  • (An array, etc.) assigned to cycle keys () items ()

1.3 assignment loop array generation method

  • Cycle dict5 (I) = ""

 

2 generates the most suitable method dictionary: cyclic assignment method for generating an array - as flexible enough, high fault tolerance

  • Cycle dict5 (I) = ""
  • Because when the key is not 1, it will add a new key - item
  • Because when the key 2 is repeated, it will not error
  • 3 key because when repeated, will be reassigned
     
sub test1()
arr4=array(1,3,5,7,9)

For Each I In arr4
   dict5(I) = k
   k=k+1
Next

end sub

 

Code 3: method for generating an array of more specific process

Sub testdict100()

Dim dict1 As Object
Dim dict2 As Object
Dim dict3 As Object
Dim dict4 As Object
Dim dict5 As Object

Set dict1 = CreateObject("scripting.dictionary")
Set dict2 = CreateObject("scripting.dictionary")
Set dict3 = CreateObject("scripting.dictionary")
Set dict4 = CreateObject("scripting.dictionary")
Set dict5 = CreateObject("scripting.dictionary")

'生成数组,方法1,逐个
dict1.Add 1, "a"
dict1.Add "1", "a"   '1和"1" 不一样
dict1.Add 3, "c"
dict1.Add 4, "d"
dict1.Add 5, "e"

Debug.Print "dict1"
For Each I In dict1.Keys()
    Debug.Print I & "," & dict1(I)    '虽然不能用dict1.items(index),但ict1(index)  这个可以有
Next
Debug.Print

'生成数组,方法2-1,用数组整体,循环添加
arr1 = Array(1, 2, 3, 4, 5)

For Each I In arr1
   dict2(I) = ""
Next

Debug.Print "dict2"
For Each I In dict2.Keys()      '考虑可以把这个写成一个显示dict的函数把?
    Debug.Print I & "," & dict2(I)
Next
Debug.Print


'生成数组,方法2-2,key item分别也是可以的
arr2 = Array(1, 2, 3, 4, 5)
arr3 = Array(11, 22, 33, 44, 55)
'先保证这2个数组,长度一样

'用同一个变量循环体,应该可以
For I = LBound(arr2) To UBound(arr2)
   dict3(arr2(I)) = arr3(I)
Next

Debug.Print "dict3"
For Each I In dict3.Keys()
    Debug.Print I & "," & dict3(I)
Next
Debug.Print


'生成数组,方法3,用add循环添加
arr4 = [{101,102,103,104,105,101,101}]
For Each I In arr4
   If Not dict4.exists(I) Then
       dict4.Add I, ""
   End If
Next

Debug.Print "dict4"
For Each I In dict4.Keys()
    Debug.Print I & "," & dict4(I)
Next
Debug.Print



'生成数组,方法4,查询式循环添加
'适应性很强,没有则添加,有则赋值,重复不出错只是再赋值

For Each I In arr4
   dict5(I) = ""
Next


Debug.Print "dict5"
For Each I In dict5.Keys()
    Debug.Print I & "," & dict5(I)
Next
Debug.Print



End Sub

 

Published 370 original articles · won praise 45 · views 90000 +

Guess you like

Origin blog.csdn.net/xuemanqianshan/article/details/103923936