LoginSignup
0
0

More than 5 years have passed since last update.

Windows 10 Pro x64 + Excel2016 x86 VBA で 可変長配列、Type、Dictionary を使う

Last updated at Posted at 2019-02-07

目的

自分の中では、可変長配列、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を取得する
対象データは郵便番号データダウンロードの全国一括(KEN_ALL.CSV)より一部抜粋

サンプルコード

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
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0