VBA根据条件汇总行中的值
我需要根据以下条件编写VBA代码: -如果订单在D列、F列、P列和P列中的值相同,则将Q列中的值相加;如果P列=金额,则将S列中的值相加VBA根据条件汇总行中的值,vba,excel,Vba,Excel,我需要根据以下条件编写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:
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)行中得到了range对象错误1004。End(xlUp)。Value=Cumulative
我的代码中的问题在哪里?这是错误的范围(“S”&y-1&.Rows.Count)。结束(xlUp)。值=累积的
它的计算结果类似于例如S9:1048576
,这将抛出错误1004
将其更改为:
范围(“S”&y-1&“:S”&.Rows.Count).End(xlUp).Value=Cumulative
您想要实现什么?你在寻找什么范围?当范围参数失败时检查它。注意,所有这些都可以通过公式完成,而不需要VBA。“S”&y-1和.Rows.Count
肯定是不正确的:为什么要在那里追加Rows.Count
?它会将两个数字(y-1
和.Rows.Count
)的数字连接起来,导致行号超出可接受的范围。这是毫无意义的。什么是Wb2.工作表。项目(1)
?我看不出您是否在任何地方定义了Wb2
。它也可以写为Wb2.Worksheets(1)
——但最好写Wb2.Worksheets(“Sheet1”)
,以防您移动工作表的顺序。您将与一起使用,但仅使用行引用它两次。计数-每个范围和单元格都应该是。范围和单元格,否则它们将引用活动工作表。