问题
The sheets that I am scanning for duplicates have different numbers of columns
I'm trying to specify the array of columns for Range.RemoveDuplicates by using a string like this:
Let's say there are 5 columns in this sheet
Dim Rng As Range
Dim i As Integer
Dim lColumn As Integer
Dim strColumnArray As String
With ActiveSheet
lColumn = Cells(1, Columns.Count).End(xlToLeft).Column
strColumnArray = "1"
For i = 2 To lColumn
strColumnArray = strColumnArray & ", " & i
Next i
'String ends up as "1, 2, 3, 4, 5"
Set Rng = Range(Cells(1, 1), Cells(1, lColumn).End(xlDown))
Rng.RemoveDuplicates Columns:=Array(strColumnArray), Header:=xlNo
End With
And I get the Run-Time error 13 Type Mismatch" error
So I read posts and saw where someone did it by specifying it as an array like this:
Dim Rng As Range
Dim i As Integer
Dim lColumn As Integer
Dim strColumnArray() As String
With ActiveSheet
lColumn = Cells(1, Columns.Count).End(xlToLeft).Column
ReDim strColumnArray(lColumn) As String
For i = 1 To lColumn + 1 'The array needs to start with 1
strColumnArray(i) = i
Next i
Set Rng = Range(Cells(1, 1), Cells(1, lColumn).End(xlDown))
Rng.RemoveDuplicates Columns:=strColumnArray, Header:=xlNo
End With
I've tried it this way:
Rng.RemoveDuplicates(strColumnArray, Header:=xlNo)
amd this way:
Rng.RemoveDuplicates(Columns:=Array(strColumnArray), Header:=xlNo)
and in endless combinations of Variant, String, Integer, etc.
I must just be missing it at this point
any help would be appreciated
回答1:
I had to go back and re-read my post on this. I think the array has to be a Variant
. Anyways, this seems to work:
Sub RemoveDupes()
Dim Rng As Range
Dim i As Integer
Dim lColumn As Integer
Dim ColumnArray As Variant
With ActiveSheet
lColumn = Cells(1, Columns.Count).End(xlToLeft).Column
ReDim ColumnArray(lColumn - 1)
For i = 0 To lColumn - 1 'The array needs to start with 1
ColumnArray(i) = i + 1
Next i
Set Rng = Range(Cells(1, 1), Cells(1, lColumn).End(xlDown))
Rng.RemoveDuplicates Columns:=(ColumnArray), Header:=xlYes
End With
End Sub
来源:https://stackoverflow.com/questions/36814816/excel-2013-vba-range-removeduplicates-issue-specifying-array