VBA course · Lesson 16 of 33

Functions and Subs: parameters, ByVal, ByRef and return values

Split VBA code into reusable Subs and Functions: pass parameters, understand ByRef vs ByVal, use Optional arguments and return values.

Intermediate 16 min read

So far most of your macros have been one long Sub that does everything from top to bottom. That works for ten lines, but a real workbook soon has macros of two hundred lines where the same steps (find the last row, format a header, calculate VAT) appear again and again. The cure is to split the work into small procedures that each do one job and that call each other. This lesson shows how to pass information into a procedure, how to get a result back, and the one subtle rule (ByRef versus ByVal) that causes the strangest bugs.

Sub or Function?

VBA has two main kinds of procedure:

KindStarts withReturns a value?Typical use
SubSub Name()NoDo something: format, copy, save, show a message
FunctionFunction Name() As TypeYesCalculate something and hand the answer back

Only a Sub without parameters appears in the Macros dialog (Alt+F8, Mac: Tools > Macro > Macros) and can be assigned to a button. Functions and Subs that need parameters are called from other code. A Function placed in a standard module can also be used directly in a worksheet cell; that is the subject of User-defined functions (UDFs): your own worksheet functions.

Parameters: passing information in

A parameter is a variable declared in the brackets of the procedure. The caller supplies the value, called the argument.

VBA
Option Explicit

Sub FormatHeader(ws As Worksheet, lastCol As Long)
    With ws.Range(ws.Cells(1, 1), ws.Cells(1, lastCol))
        .Font.Bold = True
        .Interior.Color = RGB(221, 235, 247)
        .HorizontalAlignment = xlCenter
    End With
End Sub

Sub PrepareReports()
    FormatHeader ThisWorkbook.Worksheets("Sales"), 5
    FormatHeader ThisWorkbook.Worksheets("Staff"), 7
End Sub
A Sub with two parameters and a macro that calls it

FormatHeader knows how to format a header row, but not which sheet or how wide. PrepareReports tells it each time. Write the formatting once, use it everywhere, and if the company colours change you update one place.

Notice the call syntax: the procedure name, a space, then the arguments separated by commas, without brackets. If you prefer brackets, use the Call keyword: Call FormatHeader(ThisWorkbook.Worksheets("Sales"), 5). Both are correct; mixing them up is a classic error (see below).

Functions: getting a result back

A function returns its answer by assigning a value to its own name before it ends.

VBA
Option Explicit

Function GrossAmount(net As Double, vatRate As Double) As Double
    GrossAmount = Round(net * (1 + vatRate), 2)
End Function

Sub InvoiceDemo()
    Dim total As Double
    total = GrossAmount(1250, 0.24)
    MsgBox "Invoice total: " & Format(total, "#,##0.00")   ' 1,550.00
End Sub
A function that returns the gross amount of an invoice

When you use the result of a function, the arguments must be in brackets: total = GrossAmount(1250, 0.24). The As Double after the closing bracket is the return type. If you forget to assign to GrossAmount on some path through the function, it silently returns the default for the type (0 for numbers, "" for strings), which is a common source of wrong results.

You can leave a function early with Exit Function, just as you leave a Sub with Exit Sub. Set the return value first.

VBA
Option Explicit

Function DiscountRate(orderTotal As Double) As Double
    If orderTotal >= 5000 Then
        DiscountRate = 0.1
        Exit Function
    End If
    If orderTotal >= 1000 Then
        DiscountRate = 0.05
        Exit Function
    End If
    DiscountRate = 0
End Function
Returning early from a function

ByRef and ByVal

Here is the rule that surprises programmers coming from other languages. By default VBA passes arguments ByRef (by reference). The parameter is not a copy; it is another name for the caller's variable. If the procedure changes the parameter, the caller's variable changes too.

VBA
Option Explicit

Sub AddBonusByRef(salary As Double)          ' ByRef is the default
    salary = salary + 500
End Sub

Sub AddBonusByVal(ByVal salary As Double)
    salary = salary + 500
End Sub

Sub TestPassing()
    Dim pay As Double

    pay = 2000
    AddBonusByVal pay
    Debug.Print "After ByVal: "; pay      ' 2000, the copy changed, not pay

    AddBonusByRef pay
    Debug.Print "After ByRef: "; pay      ' 2500, pay itself changed
End Sub
ByRef changes the caller's variable, ByVal does not

With ByVal the procedure receives a copy, so whatever it does stays inside. With ByRef it works on the original.

When should you use which?

  • Use ByVal for normal input values (numbers, text, dates) that the procedure should only read. It protects the caller from accidental changes and documents your intention. Many experienced developers write ByVal on almost every parameter.
  • Use ByRef deliberately when a procedure needs to hand back more than one result. For example, a Sub that splits a full name could fill two ByRef parameters, firstName and lastName. Write ByRef explicitly in that case so readers notice.
  • Objects (worksheets, ranges, workbooks) are references anyway. Passing a Range ByVal gives a copy of the reference, but both still point to the same cells, so rng.Value = 0 inside the procedure changes the sheet either way.
VBA
Option Explicit

Sub SplitName(ByVal fullName As String, ByRef firstName As String, ByRef lastName As String)
    Dim pos As Long
    fullName = Trim(fullName)
    pos = InStrRev(fullName, " ")
    If pos = 0 Then
        firstName = fullName
        lastName = ""
    Else
        firstName = Left(fullName, pos - 1)
        lastName = Mid(fullName, pos + 1)
    End If
End Sub

Sub TestSplitName()
    Dim f As String, l As String
    SplitName "Maria Papadopoulou", f, l
    Debug.Print f; " / "; l       ' Maria / Papadopoulou
End Sub
Returning two results through ByRef parameters
Watch out. A ByRef argument must be a variable of exactly the declared type. If you pass a Variant or an Integer to a parameter declared ByRef x As Long, you get the compile error ByRef argument type mismatch. Either declare the caller's variable with the same type or make the parameter ByVal.

Optional parameters and default values

Add Optional before a parameter to let the caller leave it out. You can give a default value with =. Optional parameters must come after all the required ones.

VBA
Option Explicit

Function PriceWithVat(ByVal net As Double, Optional ByVal rate As Double = 0.24) As Double
    PriceWithVat = Round(net * (1 + rate), 2)
End Function

Sub TestOptional()
    Debug.Print PriceWithVat(100)          ' 124, default 24%
    Debug.Print PriceWithVat(100, 0.13)    ' 113, reduced rate
End Sub
An optional VAT rate with a default value

If you need to know whether the caller supplied the argument at all (not just what its value is), declare it as Optional x As Variant without a default and test with IsMissing(x). IsMissing only works with Variant parameters; with a typed parameter the missing value simply becomes the default.

Named arguments

When a procedure has several optional parameters you can name the ones you pass with :=, in any order:

VBA
Debug.Print PriceWithVat(rate:=0.06, net:=80)   ' 84.8

You already use this style with Excel's own methods, for example ws.Range("A1:D20").Sort Key1:=ws.Range("D1"), Order1:=xlDescending, Header:=xlYes.

ParamArray: any number of arguments

Occasionally a procedure should accept a variable number of values, like SUM does. The last parameter can be a ParamArray, which arrives as a 0-based Variant array.

VBA
Option Explicit

Function AddAll(ParamArray amounts() As Variant) As Double
    Dim i As Long
    For i = LBound(amounts) To UBound(amounts)
        AddAll = AddAll + amounts(i)
    Next i
End Function

Sub TestParamArray()
    Debug.Print AddAll(120, 80.5, 300)     ' 500.5
End Sub
A function that adds any number of amounts

Public and Private

Procedures are Public by default: any module in the project can call them, and public Subs without parameters show up in the Macros list. Write Private Sub or Private Function to hide a helper. A private procedure can only be called from the same module, it does not appear in the Macros dialog, and a private function cannot be used in a worksheet cell. It is good practice to make helpers private and keep only the "entry point" macros public. VBA best practices: clean code, sharing and security has more on organising modules.

Putting it together

Here is a small but complete example that uses everything above. It reads the Staff sheet (name in A, monthly salary in B) and writes the gross annual pay with a 14-salary year in column C, and the full name split into first and last name in D and E.

ABCDE
1NameMonthlyAnnualFirstLast
2Maria Papadopoulou1800
3Jonas Weber2450
4Lucía García Pérez2100

Before: the Staff sheet

VBA
Option Explicit

Public Sub UpdateStaffSheet()
    Dim ws As Worksheet
    Dim r As Long
    Dim f As String, l As String

    Set ws = ThisWorkbook.Worksheets("Staff")
    For r = 2 To LastDataRow(ws)
        ws.Cells(r, "C").Value = AnnualPay(ws.Cells(r, "B").Value, 14)
        SplitName ws.Cells(r, "A").Value, f, l
        ws.Cells(r, "D").Value = f
        ws.Cells(r, "E").Value = l
    Next r
End Sub

Private Function LastDataRow(ByVal ws As Worksheet) As Long
    LastDataRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
End Function

Private Function AnnualPay(ByVal monthly As Double, Optional ByVal payments As Long = 12) As Double
    AnnualPay = monthly * payments
End Function

Private Sub SplitName(ByVal fullName As String, ByRef firstName As String, ByRef lastName As String)
    Dim pos As Long
    fullName = Trim(fullName)
    pos = InStrRev(fullName, " ")
    If pos = 0 Then
        firstName = fullName
        lastName = ""
    Else
        firstName = Left(fullName, pos - 1)
        lastName = Mid(fullName, pos + 1)
    End If
End Sub
One entry-point macro and three small helpers
ABCDE
1NameMonthlyAnnualFirstLast
2Maria Papadopoulou180025200MariaPapadopoulou
3Jonas Weber245034300JonasWeber
4Lucía García Pérez210029400Lucía GarcíaPérez

After running UpdateStaffSheet

The last row shows the limit of the simple rule "last word is the last name": Spanish names with two surnames need a different rule. Because the logic lives in one helper, you only have to improve SplitName to fix it everywhere. That is the payoff of splitting code into procedures.

Only UpdateStaffSheet appears in the Macros list; the helpers are private. The cell values are passed to the ByVal parameters directly, which works because VBA converts each value to the parameter type.

Common mistakes

  • Brackets on a Sub call without Call. FormatHeader(ws, 5) gives a syntax error ("Expected: =") because VBA reads the brackets as part of an expression. Use FormatHeader ws, 5 or Call FormatHeader(ws, 5). With a single argument, DoSomething (x) compiles but quietly passes x ByVal, which hides ByRef changes.
  • Forgetting to assign the function's name. The function returns 0 or "" and nothing complains.
  • Unintended ByRef changes. A helper modifies its parameter for its own convenience and the caller's variable changes. Default to ByVal.
  • Optional parameters before required ones. Not allowed; put them last.
  • Giving a procedure the same name as a module. VBA then cannot tell them apart. Name modules like modReports and procedures like BuildReport.

Check yourself

1. What is the default way VBA passes arguments when you write neither ByVal nor ByRef?

2. How does a Function return its result?

3. Which call of Sub Report(ws As Worksheet, days As Long) is correct?

4. IsMissing only works reliably with which kind of optional parameter?

5. Why make a helper procedure Private?