PDA

View Full Version : Different ways to call a sub or a function



wpanssi
11-10-2008, 12:44 AM
I'm confused about the different ways of calling functions or subs.

Sub addOne(ByRef num As Long)
num = num + 1
End Sub

Sub test()
Dim num As Long
num = 10

addOne num
addOne (num)


End Sub



The two different ways of calling the sub results to a different behaviour. The first one results in incrementing the num variable defined in the test sub. The second one doesn't.
Then there would be a third way: Call addOne (num)
What's the difference of these different ways? How do I know what to use?
This really bothers me a lot so any help is appreciated!

Thanks!

Bob Phillips
11-10-2008, 02:08 AM
By enclosing the variable in parentheses it gets evaluated before being passed to the called procedure, because VB/VBA treats the content in parentheses as expressions to be evaluated.

This is problemmatical with arguments that are passed by reference (ByRef) , either explicitly or implicitly (the default if the argument type is not specified). Enclosed within parentheses means that VB/VBA passes the memory address of the temporary memory location used to evaluate the expression, not the address of the argument value itself, and the procedure writes back its ByRef argument to that location. This means the original variable that was supposed to be (expected to be?) updated by the subroutine will not be. No error is generated, but the results are incorrect.

For arguments pasesd by value (ByVal), it is not a problem as the value returned would not normally be updated, but it is unnecessary.

If your method or subroutine call requires two arguments (or more), encasing them in one set of parentheses will cause a compilation error as a comma separated list is not a proper expression that can be evaluated.

Therefore, whilst a procedure call of the form



myProc (someval)


might be legitimate, and it might be the programmer's intent, it should be avoided IMO because of its special behaviour that most peple are unaware of, and if it is needed to evaluate the expresssion before pasisng it to the procedure do it explicitly.

My personal preference is to always use Call



Call myProc(someval)


as it is shows the code's intent, and is consistent and totally unambiguous. Of course, if using a Function to return a result via the function call,



myResult = myFunction(someval)


is the exception, adding Call will create a compilation error.

wpanssi
11-10-2008, 04:46 AM
This is essential information, thanks!