📊 Excel VBA Top100
🔄

TrimSpaces

データ処理

選択範囲のセルから前後の余分なスペースを削除します

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: 対象範囲を選択してから TrimSpaces を実行します

💻 VBAコード

' TrimSpaces
' -----------------
' Macro Name: TrimSpaces
' Description: 選択範囲のセルから前後の余分なスペースを削除します
' Parameters: なし
' Returns: なし
' Usage: 対象範囲を選択してから TrimSpaces を実行します
' -----------------

Sub TrimSpaces()
    On Error GoTo ErrorHandler

    Dim rng As Range
    Dim cell As Range
    Dim trimmedCount As Long
    Dim original As String

    If TypeName(Selection) <> "Range" Then
        MsgBox "セル範囲を選択してから実行してください", vbCritical, "エラー"
        Exit Sub
    End If

    Set rng = Selection
    trimmedCount = 0

    For Each cell In rng
        If Not IsEmpty(cell) And VarType(cell.Value) = vbString Then
            original = cell.Value
            cell.Value = Trim(cell.Value)
            If cell.Value <> original Then trimmedCount = trimmedCount + 1
        End If
    Next cell

    MsgBox trimmedCount & " セルのスペースを削除しました", vbInformation, "完了"

    Exit Sub

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