📘 Excel逆引き事典

【VBA】特定の文字を含む行をエラー処理付きでコピーする方法

手作業で大量のデータから特定の文字列を含む行だけを選別するのは大変な作業です。この記事では、VBAを使って簡単にその作業を自動化し、効率的に業務を進めましょう。

サンプルコード

VBA
Option Explicit
Sub CopyRowsWithSpecificText()
    Dim ws As Worksheet, targetWs As Worksheet
    Dim lastRow As Long, i As Long
    Dim searchRange As Range, cell As Range
    Dim targetSheetName As String
    Dim searchText As String
    
    ' シートと検索文字列の設定
    Set ws = ThisWorkbook.Sheets("SourceSheet")
    targetSheetName = "TargetSheet"
    searchText = "特定の文字"
    
    ' 目的シートが存在しない場合は作成する
    On Error Resume Next
    Set targetWs = ThisWorkbook.Sheets(targetSheetName)
    If targetWs Is Nothing Then
        Set targetWs = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        targetWs.Name = targetSheetName
    End If
    On Error GoTo 0
    
    ' エラー処理の設定
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' 最終行を取得
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' 検索範囲の定義とループ処理
    For i = 1 To lastRow
        Set cell = ws.Cells(i, 1)
        If InStr(cell.Value, searchText) > 0 Then
            cell.EntireRow.Copy Destination:=targetWs.Cells(targetWs.Rows.Count, "A").End(xlUp).Offset(1, 0)
        End If
    Next i
    
    ' 完了処理
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    MsgBox "コピーが完了しました。", vbInformation
End Sub

よくある質問

Q 元に戻せますか?

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

Q エラーが出たら?

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