简体   繁体   中英

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. At this point I can't figure out how to turn this array, containing 5 values, into a "=sum( )" function. 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 . I would recommend using Dim numbers(1 to 3) As Double rather than relying on the Base option.

Edit 2: You either have forgotten Dim I in your example or don't use Option Explicit which is highly reccomended!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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