0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VBAのディクショナリーのネスト(親ディクショナリー、子ディクショナリー)

Last updated at Posted at 2025-03-07

はじめに
値 以外をデバックプリントしようとしないでください

Sub 都道府県市区町村()

' 都道府県ディクショナリを作成
Dim 都道府県 As Object, 市区 As Variant
Set 都道府県 = CreateObject("scripting.dictionary")

' Excelテーブルのデータを配列に格納
Dim arr As Variant
'注目! テーブル のデータ行は .DataBodyRange です
arr = list.ListObjects(1).DataBodyRange

Dim r As Long

' 各行をループ処理
'ヘッダーが含まれていないので 1 始まり
For r = 1 To list.ListObjects(1).DataBodyRange.Rows.Count

    ' 親キー(都道府県)と子キー(市区)を取得
    Dim 親キー As String, 子キー As String
    親キー = arr(r, 2)
    子キー = arr(r, 3)

    ' 親キーがディクショナリに存在しない場合、新しい辞書を作成して追加
    If Not 都道府県.exists(親キー) Then
    
        Set 市区 = CreateObject("scripting.dictionary")
        
        都道府県.Add 親キー, 市区
        
    End If

    ' 子キーが親キーの辞書に存在しない場合、新しい項目を追加
    If Not 都道府県(親キー).exists(子キー) Then
    
        都道府県(親キー).Add 子キー, arr(r, 4)
        
    End If

Next r

' 都道府県ディクショナリのアイテムを出力
Dim 出力 As Variant
Dim 出力1 As Variant
アイテム ズ は全てのアイテム(データ、値)を返します

For Each 出力 In 都道府県.items
都道府県から直接、市区ディクショナリーを取り出します
    For Each 出力1 In 出力.items
    出力にはそれぞれの市区辞書が取り出され、市区辞書には町村が登録されています
        Debug.Print 出力1 ' 子キーの値を出力
        
    Next 出力1
    
Next 出力

End Sub
都道府県キー 市区辞書 市区キー 町村名
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?