📊 Excel VBA Top100

BatchRename

自動化

A列にある文字列を一括でB列の文字列に置換してC列に出力します

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: A列に元の文字列、B列に新しい文字列を入力してから BatchRename を実行します

💻 VBAコード

' BatchRename
' -----------------
' Macro Name: BatchRename
' Description: A列にある文字列を一括でB列の文字列に置換してC列に出力します
' Parameters: なし
' Returns: なし
' Usage: A列に元の文字列、B列に新しい文字列を入力してから BatchRename を実行します
' -----------------

Sub BatchRename()
    On Error GoTo ErrorHandler

    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim renamedCount As Long

    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    If lastRow < 2 Then
        MsgBox "A列に元の文字列、B列に新しい文字列を入力してください", vbCritical, "エラー"
        Exit Sub
    End If

    ws.Cells(1, 3).Value = "結果"
    renamedCount = 0

    For i = 2 To lastRow
        Dim original As String
        Dim renamed As String
        original = CStr(ws.Cells(i, 1).Value)
        renamed = CStr(ws.Cells(i, 2).Value)
        If original <> "" And renamed <> "" Then
            ws.Cells(i, 3).Value = renamed
            renamedCount = renamedCount + 1
        End If
    Next i

    MsgBox renamedCount & " 件を処理しました(C列に出力)", vbInformation, "完了"

    Exit Sub

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