Excel VBA | キーと値を両方ソートして出力する応用例

VBA
スポンサーリンク

Dictionaryの「キー」と「値」を両方ソートして出力する応用例

通常の Scripting.Dictionary は順序を保持しませんが、キー順・値順の両方で並べ替えて出力することが可能です。即時ウィンドウでのデバッグや中身確認に役立ちます。


1. キーでソートして出力

For Each k In SortArray(dict.Keys): Debug.Print k & " => " & dict(k): Next
VB

👉 キーを昇順に並べて「キー => 値」を出力します。


2. 値でソートして出力

For Each v In SortArray(dict.Items): For Each k In dict.Keys: If dict(k)=v Then Debug.Print k & " => " & v: Exit For: Next: Next
VB

👉 値を昇順に並べて「キー => 値」を出力します。


3. 両方ソートして出力する応用例

補助関数(標準モジュールに置く)

Function SortArray(arr As Variant) As Variant
    Dim tmp As Variant, i As Long, j As Long, t As Variant
    tmp = arr
    For i = LBound(tmp) To UBound(tmp) - 1
        For j = i + 1 To UBound(tmp)
            If tmp(i) > tmp(j) Then
                t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
            End If
        Next j
    Next i
    SortArray = tmp
End Function
VB

即時ウィンドウで両方確認

' キー順
For Each k In SortArray(dict.Keys): Debug.Print "[KeySort] " & k & " => " & dict(k): Next

' 値順
For Each v In SortArray(dict.Items): For Each k In dict.Keys: If dict(k)=v Then Debug.Print "[ValSort] " & k & " => " & v: Exit For: Next: Next
VB

4. 実行例

Sub TestDictSortBoth()
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    dict.Add "C", "Cherry"
    dict.Add "A", "Apple"
    dict.Add "B", "Banana"
    
    Stop   ' ← 即時ウィンドウでワンライナーを実行
End Sub
VB

即時ウィンドウ出力例:

[KeySort] A => Apple
[KeySort] B => Banana
[KeySort] C => Cherry

[ValSort] A => Apple
[ValSort] B => Banana
[ValSort] C => Cherry

💡 まとめ

  • キー順ソートSortArray(dict.Keys)
  • 値順ソートSortArray(dict.Items) を使い、キーを逆引き
  • 即時ウィンドウでワンライナーを実行すれば「キー順」「値順」の両方を一気に確認可能

👉 この応用例を使えば「キーと値を両方ソートして出力」できるので、Dictionaryの中身を整理して確認するのに最適です。

VBA
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました