根据if条件和每个循环,求和范围内的值

时间:2019-02-13 12:30:18

标签: excel vba for-loop if-statement

我有3列数据(为便于理解,我提供了一个子集)。第一列显示标签编号,第二列显示标签编号的数量,第三列价格。

我想对第3列中的标签的价格求和,但前提是第2列中的“数量”> = 1,否则什么也不做。

数据:

enter image description here

所需结果:

enter image description here

结果是,如果第2列中的数量> = 1,则将Label1的所有值中的第3列价格相加并分配给每个标签。对于其他所有商品,价格不会改变,因为数量为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

1 个答案:

答案 0 :(得分:1)

内置的功能可以为您提供帮助。

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)