将值的最后一行范围与VBA中的一组行进行比较

时间:2019-01-25 08:33:22

标签: excel vba range

我基本上是从一个单元格输入数据,然后将其复制到另一组单元格,如下表所示。现在,我需要检查输入数据是否与以前的数据相同。如果相同,我将清除该行并将其从表中删除。

DATA1 DATA2 DATA3
cat    1    white
dog    2    white
dog    1    brown
cat    1   white (should be compared and removed from table - similar with 1st row)

我尝试过使用For循环功能。但是,范围值不能接受Range("S" & Lastrow & ":" & "X" & Lastrow)。您能告诉我正确的格式是什么吗?谢谢!

Sub RowCompare()

    Dim ary1() As Variant
    Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range

    Set xWs = ThisWorkbook.Sheets("Summary")
    LastRow = xWs.Range("T" & Rows.Count).End(xlUp).Row + 1 

    'Check last row with previous rows
    Set Range1 = Range("S5:X" & LastRow)

    For i = LastRow - 1 To 2 Step -1
        Set Range2 = Range("S")
        Set rr1 = Range1.Rows(1)
        Set rr2 = Range2.Rows(1)
        ary1 = Application.Transpose(Application.Transpose(rr1))
        ary2 = Application.Transpose(Application.Transpose(rr2))
        st1 = Join(ary1, ",")
        st2 = Join(ary2, ",")
        If st1 = st2 Then
            MsgBox "UPH already plotted"
            Exit Sub
        End If
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

例如公式

=COUNTIFS(A:A,A:A,B:B,B:B,C:C,C:C)

如果当前行重复则返回>1

enter image description here

您也可以在VBA中使用它

Option Explicit

Public Sub TestIfLastRowIsDuplicate()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim LastRow As Long 'find last used row
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim Cnt As Long 'count how many duplicates of last row exist
    Cnt = WorksheetFunction.CountIfs(ws.Range("A:A"), ws.Range("A" & LastRow), _
                                     ws.Range("B:B"), ws.Range("B" & LastRow), _
                                     ws.Range("C:C"), ws.Range("C" & LastRow))

    If Cnt > 1 Then
        MsgBox "Last row is duplicate"
    Else
        MsgBox "Last row is unique"
    End If
End Sub