3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBAの備忘録 DictionaryをKey昇順でソートする

Last updated at Posted at 2019-06-19

.NET FrameworkのArrayListクラスを利用して、
DictionaryをKey昇順でソートする。
ホンマに便利でおます。
【注意】
 サンプルの関数は「Keyは文字列で同じ文字数であること」が条件になります。
 Keyが自由な場合は、Key、Itemをそれぞれdictionaryに入れ、再度組み合わせる…等、もうひと捻り必要ですね。

関数側

Public Function Dic昇順(ByRef dic As Dictionary)
    '------------------------------------------------------------------
    'DictionaryをKeyの昇順に並び替える。
    '[流れ]
    ' ByRefで引数を受け、
    ' ArrayListクラスのSortメソッドで昇順に並べ替えて、dicに戻す。
    '------------------------------------------------------------------
    
    Dim i As Long
    Dim KeyItem_AryList As Object   '// ArrayList
    Dim KeyItem As String
    Dim temp As Variant 'splitのデータ受け用

    
    '// .NET FrameworkのArrayListクラスを利用する
    Set KeyItem_AryList = CreateObject("System.Collections.ArrayList")
    
    '先ずはArrayListに移す。
    Dim curKey As Variant
    For Each curKey In dic
        KeyItem = curKey & "_" & dic(curKey) 'ソート後スプリットする
        KeyItem_AryList.Add KeyItem
    Next curKey
    
    KeyItem_AryList.Sort   '移し替えた方をソート!!!これ便利!!!
    
    dic.RemoveAll  '一旦、消し去る
     
    'もう一度入れなおす。
    For i = 0 To KeyItem_AryList.Count - 1
        temp = Split(KeyItem_AryList(i), "_")
        dic(temp(0)) = temp(1)
    Next i
    
    
    '確認
'    For Each curKey In dic
'        Debug.Print (curKey & ":" & dic(curKey))
'    Next curKey

End Function

呼び出し側

呼び出し側

Call Dic昇順(dicAAA)
3
1
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?