Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA array syntax

Tags:

vba

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

like image 487
Kenny Nguyen Avatar asked Sep 16 '25 00:09

Kenny Nguyen


1 Answers

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.

like image 168
Dick Kusleika Avatar answered Sep 17 '25 15:09

Dick Kusleika