📊 Excel VBA Top100
📋

SortSheetsByName

シート管理

シートを名前順に並べ替える

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: 実行するとシートがアルファベット順に並べ替えられる

💻 VBAコード

' SortSheetsByName
' -----------------
' Macro Name: SortSheetsByName
' Description: シートを名前順に並べ替える
' Parameters: なし
' Returns: なし
' Usage: 実行するとシートがアルファベット順に並べ替えられる
' -----------------

Sub SortSheetsByName()
    Dim ws As Worksheet
    Dim sheetNames() As String
    Dim i As Long
    Dim j As Long
    Dim temp As String
    Dim sheetCount As Long

    On Error GoTo ErrorHandler

    sheetCount = Worksheets.Count

    If sheetCount <= 1 Then
        MsgBox "シートが1つしかないため並べ替えの必要はありません。", vbInformation
        Exit Sub
    End If

    ReDim sheetNames(1 To sheetCount)
    For i = 1 To sheetCount
        sheetNames(i) = Worksheets(i).Name
    Next i

    For i = 1 To sheetCount - 1
        For j = i + 1 To sheetCount
            If StrComp(sheetNames(i), sheetNames(j), vbTextCompare) > 0 Then
                temp = sheetNames(i)
                sheetNames(i) = sheetNames(j)
                sheetNames(j) = temp
            End If
        Next j
    Next i

    For i = 1 To sheetCount
        Worksheets(sheetNames(i)).Move Before:=Worksheets(i)
    Next i

    MsgBox sheetCount & "枚のシートを名前順に並べ替えました。", vbInformation
    Exit Sub

ErrorHandler:
    MsgBox "エラーが発生しました: " & Err.Description, vbCritical
End Sub