我需要根据条件编写VBA代码: -if订单在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。
我的代码中的问题在哪里?
答案 0 :(得分:1)
这是错误的Range("S" & y - 1 & .Rows.Count).End(xlUp).Value = Cumulative
它评估为例如S9:1048576
,它会抛出错误1004.
将其更改为:
Range("S" & y - 1 & ":S" & .Rows.Count).End(xlUp).Value = Cumulative