ByVal or ByRef


ByRef (Default)

Passing variables by reference is the default and this means that you pass a pointer to the variable and therefore the variable's value can be changed inside the procedure or function.
Passing an argument by reference is the default.

If you pass a variable defined as a user defined data type to a procedure, it must be passed by reference.
Attempting to pass it by value will cause an error.


ByVal

Passing arguments by value passes a copy of the variable and changing the value will only affect the local copy.
This should be used when you do not want the procedure to modify the actual variable but just to use the value.


Passing in Value Data Types

Value data types are also referred to as simple data types.


Passing in Reference Data Types

Reference data types are also referred to as object types.
In VBA all objects are passed by reference although there is a difference.
ByRef - the address of the object is passed.
ByVal - a copy of the address to the object is passed.


Saving Memory

Passing in variables using ByRef compared to ByVal can save memory, but only for Value data types (Integers, Doubles, Booleans, User-Defined Types).
ByRef does not save memory for Reference data types (Object, Class Collection) because ByVal does not copy the object.
It is best practice to only use ByRef when a variable is being changed inside the subroutine or function.
If you have very large User Defined Types, Strings above 10,000 characters or Loops executing 100,000+ times then it can save some memory.
If you have used ByRef for a performance / memory reason you should always add a comment indicating that this is the reason.


© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext