数値を降順、文字列を昇順に並べる応用例(VBA)
「数値と文字列が混在した配列」を 数値は降順、文字列は昇順 に並べる方法を紹介します。ポイントは 数値と文字列を分けてソート → 結合 です。
1. 汎用ソート関数(昇順・降順切替可能)
Function SortArray(arr 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)
If ascending Then
If tmp(i) > tmp(j) Then t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
Else
If tmp(i) < tmp(j) Then t = tmp(i): tmp(i) = tmp(j): tmp(j) = t
End If
Next j
Next i
SortArray = tmp
End Function
VB2. 数値と文字列を分けてソート
Sub SortMixedArrayExample()
Dim arr As Variant
arr = Array("Banana", 10, "Apple", 2, 1, "Cherry", 20)
Dim nums() As Variant, strs() As Variant
Dim i As Long, nCount As Long, sCount As Long
' 数値と文字列を分ける
For i = LBound(arr) To UBound(arr)
If IsNumeric(arr(i)) Then
nCount = nCount + 1
ReDim Preserve nums(1 To nCount)
nums(nCount) = CDbl(arr(i))
Else
sCount = sCount + 1
ReDim Preserve strs(1 To sCount)
strs(sCount) = CStr(arr(i))
End If
Next i
' 数値は降順、文字列は昇順でソート
If nCount > 0 Then nums = SortArray(nums, False)
If sCount > 0 Then strs = SortArray(strs, True)
' 結果を結合
Dim result() As Variant, idx As Long
ReDim result(1 To nCount + sCount)
idx = 1
' 数値を先に(降順)
For i = LBound(nums) To UBound(nums)
result(idx) = nums(i)
idx = idx + 1
Next i
' 文字列を後に(昇順)
For i = LBound(strs) To UBound(strs)
result(idx) = strs(i)
idx = idx + 1
Next i
' 出力確認
For i = LBound(result) To UBound(result)
Debug.Print result(i)
Next i
End Sub
VB3. 出力例
元の配列:
("Banana", 10, "Apple", 2, 1, "Cherry", 20)
VB結果(数値降順 → 文字列昇順):
20
10
2
1
Apple
Banana
Cherry
まとめ
- IsNumeric で数値と文字列を分ける
- 数値は降順、文字列は昇順でソート
- 結合して出力 → 数値が先、文字列が後
👉 この応用例を使えば「数値を降順、文字列を昇順に並べる」ことができ、混在配列でも整理された結果を得られます。


