Warm tip: This article is reproduced from serverfault.com, please click

VBA looping through sheets removing duplicates

发布于 2020-11-28 12:42:06

I have seen similar things, but my code that seems to be working I just want to check for improvements or what potential bugs, unintended consequences there could be for it.

I have been handed spreadsheets that have ended up getting duplicate information. There are a lot of spreadsheets, some have 100 sheets inside each file. Obviously don't want to go through each sheet manually using remove duplicate information. After searching around I think I have a solution and want your opinions on it. I have a JS background and this is my first time using vba.

Sub RemoveDuplicates()

' RemoveDuplicates Macro ' Selects all values then removes duplicates '

 ' Declare Current as a worksheet object variable.
     Dim Current As Worksheet
     Dim starting_ws As Worksheet
     Set starting_ws = ActiveSheet 'remember which worksheet is active in the beginning

     ' Loop through all of the worksheets in the active workbook.
     For Each Current In Worksheets
        Current.Activate
        
        LastRow = Cells(Rows.Count, "A").End(xlUp).Row
        ActiveSheet.Range("A1" & LastRow).RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Header:=xlYes
  
     Next
     
starting_ws.Activate 'activate the worksheet that was originally active

End Sub

I am only looking for duplicates on each sheet, not compating worksheets. Also the number of columns will stay the same. Thank you very much for your help in advance. Sorry if this is a basic VB thing.

Questioner
Chris MacDonald
Viewed
0
VBasic2008 2020-11-28 23:01:11

Remove Duplicates (Multiple Columns and Worksheets)

  • Use Option Explicit.
  • This ActiveSheet.Range("A1" & LastRow) is surely wrong. Think about it.
  • You have to qualify Range, Cells, Rows and Columns e.g. Current.Cells, Current.Rows.Count...
  • You don't have to activate Current. Current is the ActiveSheet in your case (since you have activated it), so no need to use ActiveSheet instead.
  • Do not let Excel to define the range: you define it.

A Code With a Question

Option Explicit

Sub removeDupes()
     
     ' Here's a question:
     '     Why can't I use 'Cols' instead of the array written explicitly?
     Dim Cols As Variant
     Cols = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
     
     Const FirstAddress As String = "A1"
     Dim wb As Workbook
     Set wb = ActiveWorkbook
     
     Dim ws As Worksheet
     Dim LastCell As Range
     
     For Each ws In wb.Worksheets
         Set LastCell = ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(, 10)
         ws.Range(FirstAddress, LastCell).RemoveDuplicates _
             Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Header:=xlYes
         ' This doesn't work.
         'ws.Range(FirstAddress, LastCell).RemoveDuplicates _
             Columns:=Cols, Header:=xlYes
     Next

End Sub