VBA:函数比较一个范围的不同列上的 SUMIFS 并根据布尔值返回 Min 或 Max

VBA: Function comparing SUMIFS on different columns of a range and returning Min or Max according to a boolean

我正在尝试在一组重要的列上使用两个参数求和(列数不会改变,数据会改变),然后 return 最大值或最小值

Function min_or_max(B As Boolean, table As Range, col1 As Range, c1 As Cell, col2 As Range, c2 As Cell)
Dim column As Range

'If B = False Then
min_or_max = 0
For Each column In Range.Columns
If ActiveSheet.WorksheetFunction.SumIfs(Range.column, col1, c1, col2, c2) > min_or_max Then
min_or_max = ActiveSheet.WorksheetFunction.SumIfs(Range.column, col1, c1, col2, c2)
End If
Next column

'Elsif B = True
'min_or_max = 10000000
'For Each column In Range.Columns
'If ActiveSheet.WorksheetFunction.SumIfs(Range.Columns(i), col1, c1, col2, c2) < min_or_max Then
'min_or_max = ActiveSheet.WorksheetFunction.SumIfs(Range.Columns(i), col1, c1, col2, c2)
'End If
'Next column
End Function

甚至在执行拆分最小值或最大值之前,我都无法让 SUMIFS 工作。是因为输入错误吗? (我希望清楚!)

非常感谢能帮助我的人! drf

问题是 WorksheetFunction 不是 Worksheet 对象,而是 Application 对象

所以,你会想要使用 Application.Worksheetfunction

这一行:

If ActiveSheet.WorksheetFunction.SumIfs(Range.column, col1, c1, col2, c2) > min_or_max Then

需要看起来像这样:

If Application.WorksheetFunction.SumIfs(Range.column, col1, c1, col2, c2) > min_or_max Then

现在我使用的是一个非常基本和缓慢的解决方案:

Function max_table(table As range, col1 As range, c1 As range, col2 As range, c2 As range)
Dim i, j As Integer
Dim prov As Integer

max_table = 0
For i = 1 To table.Columns.Count
prov = 0
For j = 1 To table.Rows.Count
    If col1(j).Value = c1.Value And col2(j).Value = c2.Value Then
    prov = prov + table.Cells(j, i).Value
    End If
Next j
If max_table < prov Then
max_table = prov
End If
Next i

End Function