Excel VBAにて配列をソートする。

Cassiopeia2007-05-01

ExcelVBAには配列を並び替えるメソッドがないんですね。
ワークシートのセルを並び替えるメソッドはあるのでそっちを使うのも良いのですがVBAのコードでソートする必要に迫られまして、作ったのでメモしておきます。
セレクションソートなので大量のデータの並び替えには不向きです。

Sub セレクションソートを試すサンプル()
'■試し方
'   1.sheet1 の cells(1,1) (シートのいちばん左上)
'       から下へ並び替えたい数字なり文字列なりを並べる。
'   2.[ツール]-[マクロ]-[マクロ]-セレクションソート
'       を試すサンプル を実行。
'   3.cells(1,3) から下に並び替えたデータが表示される。

    Dim ar() As Variant
    Dim i As Long
    Dim EndOfLine As Long
    
    EndOfLine = Cells(1, 1).End(xlDown).Row
    
    ReDim ar(1 To EndOfLine)
    
    '並び替える数やら文字列やらを配列に読み込む。
    For i = 1 To EndOfLine
        ar(i) = Cells(i, 1).Value
    Next i
    
    '配列 ar() を並び替える。
    Selectionsort ar
    
    '並び替えた配列を表示する。
    For i = 1 To UBound(ar)
        Cells(i, 3) = ar(i)
    Next i

End Sub


Sub Selectionsort(values() As Variant)

    Dim i As Long
    Dim j As Long
    Dim smallest_value As Variant
    Dim smallest_j As Long
    Dim max As Long
    Dim min As Long
    
    max = UBound(values)
    min = LBound(values)
    
    For i = min To max - 1
        smallest_value = values(i)
        smallest_j = i
        For j = i + 1 To max
            If values(j) < smallest_value Then
                smallest_value = values(j)
                smallest_j = j
            End If
        Next j
        If smallest_j <> i Then
            values(smallest_j) = values(i)
            values(i) = smallest_value
        End If
    Next i
End Sub