Reputation: 9018
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
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