매크로 예제를 사용하여 Excel 목록에서 중복 항목을 삭제하는 방법

추가 정보

Microsoft에서 제공하는 프로그래밍 예제는 예시를 위한 것일 뿐이며 이와 관련하여 명시적이거나 묵시적인 어떠한 보증도 하지 않습니다. 이는 상품성이나 특정 목적에 대한 적합성의 묵시적인 보증을 포함하며 이에 제한되지 않습니다. 이 문서에서는 예제에 사용되고 있는 프로그래밍 언어와 프로시저를 만들고 디버깅하는 데 사용되는 도구를 사용자가 잘 알고 있는 것으로 가정합니다. Microsoft 지원 엔지니어는 사용자에게 도움이 되도록 특정 프로시저에 대한 기능을 설명할 수 있지만 사용자의 특정 요구 사항에 맞도록 예제를 수정하여 추가 기능을 제공하거나 프로시저를 구성하지는 않습니다.

샘플 1: 단일 목록에서 중복 항목 삭제

다음 샘플 매크로는 A1:A100 범위의 단일 목록을 검색하고 목록의 모든 중복 항목을 삭제합니다. 이 매크로를 사용하려면 목록 범위에 빈 셀이 있어야 합니다. 목록에 빈 셀이 포함된 경우 빈 셀이 모두 목록의 끝에 있도록 데이터를 오름차순으로 정렬합니다. 

    Sub DelDups_OneList()
    Dim iListCount As Integer
    Dim iCtr As Integer
    
    ' Turn off screen updating to speed up macro.
    Application.ScreenUpdating = False
    
    ' Get count of records to search through.
    iListCount = Sheets("Sheet1").Range("A1:A100").Rows.Count
    Sheets("Sheet1").Range("A1").Select
    ' Loop until end of records.
    Do Until ActiveCell = ""
       ' Loop through records.
       For iCtr = 1 To iListCount
          ' Don't compare against yourself.
          ' To specify a different column, change 1 to the column number.
          If ActiveCell.Row <> Sheets("Sheet1").Cells(iCtr, 1).Row Then
             ' Do comparison of next record.
             If ActiveCell.Value = Sheets("Sheet1").Cells(iCtr, 1).Value Then
                ' If match is true then delete row.
                Sheets("Sheet1").Cells(iCtr, 1).Delete xlShiftUp
                   ' Increment counter to account for deleted row.
                   iCtr = iCtr + 1
             End If
          End If
       Next iCtr
       ' Go to next record.
       ActiveCell.Offset(1, 0).Select
    Loop
    Application.ScreenUpdating = True
    MsgBox "Done!"
    End Sub

샘플 2: 두 목록 비교 및 중복 항목 삭제

다음 샘플 매크로는 하나의 (마스터) 목록을 다른 목록과 비교하고 마스터 목록에 있는 두 번째 목록에서 중복 항목을 삭제합니다. 첫 번째 목록은 A1:A10 범위의 Sheet1에 있습니다. 두 번째 목록은 A1:A100 범위의 Sheet2에 있습니다. 매크로를 사용하려면 시트를 선택한 다음 매크로를 실행합니다. 

    Sub DelDups_TwoLists()
    Dim iListCount As Integer
    Dim iCtr As Integer
    
    ' Turn off screen updating to speed up macro.
    Application.ScreenUpdating = False
    
    ' Get count of records to search through (list that will be deleted).
    iListCount = Sheets("sheet2").Range("A1:A100").Rows.Count
    
    ' Loop through the "master" list.
    For Each x In Sheets("Sheet1").Range("A1:A10")
       ' Loop through all records in the second list.
       For iCtr = 1 To iListCount
          ' Do comparison of next record.
          ' To specify a different column, change 1 to the column number.
          If x.Value = Sheets("Sheet2").Cells(iCtr, 1).Value Then
             ' If match is true then delete row.
             Sheets("Sheet2").Cells(iCtr, 1).Delete xlShiftUp
             ' Increment counter to account for deleted row.
             iCtr = iCtr + 1
          End If
       Next iCtr
    Next
    Application.ScreenUpdating = True
    MsgBox "Done!"
    End Sub