简体   繁体   English

将SumIf函数与范围对象或数组一起使用

[英]Use of SumIf function with range object or arrays

I'm am trying to optimize a sub that uses Excel´s sumif function since it takes several time to finish. 我正在尝试优化使用Excel的sumif函数的子项,因为它需要花费一些时间才能完成。

The specific line (contained in to a for loop) is this one: 特定行(包含在for循环中)是这一行:

Cupones = Application.WorksheetFunction.SumIf(Range("Test_FecFinCup"), Arr_FecFlujos(i), Range("Test_MtoCup"))

Where the ranges are named ranges in the workbook, and Arr_FecFlujos() is an array of dates 范围在工作簿中称为范围,而Arr_FecFlujos()是日期数组

That, code works fine, except for it takes to much time to finish. 那样,代码可以正常工作,除了需要花费大量时间才能完成。

I am trying this two approaches Arrays: 我正在尝试这两种方法数组:

Declare my arrays 声明我的数组

With Test
  Fluj = .Range(Range("Test_Emision").Cells(2, 1), Range("Test_Emision").Cells(2, 1).End(xlDown)).Rows.Count
  Arr_FecFinCup = .Range("Test_FecFinCup")
  Arr_MtoCup = .Range("Test_MtoCup")
End With

Cupones = Application.WorksheetFunction.SumIf(Arr_FecFinCup, Arr_FecFlujos(i), Arr_MtoCup)

Error tells me I need to work with Range Objects, so I changed to: 错误告诉我我需要使用范围对象,因此我更改为:

With Test
 Set Rango1 = .Range("Test_FecIniCup")
 Set Rango2 = .Range("Test_MtoCup")
End With

Cupones = Application.WorksheetFunction.SumIf(Rango1, Arr_FecFlujos(i), Rango2)

That one, doesn't shows any error messages, but the sum is incorrect. 那一个,不显示任何错误消息,但总和不正确。

Can anybody tell me what's working wrong with these methods and perhaps point me in the correct direction? 谁能告诉我这些方法有什么问题,也许可以指出正确的方向吗?

It seems that you try to sum a range of numbers using a range of criteria: 您似乎尝试使用一系列条件求和一系列数字:

WorksheetFunction.SumIf(Arr_FecFinCup, Arr_FecFlujos(i), Arr_MtoCup)

As i know, if the criteria parameter is given a range, Excel don't iterate over that range but instead look for the one value in the criteria_range that coincides with the row of the cell that it is calculating. 据我所知,如果criterias参数给出了一个范围,Excel不会在该范围内进行迭代,而是在criterias_range中寻找与其正在计算的单元格行重合的一个值。

For example 例如

Range("D3") = WorksheetFunction.SumIf(Range("A1:A10"),Range("B1:B10"))

Excel will actually calculate as follow Excel实际上将如下计算

Range("D3") = WorksheetFunction.SumIf(Range("A1:A10"),Range("B3"))

If there is no coincident, then the return is 0 如果没有巧合,则返回值为0

For example 例如

Range("D7") = WorksheetFunction.SumIf(Range("A1:A10"),Range("B1:B5"))

Then D7 is always 0 because looking for [B7] in [B1:B5] is out of range. 那么D7始终为0,因为在[B1:B5]中寻找[B7]不在范围内。

Therefore, to do a sum with multiple criterias, the correct way is using SUMIFS as suggested by @mrtiq. 因此,要对多个条件求和,正确的方法是使用@mrtiq建议的SUMIFS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM