What is the difference between passing variables to subroutines and functions by value and by reference?

If you want to pass a variable to a subroutine, run computations on it, and alter its contents, then the variable must be passed by reference (this is the default method how arguments are passed to subroutines or functions). Essentially, passing a variable by reference means passing the variable itself to the subroutine, and any changes made to it in the subroutine will be permanent. By contrast, if you want to pass a variable, run computations on it, and alter the temporary instance of it within the subroutine without affecting the original variable, then you must pass the variable by value. When a variable is passed by value to a function or subroutine, only a copy of the variable is passed, not the actual variable. If any changes are applied to the variable within the called function, then those changes will only pertain to the copy of the original variable. When passing a variable by value, its value will always be preserved, no matter what is done within the called function. To illustrate, instead of making ComputeSumOfSqrs in this example a function, we could make it a subroutine and pass the variable SumValue as an argument by reference; by using this approach, SumValue will be directly altered by the subroutine without needing to return a value. Note that the ByRef keyword in the example below would be optional, since the default method of passing arguments to subroutines or function is by reference.

Sub Main ... ...

ComputeSumOfSqrs ( LBound (x), _ UBound(x), _ x, _ SumValue) ... ... End Sub ' Now, ComputeSumOfSqrs is a subroutine, with arguments passed ' explicitly by value, or by reference (note that arrays are ' always passed by reference). Sub ComputeSumOfSqrs  ByVal iFrom As Long, _ ByVal iTo As Long, _ x() As Double, _ ByRef SumOfSqrs As Double Dim i As Integer SumOfSqrs=0 For i= iFrom To iTo SumOfSqrs=SumOfSqrs+x(i)^2 Next i End Sub ... ...