📘 Excel逆引き事典

【VBA】重複データを部分一致で配列に格納する方法

手作業で大量のデータから部分一致する重複データを探すのは大変です。この記事では、VBAを使って簡単に重複データを配列に格納し、業務効率化を図ります。

サンプルコード

VBA
Option Explicit
Sub PartialMatchDuplicateDataToArray()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim lastRow As Long, i As Long, j As Long
    Dim dataRange As Range
    Dim arr() As Variant
    Dim partialMatches() As String
    Dim isDuplicate As Boolean
    
    ' データ範囲を取得
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    Set dataRange = ws.Range("A2:A" & lastRow)
    arr = dataRange.Value
    
    ReDim partialMatches(0 To UBound(arr))
    For i = LBound(arr) To UBound(arr)
        isDuplicate = False
        For j = LBound(partialMatches) To i - 1
            If InStr(arr(i, 1), partialMatches(j)) > 0 Then
                ' 部分一致が見つかった場合、配列に格納しない
                isDuplicate = True
                Exit For
            End If
        Next j
        
        If Not isDuplicate Then
            ReDim Preserve partialMatches(UBound(partialMatches) + 1)
            partialMatches(UBound(partialMatches)) = arr(i, 1)
        End If
    Next i
    
    ' 配列の最後の要素を削除(空き領域をクリア)
    ReDim Preserve partialMatches(UBound(partialMatches) - 1)
    
    ' 結果表示(デバッグ用)
    For i = LBound(partialMatches) To UBound(partialMatches)
        Debug.Print partialMatches(i)
    Next i
End Sub

よくある質問

Q 元に戻せますか?

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

Q エラーが出たら?

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