PDA

View Full Version : [SOLVED] Calculate power

Pawel
09-05-2016, 04:48 AM
Hi guys ,
I'm trying to write a macro that will calculate sum of powers(Y) of values from 1 to X
for example :
for X = 5 and Y=2 the value should be 1^2 + 2^2+3^2+4^2+5^2

any idea how to do that?

GarysStudent
09-05-2016, 06:03 AM
Perhaps the UDF:

Public Function SumPowers(X As Long, Y As Long) As Long

Dim i As Long

SumPowers = 0
For i = 1 To X
SumPowers = SumPowers + i ^ Y
Next i
End Function

SamT
09-05-2016, 06:18 AM
Just an FYI.
SumPowers = 0 is redundant in that code.

Pawel
09-05-2016, 06:24 AM
This code would be great but I need this to be a simple macro to display the result in MsgBox

SamT
09-05-2016, 06:54 AM
This code would be great but I need this to be a simple macro to display the result in MsgBox
Shirley, you can figure that out.

BTW, this sounds like a homework assignment.

Paul_Hossler
09-05-2016, 06:57 AM
This code would be great but I need this to be a simple macro to display the result in MsgBox

MsgBox SumPowers (5, 2)

SamT
09-05-2016, 07:00 AM
Heh heh.

snb
09-05-2016, 07:27 AM
Sub M_snb()
MsgBox [sumsq(1,2,3,4,5)]
' or
MsgBox [sum({1,2,3,4,5}^2)]
End Sub

SamT
09-05-2016, 09:06 AM
Slick. I like the second line.

snb
09-05-2016, 09:11 AM
I waited for you to ask for it:

Sub M_snb()
x = 8
y = 3

MsgBox Evaluate("sum(row(1:" & x & ")^" & y & ")")
End Sub

SamT
09-05-2016, 09:30 AM
Yowzer!

Pawel
09-05-2016, 10:29 AM
I know it sounded funny-simple to you guys but I'm jus a newbie trying to learn something :)