Macro: sub with array

  • Thread starter Thread starter Allamarein
  • Start date Start date
A

Allamarein

Le't see this dummy subroutine calculating bi-dimensional scalar
product.
I wanna learn to use subroutine and function using arrays like input
+++++++++++++++++++++++
Sub main
dim a(1 to 2), b(1 to 2) as Double
product = dot(a,b)
end main

Function dot(x_vec(),y_vec() as double)
dot=x_vec(1)*y_vec(1)+x_vec(2)*y_vec(2)
end function
+++++++++++++++++++++++
This sub doesn't run: at third line 'a' is not accepted in dot
function.
How should I modify my code?
 
First, it's a better idea to copy|paste your code directly from the VBE into
your message. It avoids lots of typos.

But this worked for me:

Option Explicit
Sub main()
Dim Product As Double

Dim a(1 To 2) As Double
Dim b(1 To 2) As Double

a(1) = 1.1
a(2) = 1.2
b(1) = 2.1
b(2) = 2.2

Product = dot(a, b)
MsgBox Product & vbLf & Application.SumProduct(a, b)

End Sub

Function dot(x_vec() As Double, y_vec() As Double)
dot = x_vec(1) * y_vec(1) + x_vec(2) * y_vec(2)
End Function

=====
ps.

When you do something like:
dim a(1 to 2), b(1 to 2) as Double

This declares the elements of b() as doubles. But the elements of a are variants.

You could use this syntax if you wanted:

dim a(1 to 2) as double, b(1 to 2) as Double
 
Back
Top