I generally use VBA but have been reading up on programming techniques in The C# Programming Yellow Book which, obviously, is more specific to C#. Anyway, it mentions a technique of passing parameters using the Out
keyword.
I already know that VBA supports byVal
and byRef
and am fairly certain there is no direct equivalent for Out
. Passing parameters using Out
is subtly different to passing parameters by Ref
.
This Answer https://stackoverflow.com/a/388781/3451115 seems to give a good explanation of the difference between Out
& Ref
.
The Ref modifier means that:
The value is already set and The method can read and modify it.
The Out modifier means that:
The Value isn't set and can't be read by the method until it is set. The method must set it before returning.
In the code base that I've inherited there are several places where values are assigned to variables using methods that accept parameters byRef
. It seems to me that while passing byRef
does the job, passing by Out
would be safer... So (and here is the question) is there a way of safely / reliably replicating Out
in VBA?
In my first iteration (original question) I imagined that the code would have a pattern like:
Sub byOutExample(byRef foo As String)
' Check before running code:
' foo must = vbNullString
If foo <> vbNullString then Err.Raise(someError)
' Do Something to assign foo
foo = someString
' Check before exiting:
' foo must <> vbNullString
If foo = vbNullString then Err.Raise(someError)
End Sub
Other considerations: is it worth doing, is there a better way, what could go wrong?
Edit: I noticed in the comments for the above definition of Ref
vs Out
that the passed parameter need not be null
, nothing
, empty
etc. it can be preassigned - the main criteria seems that it is re-assigned.
In light of @ThunderFrame's answer below and the comment that a parameter passed by Out
can be pre-assigned (and used), perhaps the following is a better approach:
Sub byOutExample(ByRef foo As String)
Dim barTemp As String
barTemp = foo
' Do Something to assign a new value to foo (via barTemp)
barTemp = someString
' Must assign new variable
foo = barTemp
End Sub
In which case would it be true to say that, as long as foo
only appears in the 2 locations shown above, the above code is an accurate way to replicate passing a parameter by Out
in VBA?