【原创】VBA学习笔记(312)VBA生成字典的多种方法,和最优方法

1 生成字典多种方法

1.1 add方法生成字典

  • 逐个add
  • 循环,add,需要判断是否重复

1.2 整体添加keys()  items() ,整体生成数组

  • (用数组等)循环赋值给 keys()  items()

1.3 循环赋值生成数组的方法

  • 循环 dict5(I) = ""

2 生成字典最合适的方法:循环赋值生成数组的方法--因为足够灵活,容错率高

  • 循环 dict5(I) = ""
  • 因为1  当key没有,则会添加一个新的key--item
  • 因为2  当key重复了,也不会报错
  • 因为3  当key重复了,会进行重新赋值
     
sub test1()
arr4=array(1,3,5,7,9)

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

end sub

3 代码:多种方法生成数组的具体过程

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
发布了370 篇原创文章 · 获赞 45 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/xuemanqianshan/article/details/103923936