Excel VBA | 複数の優先文字列を順番に並べるカスタムソート

VBA
スポンサーリンク

複数の優先文字列を順番に並べるカスタムソート(VBA)

「特定の文字列を最優先に並べたい」ケースをさらに拡張して、複数の優先文字列を指定した順番で並べるカスタムソートを作る方法です。
例:"Apple""Banana" → その他を昇順


1. カスタムソート関数

Function SortWithMultiPriority(arr As Variant, priorities As Variant, Optional ascending As Boolean = True) 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)
            Dim vi As Variant, vj As Variant
            vi = tmp(i): vj = tmp(j)
            
            ' 優先順位を判定
            Dim pi As Long, pj As Long
            pi = GetPriorityIndex(vi, priorities)
            pj = GetPriorityIndex(vj, priorities)
            
            If pi <> pj Then
                ' 優先順位が違う場合 → 小さい方を先に
                If pi > pj Then
                    t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
                End If
            Else
                ' 優先順位が同じ場合 → 通常の昇順/降順比較
                If ascending Then
                    If CStr(vi) > CStr(vj) Then t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
                Else
                    If CStr(vi) < CStr(vj) Then t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
                End If
            End If
        Next j
    Next i
    
    SortWithMultiPriority = tmp
End Function

' 優先文字列のインデックスを返す(見つからなければ大きな値)
Function GetPriorityIndex(val As Variant, priorities As Variant) As Long
    Dim i As Long
    For i = LBound(priorities) To UBound(priorities)
        If val = priorities(i) Then
            GetPriorityIndex = i
            Exit Function
        End If
    Next i
    GetPriorityIndex = 9999 ' 優先外は後回し
End Function
VB

2. 使用例

Sub TestMultiPrioritySort()
    Dim arr As Variant
    arr = Array("Cherry", "Banana", "Apple", "Orange", "Grape")
    
    Dim priorities As Variant
    priorities = Array("Apple", "Banana")   ' 優先順序を指定
    
    Dim sortedArr As Variant
    sortedArr = SortWithMultiPriority(arr, priorities, True)
    
    Dim i As Long
    For i = LBound(sortedArr) To UBound(sortedArr)
        Debug.Print sortedArr(i)
    Next i
End Sub
VB

3. 出力例

元の配列:

("Cherry", "Banana", "Apple", "Orange", "Grape")
VB

結果(”Apple” → “Banana” → その他昇順):

Apple
Banana
Cherry
Grape
Orange

応用ポイント

  • priorities = Array("Apple", "Banana", "Cherry") のように複数指定可能
  • 優先外の要素は通常の昇順/降順で並べ替え
  • 数値や混在配列でも IsNumeric 判定を組み合わせれば柔軟に対応可能

👉 この方法を使えば「複数の優先文字列を指定した順番で並べる」カスタムソートが可能になります。

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