我有3列数据(为了便于理解,我提供了一个子集)。第一列显示标签编号,第二列显示标签编号的数量,第三列显示价格。
我想总结第3列中标签的价格,但仅当第2列中的数量> = 1时,否则什么都不做。
数据:
期望的结果:
在结果中,第3列中的价格从Label1的所有值中求和,并分配给每个标签如果第2列中的数量> = 1。对于所有其他人,价格不会因为数量为0而改变。
我得到了所用范围的不匹配。我不确定是否应该使用数组:
Sub test()
Dim cell As Range
Dim cell2 As Range
Dim rngLabel As Range
Dim rngQuantity As Range
Dim rngAmount As Range
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Sheet3")
With ws1
Set rngLabel = .Range(.Cells(3, 1), .Cells(.Rows.Count, 1))
Set rngQuantity = .Range(.Cells(3, 2), .Cells(.Rows.Count, 2))
Set rngAmount = .Range(.Cells(3, 3), .Cells(.Rows.Count, 3))
For Each cell In rngLabel.Cells
For Each cell2 In rngAmount.Cells
If rngQuantity.Value >= 1 Then
cell = WorksheetFunction.Sum(rngAmount)
End If
Next cell2
Next cell
End With
End Sub
有内置功能可以帮助您。
sub test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Sheet3")
With ws1
with .range(.cells(3, "A"), .cells(.rows.count, "C").end(xlup).offset(0, 1))
.columns(4).cells.formular1c1 = "=if(rc[-2]>0, sumifs(c[-1], c[-3], rc[-3]), rc[-1])"
.columns(3).cells = .columns(4).cells.value
.columns(4).cells.clear
end with
end with
end sub
顺便说一下,你的范围对象一直被设置到工作表的底部。你最后错过了.end(xlup)
。