Excel 使用 VBA 计算范围内的值是否满足特定条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:19:07  来源:igfitidea点击:

Excel to calculate if values in ranges meet certain criteria using VBA

excelvbaif-statementrange

提问by yiannis

I have two ranges in excel, say:

我在 excel 中有两个范围,比如:

x   |    y
------------
 5  |   -1
46  |   -4
 2  |    1
67  |   -1
22  |    1
 6  |    0
34  |    0
 7  |   -2

I want calculate the sum of the second column for values less than O only if the respective values in the first column is less than 10 (i.e sum(y(i)for i<0and x(i)<10) . Hence in this case the sum will be -3.

仅当第一列中的相应值小于 10(即sum(y(i)fori<0x(i)<10)时,我才想为小于 O 的值计算第二列的总和 。因此,在这种情况下,总和将为 -3。

回答by Skip Intro

Assuming your headers are in A1:B1 and your data is A2:B9 use this:

假设您的标题在 A1:B1 中并且您的数据是 A2:B9 使用这个:

=SUMIFS(B2:B9,A2:A9,"<10",B2:B9,"<0")

回答by T I

Try something like

尝试类似的东西

Function calc() AS Integer

    Dim sum AS Integer: sum = 0
    Dim c AS Range

    For Each c In ThisWorkbook.Worksheets(1).Range("A1:A15")
        If c.Value < 10  And c.Offset(0, 1).Value < 0 Then
            sum = sum + c.Offset(0, 1).Value
        End If
    Next c

    calc = sum

End Function