这是对我给出公式的同一件事的 VBA 尝试。我认为没有必要,但无论如何,OP 可能会从中吸取教训。干杯!
Sub ertdfgcvb()
Dim LastRow As Long, DatesCol As Long, AmountsCol As Long, a As Double, b As Double
LastRow = Cells.Find(What:="*", SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row
DatesCol = 4 'D column with dates
AmountsCol = 5 'E column with amounts
Columns(DatesCol).Interior.ColorIndex = xlNone 'dates lose color
For i = 1 To LastRow 'for each row
If i <> 1 Then 'had some fun with row 0 error
a = Application.WorksheetFunction.SumIfs( _
Range(Cells(1, DatesCol), Cells(i - 1, DatesCol)), _
Range(Cells(1, DatesCol), Cells(i - 1, DatesCol)), _
Cells(i, DatesCol), _
Range(Cells(1, AmountsCol), Cells(i - 1, AmountsCol)), _
Cells(i, AmountsCol)) 'counts the date values associated with recurrences before
Else
a = 0 'if it's first row I declared a zero, I don't know why
End If
If i <> LastRow Then 'yeah, last row stuff
b = Application.WorksheetFunction.SumIfs( _
Range(Cells(i + 1, DatesCol), Cells(LastRow, DatesCol)), _
Range(Cells(i + 1, DatesCol), Cells(LastRow, DatesCol)), _
Cells(i, DatesCol), _
Range(Cells(i + 1, AmountsCol), Cells(LastRow, AmountsCol)), _
Cells(i, AmountsCol)) 'counts the date values associated with recurrences after
Else
b = 0 'if it's the last row, there are definitely none after
End If
If a <> 0 Or b <> 0 Then Cells(i, 4).Interior.ColorIndex = 26 'if either one of them isn't 0 then the date value gets a nice background color
Next i
End Sub
使用Countifs 并进行一些优化后,它将如下所示:
Sub ertdfgcvb()
Dim LastRow As Long, DatesCol As Long, AmountsCol As Long
LastRow = Cells.Find(What:="*", SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row
DatesCol = 4 'D column with dates
AmountsCol = 5 'E column with amounts
Columns(DatesCol).Interior.ColorIndex = xlNone 'dates lose color
For i = 1 To LastRow 'for each row
If 1 < Application.WorksheetFunction.CountIfs(Range(Cells(1, DatesCol), Cells(LastRow, DatesCol)), _
Cells(i, DatesCol), _
Range(Cells(1, AmountsCol), Cells(LastRow, AmountsCol)), _
Cells(i, AmountsCol)) _
Then Cells(i, 4).Interior.ColorIndex = 26 ' 'counts the date values associated with occurrences if there's more than one then the date gets a nice background color
Next i
End Sub