特定の文字列(例:”Apple”)を最優先に並べるカスタムソート(VBA)
通常のソートでは「昇順」「降順」しか選べませんが、特定の文字列を最優先に並べるカスタムルールを組み込むことで、任意の要素を先頭に持ってくることができます。
1. カスタムソート関数
Function SortWithPriority(arr As Variant, priority As String, 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)
' ★ 優先文字列を最優先に並べる
If vi = priority And vj <> priority Then
' viが優先 → そのまま
ElseIf vj = priority And vi <> priority Then
' vjが優先 → 入れ替え
t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
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
SortWithPriority = tmp
End Function
VB2. 使用例
Sub TestPrioritySort()
Dim arr As Variant
arr = Array("Banana", "Apple", "Cherry", "Orange", "Grape")
Dim sortedArr As Variant
sortedArr = SortWithPriority(arr, "Apple", True) ' "Apple"を最優先
Dim i As Long
For i = LBound(sortedArr) To UBound(sortedArr)
Debug.Print sortedArr(i)
Next i
End Sub
VB3. 出力例
元の配列:
("Banana", "Apple", "Cherry", "Orange", "Grape")
VB結果(”Apple”を最優先 → 残りは昇順):
Apple
Banana
Cherry
Grape
Orange
応用ポイント
- 優先文字列を複数指定したい場合は、
priorityを配列にして判定を拡張すればOK - 数値と文字列が混在していても、
IsNumeric判定を組み合わせれば柔軟に対応可能 - 「特定の文字列を最優先に並べる」ルールは、データ分析や検索結果の整理に便利
👉 この方法を使えば「Appleを最優先に並べる」だけでなく、任意の文字列を先頭に持ってくるカスタムソートが可能になります。


