【问题标题】:Excel 2013 VBA Range.RemoveDuplicates issue specifying arrayExcel 2013 VBA Range.RemoveDuplicates 指定数组的问题
【发布时间】:2016-08-17 07:46:09
【问题描述】:

我正在扫描的重复工作表具有不同的列数

我正在尝试使用这样的字符串为Range.RemoveDuplicates 指定列数组:

假设这张表格有 5 列

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

我收到运行时错误 13 Type Mismatch" 错误

所以我阅读帖子并通过将其指定为这样的数组来查看某人在哪里做的:

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

我试过这样:

Rng.RemoveDuplicates(strColumnArray, Header:=xlNo)

amd 这样:

Rng.RemoveDuplicates(Columns:=Array(strColumnArray), Header:=xlNo)

还有 Variant、String、Integer 等无穷无尽的组合。

我一定只是想念它在这一点上

任何帮助将不胜感激

【问题讨论】:

标签: arrays excel vba duplicates range


【解决方案1】:

我不得不回去重新阅读my post。我认为数组必须是Variant。无论如何,这似乎有效:

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

【讨论】:

  • 很奇怪。是的 - 它需要变体,并且在括号中()
  • 是的,就是这样。我绕过它,只是没有看到它。感谢您的帮助!
  • 只是好奇,您将数组循环更改为从零开始,当然仍然从 1 开始编号。是否可以跳过第一个位置或会导致数组出错?
  • 我在答案中链接到的帖子说数组必须从零开始。我不确定我是从哪里得到的——它不在我刚刚看过的几个 MSDN 页面中——但简单的测试似乎证明了这一点。如果上面的代码从 1 到 3 更改为 Redim,则会出现“运行时错误 5:无效的过程调用或参数”。
  • 再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
相关资源
最近更新 更多