View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Rob Bovey Rob Bovey is offline
external usenet poster
 
Posts: 811
Default Is ByVal always better if ByRef isn't necessary

Hi Jeff,

For most situations, if you don't want the calling procedure to see any
changes made to arguments passed to the called procedure then you should
declare the called procedures parameters ByVal. This prevents any bugs from
occurring as a result of inadvertently modifying a parameter variable, and
it allows you to use parameters as variables inside the called procedure
rather than having to declare separate variables to transfer them into.

There are a couple of exceptions to this, both of which have to do with
performance. Passing Strings and object references ByVal is relatively
expensive in performance terms. You aren't likely to notice a difference
unless you're doing this inside a long loop, but if you are, you may want to
change these parameter types to ByRef in order to speed things up. Just be
careful not to modify them in the called procedure.

--
Rob Bovey, MCSE, MCSD, Excel MVP
Application Professionals
http://www.appspro.com/

* Please post all replies to this newsgroup *
* I delete all unsolicited e-mail responses *


"Jeff" wrote in message
...
If a variable is not being modified in the passed to sub
or function, is there a reason to specify ByVal rather
than allowing the default ByRef.

And same question if a value is being passed.

In these cases I do not perceive any practical difference
between ByVal or ByRef, but somehow I suspect there is!

TIA for clarifaction,
Jeff