【问题标题】:Sum values in the range based on if condition and for each loop根据 if 条件和每个循环对范围内的值求和
【发布时间】:2019-02-13 12:30:17
【问题描述】:

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

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

数据:

期望的结果:

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

【问题讨论】:

    标签: excel vba for-loop if-statement


    【解决方案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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多