vba 如何在VBA中对两个数组中的值进行求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13914907/
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 18:51:31  来源:igfitidea点击:

How to do a sumproduct of values in two arrays in VBA

excelvbaworksheet-function

提问by Marc L

I am trying to do the sumproduct of two arrays in VBA as I am trying to avoid referencing the worksheet until write time due to its size and complexity.

我试图在 VBA 中对两个数组进行求和,因为我试图避免在写入时间之前引用工作表,因为它的大小和复杂性。

I knwo I can use the applicationfunction to run sumproduct with defining two ranges, but that still references the worksheet, is there anyway to do it with just using arrays purely in code?

我知道我可以使用 applicationfunction 来运行 sumproduct 并定义两个范围,但这仍然引用工作表,无论如何只在代码中使用数组来做到这一点?

回答by Charles Williams

Sure, you just call SUMPRODUCT and pass it the arrays: (but note that its a bit inefficient)

当然,您只需调用 SUMPRODUCT 并将数组传递给它:(但请注意,它的效率有点低)

Sub testing2()
Dim varr1(1 To 10)
Dim varr2(1 To 10)
Dim vres As Variant
Dim j As Long
For j = 1 To 10
varr1(j) = j
varr2(j) = j * 10
Next j
vres = Application.WorksheetFunction.SumProduct(varr1, varr2)
End Sub