📘 Excel逆引き事典

【VBA】特定の文字を含む行を配列を使って高速に抽出する方法

手作業でのデータ抽出は時間がかかるうえ、ミスも増えます。この記事では、特定の文字を含む行を高速に抽出するVBAマクロを作成し、業務効率化を実現します。

サンプルコード

VBA
Option Explicit
Sub ExtractRowsWithKeyword()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    Dim lastRow As Long, i As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    Application.ScreenUpdating = False
    
    Dim keyword As String: keyword = "特定の文字"
    Dim targetRange As Range
    Set targetRange = ws.Range("A1:A" & lastRow)
    
    Dim arr() As Variant, j As Long
    arr = Application.Transpose(Application.Transpose(targetRange.Value))
    ReDim result(1 To UBound(arr), 1 To 1)
    
    For i = LBound(arr) To UBound(arr)
        If InStr(1, arr(i, 1), keyword) > 0 Then
            j = j + 1
            result(j, 1) = ws.Cells(i + targetRange.Row - 1, targetRange.Column).Address
        End If
    Next i
    
    Dim outputWs As Worksheet
    Set outputWs = ThisWorkbook.Sheets("OutputSheet")
    outputWs.Range("A1:A" & j).Value = Application.Transpose(result)
    
    Application.ScreenUpdating = True
End Sub

よくある質問

Q 元に戻せますか?

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

Q エラーが出たら?

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