问题
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.
回答1:
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
andColumns
e.g.Current.Cells
,Current.Rows.Count
... - You don't have to activate
Current
.Current
is theActiveSheet
in your case (since you have activated it), so no need to useActiveSheet
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
来源:https://stackoverflow.com/questions/65049675/vba-looping-through-sheets-removing-duplicates