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?

More than 3 years have passed since last update.

VBA / Dictionaryの(Keyではなく)Item値でソートする

Posted at

VBA / Dictionaryの(Keyではなく)Item値でソートする

・やや力技だが、Item値でソートする例
・DictionaryのKeyとItemを、順序を入れ替えて、ArrayListに格納している
・KeyとItemは適当なデリミタ(ここではΩ)で区切っている
・ArrayListのSort機能で並び替えている。
・Item値がきれいに並ぶようにFormatで形を揃ている点注意
・並び替えた後、デリミタでSplitして、別のDictionaryに戻している

sample.xlsm
Option Explicit

Sub sample_dictionary_sort_by_items()

'参照設定:Microsoft Scripting Runtime
Dim dict As Scripting.Dictionary
'Set dict = CreateObject("Scripting.Dictionary")
Set dict = New Scripting.Dictionary

dict.Add "a", Rnd()
dict.Add "b", Rnd()
dict.Add "c", Rnd()
dict.Add "d", Rnd()
dict.Add "e", Rnd()

Dim arr
Set arr = CreateObject("System.Collections.ArrayList")

Dim ky
For Each ky In dict.Keys
    arr.Add Format(dict.Item(ky), "0.00000") & "Ω" & ky
Next
arr.Sort
'arr.Reverse

Dim a1
For Each a1 In arr
    Debug.Print a1
Next

Dim dict2 As Scripting.Dictionary
Set dict2 = New Scripting.Dictionary

Dim o() As String

Dim a2
For Each a2 In arr
    o = Split(a2, "Ω")
    dict2.Add o(1), CDbl(o(0))
Next

For Each ky In dict2.Keys
    Debug.Print ky & "_" & dict2.Item(ky)
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?