问题
I am basically inputting data from a cell and copying it to another set of cells as seen on the table below as an example. Now I need to check if the input data is the same as the previous ones. If it is the same, I will clear that row and remove it form the table.
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)
I have tried using a For loop function. However, Range value cannot accept Range("S" & Lastrow & ":" & "X" & Lastrow)
. Could you please advise what should be the correct format for this? Thank you!
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:
For example the formula
=COUNTIFS(A:A,A:A,B:B,B:B,C:C,C:C)
results in >1
if the current row is a duplicate:
You could also use this in 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
来源:https://stackoverflow.com/questions/54361585/compare-last-row-range-of-values-to-a-set-of-rows-in-vba