Kenny Nguyen
Kenny Nguyen

Reputation: 232

VBA array syntax

Looking over vba arrays and stumbled upon something and need someone to clear it up.

Sub AAATest()
Dim StaticArray(1 To 3) As Long
Dim N As Long
StaticArray(1) = 1
StaticArray(2) = 2
StaticArray(3) = 3
PopulatePassedArray Arr:=StaticArray
For N = LBound(StaticArray) To UBound(StaticArray)
    Debug.Print StaticArray(N)
Next N
End Sub

AND

Sub PopulatePassedArray(ByRef Arr() As Long)
''''''''''''''''''''''''''''''''''''
' PopulatePassedArray
' This puts some values in Arr.
''''''''''''''''''''''''''''''''''''
Dim N As Long
For N = LBound(Arr) To UBound(Arr)
    Arr(N) = N * 10
Next N
End Sub

What's happening at

PopulatePassedArray Arr:=StaticArray

in AAATest sub

Upvotes: 4

Views: 842

Answers (1)

Dick Kusleika
Dick Kusleika

Reputation: 33145

There are two ways you can pass arguments to another procedure: using named arguments or in order. When you pass them in order, you must past them in the same order as the procedure definition.

Function DoTheThing(arg1 As Double, arg2 As String, arg3 As Boolean) As Double

When you call this function (in order), you call it like

x = DoTheThing(.01, "SomeString", TRUE)

When you call the function using named arguments, you use :=, the name of the argument, and the value of the argument. The := is not a special assignment operator - well I guess it kind of is. The upshot is that when you use named arguments, you can supply them in any order.

x = DoTheThing(arg2:="SomeString", arg3:=TRUE, arg1:=.01)

Some people also think that named arguments make your code more readable. I'm not one of those people. It clutters it up and if you're passing more than two or three arguments, you're doing it wrong anyway.

Upvotes: 2

Related Questions