I am working on a procedure in Excel using VBA that highlights duplicate rows. The procedure evaluates the result of the worksheet function sumproduct to determine if the row has duplicates.
The evaluated formula ends up looking like this:
SUMPRODUCT(--(A1:A10 = A1), --(B1:B10 = B1), --(C1:C10 = C1))
So far the procedure works great, but I need it to disregard hidden rows and columns from the evaluation. I can skip over hidden rows in columns in my loops using Range.Hidden = False
, but I haven't figured out a way to exclude hidden rows and columns from SUMPRODUCT.
I also tried iterating through every row twice using two nested loops and just comparing values two rows at a time, but that resulted in N-squared, or O(n2), iterations, so I gave up on that method.
Is there a way to coerce SUMPRODUCT into ignoring hidden rows, as is possible with the spreadsheet formula SUBTOTAL?
Here is what I have so far using Evaluate(SUMPRODUCT)
: Thanks!
Private Sub ShowDuplicateRows()
Dim lngRow As Long
Dim lngColumn As Long
Dim strFormula As String
With Selection
For lngRow = 1 To .Rows.Count
If Not .Rows(lngRow).Hidden Then
strFormula = "SUMPRODUCT("
For lngColumn = 1 To .Columns.Count
If Not .Columns(lngColumn).Hidden Then
If strFormula <> "SUMPRODUCT(" Then
strFormula = strFormula & ", "
End If
strFormula = strFormula _
& "--(" & .Columns(lngColumn).Address _
& " = " & .Cells(lngRow, lngColumn).Address & ")"
End If
Next
strFormula = strFormula & ")"
If Evaluate(strFormula) > 1 Then
.Rows(lngRow).Font.Color = RGB(255, 0, 0)
End If
End If
Next lngRow
End With
End Sub