user3022875
user3022875

Reputation: 9018

How do you square a vector in VBA without looping

I have a vector. How do I square it without looping in vba?

s(0) = 4
s(1) = 5

sq = ??

i am looking for:

sq(0)= 16
sq(1) = 25

any thoughts?

Upvotes: 0

Views: 822

Answers (2)

lori_m
lori_m

Reputation: 5567

In Excel VBA, you can use

sq = Application.Power(s, 2)  

Upvotes: 0

Blackhawk
Blackhawk

Reputation: 6140

Instead of looping each time, you can encapsulate this operation in a function and simply call that:

'Modifies array in place - saves from having to determine array type
Public Sub ArrayPower(arr As Variant, power As Long)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
       arr(i) = arr(i) ^ power
    Next
End Function

In your code you can call it like so:

Public Sub Main()
    Dim arr(2) As Long
    arr(0) = 1
    arr(1) = 2
    arr(2) = 3

    'Before: {1,2,3}        

    ArrayPower arr, 2

    'After: {1,4,9}
End Sub

Upvotes: 1

Related Questions