删除重复项-忽略列

时间:2018-06-21 18:18:03

标签: excel vba

我正在创建一个宏,该宏选择具有日期的所有单元格,然后在不考虑J或K列的情况下删除重复项。

我只是试图让VBA仅考虑A列(从A3开始,第1行和第2行是标题行)进行测试。

Dim sht As Worksheet
Dim lastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Credit Time")
Set StartCell = Range("A3")

lastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

sht.Range(StartCell, sht.Cells(lastRow, LastColumn)).Select
RemoveDuplicates Column:=1 Header:=xlNo

如果我编辑RemoveDup...行,则所有数据均被选择为完美。

1 个答案:

答案 0 :(得分:0)

构造您的列数组,以在删除第J和K列时动态删除重复项时考虑。

Option Explicit

Sub Macro1()
    Dim lastRow As Long, LastColumn As Long, StartRow As Long
    Dim i As Long, arr As Variant

    With Worksheets("Credit Time")

        StartRow = 3
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        LastColumn = .Cells(StartRow, .Columns.Count).End(xlToLeft).Column

        ReDim arr(0 To LastColumn - 3)
        For i = 1 To LastColumn
            If i <> Range("J:J").Column And i <> Range("K:K").Column Then
                arr(i - 1 + Int(i > Range("K:K").Column) * 2) = i
            End If
        Next i

        'arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 12)

        With .Range(.Cells(StartRow, "A"), .Cells(lastRow, LastColumn))
            .RemoveDuplicates Columns:=(arr), Header:=xlNo
        End With
    End With
End Sub

(arr)不是错字; vba必须将变体数组识别为列索引号的数组。