📘 Excel逆引き事典

【VBA】重複データをバックグラウンドで削除する方法

日々の業務の中で大量のデータを扱う際、重複データの存在は作業効率を大きく下げる原因となります。この記事では、VBAを使用して重複データを高速にバックグラウンドで削除する方法を紹介します。これにより、手動での重複チェックと削除から解放され、業務効率が大幅に向上します。

サンプルコード

VBA
Option Explicit
Sub RemoveDuplicateData()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("シート1")
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' 最終行を取得
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    
    ' A列のデータを一時的にB列にコピー
    ws.Range("A2:A" & lastRow).Copy Destination:=ws.Range("B2")
    
    ' B列のデータをソート
    ws.Sort.SortFields.Clear
    With ws.Sort
        .SortFields.Add Key:=ws.Range("B2:B" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .SetRange ws.Range("A1:B" & lastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .Apply
    End With
    
    ' 重複データを削除
    Dim i As Long, j As Long
    For i = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row To 2 Step -1
        If ws.Range("B" & i) = ws.Range("B" & (i + 1)) Then
            ws.Rows(i).Delete
        End If
    Next i
    
    ' B列のデータを削除
    ws.Columns("B").ClearContents
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

よくある質問

Q 元に戻せますか?

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

Q エラーが出たら?

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