Passing Arrays as Arguments

Passing an array to a function or subprocedure is not as difficult in VBA as one might think. You must follow a couple of rules, however, to ensure a valid argument pass.

To pass all elements in an array to a procedure, simply pass the array name with no parentheses. Next, you must define the parameter name with an empty set of parentheses, as the next two procedures demonstrate.

Private Sub cmdPassEntireArray_Click() Dim myArray(5) As Integer HowMany myArray End Sub

Private Sub HowMany(x() As Integer)

MsgBox "There are " & UBound(x) & " elements in this array." End Sub

To pass a single element in an array, it is not necessary to define the parameter name as an array. Rather, simply pass one array element as a normal variable argument:

Private Sub cmdPassArrayElement_Click() Dim myArray(5) As Integer CheckItOut myArray(3) End Sub

Private Sub CheckItOut(x As Integer)

MsgBox "The parameter's value is " & x & "." End Sub

Passing arrays and elements of arrays as arguments is that easy!

0 0

Post a comment