by Maeenul
26. November 2011 15:49
In VBA, there is no built in function that works like Power (number, power) function in Excel. But we can easily create a power function in VBA ourselves that will work like the Power function in Excel. In fact, in VBA we can use ^ operator to do the exponent/power calculation. To calculate Power (3, 3) which should return 27, we can easily use the below VBA code: Dim PowerValue as Long powerValue = 3 ^ 3 Below you can find a complete VBA code for Power function. Public Function Power(ByVal number As Double, ByVal exponent As Double) As Double
' number is the base value
' exponent is the power to the base number
Power = number ^ exponent End Function
Example: Power(0, 0) returns 1 Power(1, 0) returns 1 Power(1, 1) returns 1 Power(3, 0) returns 1 Power(3, 3) returns 27 Power(3.3, 4) returns 118.5921 Power(3.3, 4.4 returns 191.188310515809 Power(-3.8, -4) returns 4.79585024669854E-03 Power(3.3, -4.4) returns 5.23044529920312E-03 Use Excel worksheet Power function in VBA: We have used ^ operator to calculate the Power. There is another option that we can use the Power function that is already available in Excel worksheet. We can, in fact, call any excel worksheet function from VBA code in the following way. Application.WorksheetFunction.power(x, y) So our another version of VBA Power function would look like below. Public Function Power(ByVal number As Double, ByVal exponent As Double) As Double
' number is the base value
' exponent is the power to the base number
Power = Application.WorksheetFunction.power(number, exponent) End Function
a384bf6a-3fd2-484a-afdc-ac2cea287143|1|5.0
Tags:
Category: VBA