A copy of the pointer => This is for me irrelevant in terms of time.For objects, ByRef passes the pointer itself, while ByVal passes a copy of the pointer (not, to be clear, another instance of the object).
However, I use the interface to show that the object reference will not be changed.
For me, this is worth more than the time that may be needed to create a copy of the reference.
Tried it out briefly:
Code:
Private Function ProcByVal(ByVal AppRef As Application)
ProcByVal = AppRef.Name
End Function
' VS.
Private Function ProcByRef(ByRef AppRef As Application)
ProcByRef = AppRef.Name
End Function
The incorrect use of ByRef
Code:
Private Function WrongProcByRef(ByRef AppRef As Application)
ProcByRef = AppRef.Name
Set AppRef = Nothing ' <---- But that never happens, does it? ;-)
End Function
For array parameters, VBA forces the use of ByRef.
ByRef vs ByVal (for value types)
I also use ByRef if I want to return something. This clearly defines for me in the interface what can happen with the parameters.
Typical example: Return Value with ByRef parameter in Try* functions
Code:
Private Function TryConvertDate(ByVal ValueToConvert As Variant, ByRef ConvertedDate As Date) As Boolean
...
End Function
' use:
dim ValueToConvert as Variant
dim DateValue as Date
...
if Not TryConvertToDate(ValueToConvert, DateValue) then
Err.Raise .... or set something and/or exit procedure or ...
end if
However, ByRef can also be useful to prevent implicit conversion.
Code:
Private Sub Test()
Dim X As Variant
X = "2.5" ' test with 2.5 or 2,5 ... If the dot is the decimal separator in the regional setting, please use "2,5"
Debug.Print X, DoubleParamRequiredProc(X)
End Sub
Private Function DoubleParamRequiredProc(ByVal DoubleParam As Double) As Double
DoubleParamRequiredProc = DoubleParam / 10
End Function
Code:
Private Sub Test()
Dim X As Double 'use: As Variant => compiler error
X = "2.5" ' test with 2.5 or 2,5 ... If the dot is the decimal separator in the regional setting, please use ,
Debug.Print X, DoubleParamRequiredProc(X)
End Sub
Private Function DoubleParamRequiredProc(ByRef DoubleParam As Double) As Double
DoubleParamRequiredProc = DoubleParam / 10
End Function
To summarize, I use ByRef when it is useful for the code, otherwise I use ByVal.
But this is just my personal approach, if you only use ByRef and always make sure that parameter values are never changed, then of course this is correct.
Perhaps this is also due to the fact that I also program a lot with C#. There,
ref or out is rarely used.BTW: [Classes and VBA]
Honestly, I never understood why classes are often considered complicated. For me, they're just a regular part of working with VBA.But, YMMV. I'll be the first to admit this view largely can be attributed to a nitpicky style, or too much time spent programming classes.
Last edited: