VBA - 具有条件的Summing Array列 - 与excel sumif一样

Mar*_*ark 2 arrays vba for-loop while-loop multidimensional-array

我想根据几个条件对数组中的进行求和.如果数据在Excel中,我会使用=SUMIFS公式.

我所拥有的二维数组中的样本数据集是:

ID1     ID2     ID3     Value
0       1       1       4
0       2       2       5
1       3       2       6
0       1       1       3
0       1       0       2
Run Code Online (Sandbox Code Playgroud)

我想根据以下条件求值列:

ID1=0
ID2=1
ID3=1
Run Code Online (Sandbox Code Playgroud)

因此第1行和第4行符合此标准,因此答案为7(4 + 3)

我将如何在VBA中构建它.

请注意,ID可能是无限的,它们可能是字符串,因此我无法ID=0在循环中设置.

A.S*_*erh 5

只是一个关于速度的小警告!

我相信这个问题是针对2D数组而不是针对excel.range,因为excel范围上的循环非常缓慢(仅当你有大量数据时才有效,但我敢打赌,如果你打算使用它,这是通常的情况一个VBA宏;-))

我之前遇到了范围缓慢的问题,直到我发现一些报告此问题的链接(对于10000个单元格的示例,一个用户使用2D阵列报告9,7seg与0,16 seg !!).链接如下.我的建议是始终使用2D数组,简单,干净,快速!

查看更多性能测试:

因此,如果你要处理大量的数据,的Jakub答复的代码应该改变只是有点,为了增益的电源的的二维数组:

Public Function sumIfMultipleConditionsMet2(rng As Range, ParamArray conditions() As Variant) As Double
    Dim conditionCount As Long: conditionCount = UBound(conditions) + 1
    Dim summedColumnIndex As Long: summedColumnIndex = conditionCount + 1
    Dim currentRow As Range
    Dim result As Double: result = 0 'Changed from Long to Double
    Dim i As Long

    If rng.Columns.Count <> conditionCount + 1 Then
        Err.Raise 17, , "Invalid range passed"
    End If        

    Dim conditionsMet As Boolean

    'USING AN ARRAY INSTEAD OF A RANGE
    Dim arr As Variant
    arr = rng.Value 'Copy the range to an array
    Dim r As Long

    For r = LBound(arr, 1) To UBound(arr, 1)  'OLD: For Each currentRow In rng.Rows
        conditionsMet = True
        For i = LBound(conditions) To UBound(conditions)
            ' cells collection is indexed from 1, the array from 0
            ' OLD: conditionsMet = conditionsMet And (currentRow.Cells(1, i + 1).Value = conditions(i))
            conditionsMet = conditionsMet And (arr(r, i + 1) = conditions(i))
        Next i

        If conditionsMet Then
            'OLD: result = result + currentRow.Cells(1, summedColumnIndex).Value
            result = result + arr(r, summedColumnIndex)
        End If
    Next r

    sumIfMultipleConditionsMet2 = result
End Function
Run Code Online (Sandbox Code Playgroud)

使用方式与Jakub在回复中显示的方式相同:

debug.Print sumIfMultipleConditionsMet2(Range("A1:D50000"), 0, 1, 1)
Run Code Online (Sandbox Code Playgroud)

希望你喜欢!

此致,Andres


PS:如果你想更进一步,这里有更多关于excel的速度提示.希望你喜欢!