简体   繁体   English

使用VBA定义的数组将公式应用于单元格

[英]Apply Formula to Cell Using a VBA defined Array

There are definitely easier ways to achieve what this code is trying to do, but I created a simplified code to show what I am trying to achieve. 肯定有更简单的方法可以实现此代码要执行的操作,但是我创建了一个简化的代码来显示我要实现的功能。 Basically I want to perform calculations on lots of data and I don't want to have to have to add that to the worksheets. 基本上,我想对大量数据执行计算,而不必将其添加到工作表中。

So basically I need to run formulas like sum, averageifs, etc. in a worksheet through using an Array that I defined in my Macro. 因此,基本上,我需要使用在宏中定义的数组在工作表中运行诸如sum,averageifs等公式。 At this point I can't figure out how to turn this array, containing 5 values, into a "=sum( )" function. 在这一点上,我不知道如何将包含5个值的该数组转换为“ = sum()”函数。 Thanks in advance for your help! 在此先感谢您的帮助!

Sub ArraySum()

Dim numbers(5) As Double
Dim E As Double

For I = 1 To 5
    E = Cells(I, 1)
    numbers(I) = Cos(E)
Next I

Range("b1").Formula = "=sum(" & numbers & ")"

End Sub

It's not clear why you'd want to do it this way, but: 目前尚不清楚您为什么要这样做,但是:

Sub ArraySum()

    Dim numbers(1 To 5) '<<<
    Dim E As Double

    For I = 1 To 5
        E = Cells(I, 1)
        numbers(I) = Cos(E)
    Next I

    Range("B1").Formula = "=SUM(" & Join(numbers, ",") & ")"

End Sub

but then you might as well just do: 但是您最好也这样做:

Range("B1").FormulaArray = "=SUM(COS(A1:A5))"

Another way if you don't need the formula to actually be in that cell: 如果您不需要公式实际位于该单元格中的另一种方式:

Range("b1").Value = Application.WorksheetFunction.Sum(numbers)

Edit: If you haven't set Option Base 1 then Dim numbers(3) As Double will create a 4-element array numbers(0),...,numbers(3) since the default is Base 0 . 编辑:如果尚未设置Option Base 1Dim numbers(3) As Double将创建一个4元素的数组numbers(0),...,numbers(3),因为默认值为Base 0 I would recommend using Dim numbers(1 to 3) As Double rather than relying on the Base option. 我建议将Dim numbers(1 to 3) As Double而不是依赖于Base选项。

Edit 2: You either have forgotten Dim I in your example or don't use Option Explicit which is highly reccomended! 编辑2:您要么在示例中忘记了Dim I ,要么不使用高度推荐的Option Explicit

Does it have to be an equation in the worksheet? 它必须是工作表中的方程式吗? You could just get the total and put it there: 您可以将总数放到那里:

Sub ArraySum()

    Dim numbers(1 To 5) '<<<
    Dim E As Double

    For I = 1 To 5
        E = Cells(I, 1)
        numbers(I) = Cos(E)
    Next I

    Range("B1").Value = Application.WorksheetFunction.Sum(numbers)
End Sub

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

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