Optional ByRef arguments -- changing value of

J

jfp

I did a brief test and this seemed harmless but i would like to be sure.

What i want is something like this:
A function with some "normal" arguments and then some optional arguments
that allow for the return of more detailed results -- if desired. As an
example, consider a function to delete all records in some table (name
of table is a required arg) that optionally fills in a status string
("22 records were deleted"). In this case, the 2nd arg would be
something like:
ByRef Optional strStatus As String

Now, if the user calls the function and supplies a 2nd argument, then
the status will be written into the string allocated in the calling
function -- OK. What happens if the user doesn't want the status and
omits this argument? The function is still going to do something like
strStatus = " blah blah "
Where does this go? I want to be sure that it does not overwrite
anything.

I realize that i could use a Variant for this argument and then use
IsMissing() to determine whether or not to write to it -- but the above
seems simpler, as long as it works.
 
J

John Nurick

Remember that VB(A)'s default behaviour is to pass by arguments
reference. So there would seem to be no difference between
Optional ByRef
and
Optional

Also, the fact that you can declare an optional argument with a default
value means that memory is being allocated for it even if the argument
is not passed.
 
J

John Nurick

Umm. How about:
Remember that VB(A)'s default behaviour is to pass arguments by
reference. So there would seem to be no difference between
Optional ByRef
and
Optional
 
D

david epsom dot com dot au

ByRef Optional strStatus As String

strStatus can't be 'Missing' unless it is a variant.

If strStatus is a string, is ALWAYS a string.

If you don't provide a reference for the string variable, VBA must and does
create a local variable.

I am aware that there are places in some of the help files that show using
'IsMissing' with Integer and String variables, but those examples are either
wrong or refer to some other version of VB.

You can use the 'Optional' key word, but with non-variant parameters
'Optional' refers to your calling statements, not to what the called
function receives. To VBA, non-variant optional parameters are not optional
at all: VBA has to create a local parameter if you don't supply one.

Note: MS C++ and C# handle optional parameters and default values
differently than VB does.

(david)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top