VBA根据条件在行中总结值

我需要根据条件编写一个VBA代码: – 如果在D列,F列,P列和P列=单元中有相同的值,则在列Q中求和值; 如果列P =数量然后总结列S中的值

Dim lastrow1 As Long Dim startrow As Long Dim Cumulative As Variant Dim y As Long With Wb2.Worksheets.Item(1) lastrow1 = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row Cumulative = 0 startrow = 4 'Row where your data starts + 1, so row 3 + 1 in this case For y = startrow To lastrow1 If Range("P" & y - 1).Value = "Unit" Then Cumulative = Cumulative + Range("Q" & y - 1).Value If Range("F" & y).Value = Range("F" & y - 1).Value And Range("D" & y).Value = Range("D" & y - 1).Value And Range("P" & y).Value = Range("P" & y - 1).Value Then Range("Q" & y - 1 & .Rows.Count).End(xlUp).Value = Cumulative Cumulative = 0 End If ElseIf Range("P" & y - 1).Value = "Amount" Then Cumulative = Cumulative + Range("S" & y - 1).Value If Range("F" & y).Value = Range("F" & y - 1).Value And Range("D" & y).Value = Range("D" & y - 1).Value And Range("P" & y).Value = Range("P" & y - 1).Value Then Range("S" & y - 1 & .Rows.Count).End(xlUp).Value = Cumulative Cumulative = 0 End If End If Next y End With 

但代码不起作用,我得到了Range("S" & y - 1 & .Rows.Count).End(xlUp).Value = Cumulative对象错误1004。

我的代码中的问题在哪里?

这是错误的Range("S" & y - 1 & .Rows.Count).End(xlUp).Value = Cumulative

它的计算结果如S9:1048576 ,这将抛出错误1004。

将其更改为:

Range("S" & y - 1 & ":S" & .Rows.Count).End(xlUp).Value = Cumulative