Removing Duplicates dynamic columns VBA

rconverse

Well-known Member
Joined
Nov 29, 2007
Messages
1,187
Hello,

I have a loop that I've set up to go through each worksheet in a workbook and perform a series of tasks. The last task is to remove duplicates. The issue is that each worksheet could have a different number of columns. Is there a way to dynamically create an array for Excel to remove duplicates?

In the first worksheet, there are 22 columns, so this works:

Code:
rng.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)

However, the next spreadsheet only has 17 columns, so that won't work. I don't want to setup a case or if statement for each worksheet because a column may get added down the road and I don't want to have to touch the code going forward. I can get the last column with data, no problem. I just need to incorporate that in the above code as opposed to hard coded numbers.

Thanks in advance for any suggestions.

Roger
 
I have found fully worked solution for this thread for any one who looking for clear answer.

Code:
 Dim ws As Worksheet
Dim c As Long
Dim varItems() As Variant

With ws.UsedRange
        ReDim varItems(0 To .Columns.Count - 1)
        For c = 1 To .Columns.Count
            varItems(c - 1) = c
        Next c
        .RemoveDuplicates Columns:=(varItems), Header:=xlGuess
  End With
 
Upvote 0

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
Post 11 is correct.
But why does the Columns argument have to be in parenthesis

This works:
Code:
.RemoveDuplicates Columns:=(varItems), Header:=xlGuess
This does not:
Code:
.RemoveDuplicates Columns:=varItems, Header:=xlGuess
 
Upvote 0

Forum statistics

Threads
1,223,889
Messages
6,175,226
Members
452,620
Latest member
dsubash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top