Excel VBA | 数値と文字列を完全に分けて、数値を先に並べてから文字列を並べる方法

Excel VBA VBA
スポンサーリンク

数値と文字列を完全に分けて、数値を先に並べてから文字列を並べる方法(VBA)

配列に 数値と文字列が混在している場合、単純にソートすると型の違いで期待通りにならないことがあります。そこで「数値だけを先に並べ、その後に文字列を並べる」方法を紹介します。


1. 数値と文字列を分ける

まず、配列を走査して 数値配列文字列配列 に分けます。

Sub SplitAndSortMixedArray()
    Dim arr As Variant
    arr = Array("Banana", 10, "Apple", 2, 1, "Cherry")
    
    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
VB

2. 昇順ソート関数(汎用)

    ' 数値配列を昇順ソート
    nums = SortArray(nums, True)
    
    ' 文字列配列を昇順ソート
    strs = SortArray(strs, True)
VB
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
VB

3. 結果を結合して出力

    ' 結果を結合
    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
VB

4. 出力例

元の配列:

("Banana", 10, "Apple", 2, 1, "Cherry")
VB

結果(昇順ソート+数値先頭):

1
2
10
Apple
Banana
Cherry

まとめ

  • 数値と文字列を分けるIsNumeric で判定
  • それぞれソート → 数値は数値順、文字列は文字列順
  • 結合して出力 → 数値を先に並べ、その後に文字列

👉 この方法を使えば「数値を先に並べてから文字列を並べる」ことができ、混在配列でも整理された結果を得られます。

タイトルとURLをコピーしました