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.
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:
| Kind | Starts with | Returns a value? | Typical use |
|---|---|---|---|
| Sub | Sub Name() | No | Do something: format, copy, save, show a message |
| Function | Function Name() As Type | Yes | Calculate 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.
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 SubFormatHeader 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.
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 SubWhen 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.
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 FunctionByRef 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.
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 SubWith 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
ByValon 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,
firstNameandlastName. WriteByRefexplicitly in that case so readers notice. - Objects (worksheets, ranges, workbooks) are references anyway. Passing a
RangeByVal gives a copy of the reference, but both still point to the same cells, sorng.Value = 0inside the procedure changes the sheet either way.
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 SubVariant 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.
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 SubIf 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:
Debug.Print PriceWithVat(rate:=0.06, net:=80) ' 84.8You 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.
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 SubPublic 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.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Name | Monthly | Annual | First | Last |
| 2 | Maria Papadopoulou | 1800 | |||
| 3 | Jonas Weber | 2450 | |||
| 4 | Lucía García Pérez | 2100 |
Before: the Staff sheet
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| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Name | Monthly | Annual | First | Last |
| 2 | Maria Papadopoulou | 1800 | 25200 | Maria | Papadopoulou |
| 3 | Jonas Weber | 2450 | 34300 | Jonas | Weber |
| 4 | Lucía García Pérez | 2100 | 29400 | Lucía García | Pé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. UseFormatHeader ws, 5orCall FormatHeader(ws, 5). With a single argument,DoSomething (x)compiles but quietly passesxByVal, 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
modReportsand procedures likeBuildReport.
Check yourself
1. What is the default way VBA passes arguments when you write neither ByVal nor ByRef?
VBA passes by reference unless you write ByVal, so changes to the parameter reach the caller's variable.
2. How does a Function return its result?
In VBA you write FunctionName = value somewhere before the function ends.
3. Which call of Sub Report(ws As Worksheet, days As Long) is correct?
Without Call, a Sub's arguments are not in brackets. With Call, they must be: Call Report(ws, 30).
4. IsMissing only works reliably with which kind of optional parameter?
Typed optional parameters get their default value when omitted, so only a Variant parameter can be "missing".
5. Why make a helper procedure Private?
Private keeps helpers out of the Macros dialog and out of other modules; private functions are not available in cells.