📘 Excel逆引き事典

【VBA】非表示シートの部分一致文字置換

手作業で大量のデータの一部を置き換えるのは大変です。この記事では、非表示のシート内にある特定の文字列を部分一致で置き換える方法を紹介します。

サンプルコード

VBA
Option Explicit
Sub ReplacePartialMatchInHiddenSheet()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim searchStr As String, replaceStr As String
    
    ' 部分一致で置き換える文字列を指定
    searchStr = "部分一致"
    replaceStr = "新しい文字列"
    
    Application.ScreenUpdating = False
    For Each ws In ThisWorkbook.Worksheets
        If ws.Visible = xlSheetHidden Then
            lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
            For i = 1 To lastRow
                If InStr(1, ws.Cells(i, 1), searchStr) > 0 Then
                    ws.Cells(i, 1).Value = Replace(ws.Cells(i, 1).Value, searchStr, replaceStr)
                End If
            Next i
        End If
    Next ws
    Application.ScreenUpdating = True
End Sub

よくある質問

Q 元に戻せますか?

A.
VBAの実行結果は「元に戻す」が効きません。必ずバックアップを取ってから実行してください。

Q エラーが出たら?

A.
シート名や列番号が正しいか確認してください。