Windows 10 Pro_x64 + Excel2013_x86 VBA で 可変長配列、Type、Dictionary を使う

Windows 10 Pro_x64 + Excel2013_x86 VBA で 可変長配列、Type、Dictionaryを使う
 
自分の中では、可変長配列、Type、Dictionary はセットで使うことが多い気が
しているので、まとめてメモっておく
・ReDim typArry(3):可変長配列のサイズを4と定義する
 ※添え字の最小値は0、最大値は3、内容は未定義
・ReDim typArry(3)
 ReDim Preserve typArry(4):
※typArry(3)までの値は保持
※typArry(4)の内容は未定義
・Dictionary.Exists(Key):Keyが存在するかをチェックする
・Dictionary.Add Key, Value:Key, Valueのペアを登録する
・Variant = Dictionary.Keys:Keyの配列を取得する
・Dictionary.Item(Key):Keyに対応するValueを取得する


Option Explicit

Private Type typDemo
Code As String
Name As String
End Type

Private Sub UserForm_Initialize()

Dim typArry() As typDemo
Dim varkeys As Variant
Dim keys As Variant
Dim intCnt As Integer
'
' 配列の添え字は 0〜3
'
ReDim Preserve typArry(3)
Dim dict As New Dictionary
Dim dcnt As New Dictionary
'
' 使用データ
'
typArry(0).Code = "01"
typArry(0).Name = "北海道"
typArry(1).Code = "02"
typArry(1).Name = "青森県"
typArry(2).Code = "03"
typArry(2).Name = "岩手県"
typArry(3).Code = "01"
typArry(3).Name = "北海道"
'
' LBound 関数は配列の最小インデックス
' UBound 関数は配列の最大インデックス
'
For intCnt = LBound(typArry) To UBound(typArry)
If dict.Exists(typArry(intCnt).Code) Then
'
' Dictionary に Key が登録済
'
Debug.Print "dict.Exists: ", _
intCnt, _
typArry(intCnt).Code, _
typArry(intCnt).Name
'
' 出現数のカウントアップ
'
dcnt.Item(typArry(intCnt).Code) = dcnt.Item(typArry(intCnt).Code) + 1
Else
'
' Dictionary に Key, Value のペアを追加
'
dict.Add typArry(intCnt).Code, typArry(intCnt).Name
'
' 出現数のカウント:初期値
'
dcnt.Add typArry(intCnt).Code, 1
End If
Next
'
'Dictionary に登録された項目数
'
Debug.Print dict.count
'
' 登録されたkeyをVariantのリストとして取得する
'
varkeys = dict.keys
'
' Dictionary より Key, Value のペアを取得する
'
For Each keys In varkeys
Debug.Print keys, dict.Item(keys), dcnt.Item(keys)
Next
'
End Sub