A Simple VBA Tutorial: to generate a vector class module.

Here’s how you might implement some vector calculations without encapsulating it in a class.

Method 1

‘ the follow procedure adds inV2 to inV1

Public Sub AddVecs(inV1X As Double, _

inV1Y As Double, _

inV1Z As Double, _

inV2X As Double, _

inV2Y As Double, _

inV2Z As Double)

inV1X = inV1X + inV2X

inV1Y = inV1Y + inV2Y

inV1Z = inV1Z + inV2Z

End Sub

Public Sub Main()

‘Declare each vector value individually

Dim v1X As Double

Dim v1Y As Double

Dim v1Z As Double

Dim v2X As Double

Dim v2Y As Double

Dim v2Z As Double

v1X = 1

v1Y = 1

v1Z = 1

v2X = 1

v2Y = 2

v2Z = 3

AddVecs v1X, v1Y, v1Z, v2X, v2Y, v2Z

‘ now has values v1X =2, v1Y, =3,Z= v1Z

End Sub

Method 2 ,below, binds the x,y and z of the vector into a user defined type within a general module. This module also contains some functions to set the value of the vector and perform addition.

Option Explicit

‘Example of how you might implement some vector maths

‘without using a class module

‘This bit declares a user defined type to hold the x,y and Z vector values

Type Vector

X As Double

y As Double

z As Double

End Type

‘The following procedure initialises the inVec to dX,dY,dZ

Public Sub InitVec(inVec As Vector, _

dX As Double, _

dY As Double, _

dZ As Double)

inVec.X = dX

inVec.y = dY

inVec.z = dZ

End Sub

‘the following procedure adds the AddThisVec to Vec

Public Sub AddVec(Vec As Vector, _

Vec.X = Vec.X + AddThisVec.X

Vec.y = Vec.y + AddThisVec.y

Vec.z = Vec.z + AddThisVec.z

End Sub

Public Sub Main()

Dim VecA As Vector

Dim VecB As Vector

InitVec VecA, 1, 1, 1

InitVec VecB, 1, 2, 3