即時ウィンドウでDictionaryのキーと値をソートして出力する便利なワンライナー
Scripting.Dictionary はキーや値の順序を保持しませんが、Keysを配列として取得 → Sort → 出力 すれば即時ウィンドウでソート済み一覧を確認できます。
キーでソートして出力するワンライナー
For Each k In SortArray(dict.Keys): Debug.Print k & " => " & dict(k): Next
VB補助関数(標準モジュールに置いておく)
Function SortArray(arr As Variant) As Variant
Dim tmp As Variant, i As Long, j As Long
tmp = arr
For i = LBound(tmp) To UBound(tmp) - 1
For j = i + 1 To UBound(tmp)
If tmp(i) > tmp(j) Then
Dim t As Variant
t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
End If
Next j
Next i
SortArray = tmp
End Function
VB実行例
Sub TestDictSort()
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即時ウィンドウで:
For Each k In SortArray(dict.Keys): Debug.Print k & " => " & dict(k): Next
VB出力:
A => Apple
B => Banana
C => Cherry
ポイント
dict.Keysは配列なので、ソート関数を通せば順序を制御できる- ワンライナーで「キー => 値」のペアを即時ウィンドウに出力可能
- 値でソートしたい場合は
dict.Itemsをソートしてキーを逆引きする
👉 このテクニックを使えば「Dictionaryの中身をソートして一覧表示」できるので、デバッグや確認がぐっと楽になります。


