asilver50
asilver50

Reputation: 38

Using := in a vba function call

I am wondering what the reason is for using := in a function call. I know := is used when a function calls for multiple criteria. You can use the := to denote which criteria you are referring to. However, I do not understand the following snippets. This is from http://www.cpearson.com/excel/PassingAndReturningArrays.htm.

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

He is using Arr:=StaticArray. What is the Arr:= used for? My second example is as follows:

If IsArrayAllocated(Arr:=Arr) = True Then
        If NumberOfArrayDimensions(Arr:=Arr) = 1 Then

He is passing Arr to IsArrayAllocated but I do not understand why he can't just use IsArrayAllocated(Arr) instead. Thanks for any insight on this.

Upvotes: 0

Views: 119

Answers (1)

Andre Taron
Andre Taron

Reputation: 121

FOR READABILITY

"NumberOfArrayDimensions" is a function itself, which has an "Arr:= argument itself.

If NumberOfArrayDimensions(Arr:=Arr) = 1 then

You would use ":=" in the absence of multiple arguments purely for readability.

Examples: A function call written as

HireEmployees NumberOfSalesmanToHire:=4

Is much more readable than a cryptic

HireEmployees nbSlms:=4

Or the even more cryptic

HireEmployees 4

You'll write your code 1time, but you'll have to read it many, many more times. To that end, it's great to always understand what you are reading as fast as possible.

On a side note, I prefer not to use abbreviations like "Arr". Is it short for an Array or was it written on Pirate Day? I prefer to make sure everything is explicit since it doesn't lower the performance of the computation anyway

EDIT FOR MAINTENANCE

You might also wish to use the ":=" in function calls for maintenance. Let's say you have this :

Sub HireEmployees(Optional NumberOfSalesmanToHire as Integer=1, Optional NumberOfJanitors as Integer = 0)
   (do something with Salesman)
   (do something with Janitors)
End Sub

Later, you change this code so it doesn't have Salesman anymore:

Sub HireEmployees(Optional NumberOfJanitors as Integer = 0)
   (do something with Janitors)
End Sub

Now, if your arguments were not explicit, you'd start having funky behaviors through-out your code:

HireEmployees 4

What did the previous dev mean? Was it the old Salesman call or was this changed to now only work with janitors...? Who knows.

You don't have that problem if your calls were explicit:

HireEmployees NumberOfSalesman:=4

As the compiler will now warn you that this doesn't work anymore, therefor preventing your code from interpreting old Salesman as Janitors.

Upvotes: 2

Related Questions