Excel VBA procedures with arguments: split macros into parts

A long macro becomes easy to follow once each job gets its own procedure. Arguments are the values you hand over when you call it: which row, which text, which rate. You write the procedure once and call it from anywhere.

In short: Sub Flag(r As Long, note As String) takes two values. Call it with Flag 5, "check" or Call Flag(5, "check"). ByRef (the default) passes the variable itself, ByVal passes a copy. Optional discount As Double = 0.05 makes an argument voluntary.

What you need to know: user-defined functions from level 3 and error handling.

Try it right now

The main macro is already there and calls a second procedure, which is still missing. You write its header with two arguments and one line of body. As long as the header does not match the call, the exercise reports "Compile error: Wrong number of arguments or invalid property assignment".

Task The macro CheckInvoices is finished: for every invoice over 5,000 it calls the procedure Flag and passes the row and a note. Flag itself is still missing. Write it so that it takes two arguments, r As Long and note As String, and writes the note into column D of that row. Leave CheckInvoices as it is.

ABCD
1InvoiceSupplierAmountNote
2PI-2201Shaw Paper840.00
3PI-2202Weber IT Services7,450.00
4PI-2203Brightclean1,260.00
5PI-2204Hartley Furniture12,900.00
6PI-2205Beck Beverages310.00

How arguments are declared

Sub Flag(ByVal r As Long, ByVal note As String)
    Cells(r, 4).Value = note
End Sub

Function FinalPrice(listPrice As Double, Optional discount As Double = 0.05) As Double
    FinalPrice = listPrice * (1 - discount)
End Function
PartMeaning
r As LongOne argument: name and type. Inside the procedure it is a variable holding the value that was passed.
ByValThe procedure gets a copy. If it changes the argument, the caller does not notice.
ByRefThe procedure gets the caller's variable, and changes flow back. Without a keyword, VBA uses ByRef.
Optional ... = 0.05The argument may be left out; then the default applies. Optional arguments go at the end of the list.
As Double after the parenthesesFunction only: the type of the return value. Whatever you assign to the function's name is returned.

Calling with and without Call

Flag i, "Needs approval"            ' without Call: no parentheses
Call Flag(i, "Needs approval")      ' with Call: parentheses
price = FinalPrice(4800, 0.1)       ' Function on the right of =: parentheses
price = FinalPrice(discount:=0.1, listPrice:=4800)   ' named arguments

Both ways of calling a Sub do the same thing; Call is simply the older style. What matters is the parentheses rule: without Call, a Sub's arguments have no parentheses. With named arguments (name:=value) the order no longer matters and the call explains itself.

Several results with ByRef

A Function returns exactly one value. When you need two, such as net and tax from a gross amount, a Sub writes them into ByRef arguments. The caller's variables then hold the results.

Task The macro SplitAmounts calls the procedure SplitGross for every receipt. It should return two results from the gross amount and the tax rate: net and tax. Write SplitGross with four arguments: ByVal gross As Double, ByVal rate As Double, ByRef net As Double, ByRef tax As Double. Net is gross / (1 + rate), the tax is what is left.

ABCDEFG
1ReceiptGrossNetTaxTax rate20%
2R-301120.00
3R-302240.00
4R-30360.00
5R-3041,200.00

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Optional arguments

Most customers get a 5% discount, key accounts get 10%. Rather than two functions, you write one with an optional discount that is 0.05 when left out.

Task The macro SetPrices calls the function FinalPrice, with one argument for standard customers and two for key accounts. Write the function: Function FinalPrice(listPrice As Double, Optional discount As Double = 0.05) As Double. It returns the list price minus the discount. Without a second argument the discount is 5%; key accounts get 10%.

ABCD
1CustomerTypeList priceFinal price
2Carter BakeryStandard1,200.00
3Peters MotorsKey account4,800.00
4Dr. Patel's PracticeStandard650.00
5Lakeview HotelKey account9,200.00
6Brandt ElectricalStandard2,100.00

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

In real Excel

Procedures with arguments do not appear in the list under Developer > Macros (Alt+F8), because nobody could supply the values there. You always start a macro without arguments, and it calls the others. The same goes for procedures declared as Private Sub: they are visible only inside their own module, which keeps helper procedures out of the list.

Put the cursor on a call in the VBA editor and press Shift+F2 to jump to the procedure being called. When stepping with F8, VBA walks into the called procedure; Shift+F8 (Step Over) runs it in one go. More in Debugging.

Common mistakes

Wrong number of arguments

If the macro calls Flag i, "..." but the procedure has no arguments, or three, VBA reports "Compile error: Wrong number of arguments or invalid property assignment" before it starts. If a Function is missing a required argument, the message is "Compile error: Argument not optional".

Type does not match ByRef

If the caller declares Dim i As Integer but the argument is r As Long, you get "Compile error: ByRef argument type mismatch". With ByRef the type has to match exactly, because the procedure could write straight into the variable. The fix: use the same type, or declare the argument ByVal.

Parentheses without Call

Flag(i, "Needs approval") without Call and without an assignment is a syntax error in the real VBA editor, and the line turns red. With a single argument it does work, but for a different reason: the parentheses turn it into an expression that is always passed ByVal. Stick to the rule: parentheses only with Call or on the right of an =.

Changed by accident through ByRef

If a helper procedure changes its argument, say r = r + 1, and the caller passed its loop counter, the loop suddenly skips rows. Put ByVal in front of every argument that is only an input.

FAQ

Sub or Function?

A Function returns a value and can also be used as a formula in a cell. A Sub does something: fills cells, formats, adds sheets. Rule of thumb: if you need the result on the right of an =, it is a Function.

How do I tell whether an optional argument was passed?

With a default value (= 0.05) you do not need to; the default simply applies. Without a default and with the type Variant, IsMissing(discount) tells you whether it was passed. IsMissing does not work with other types.

How many arguments are too many?

There is no fixed limit. From four or five on, calls get hard to read, though. Named arguments help, or the procedure does too much and should be split.

Learn this next: debugging

With stepping, breakpoints, the Immediate window and the Locals window you see what your macro really does, and you find bugs that never raise a message.

Debugging

Write to us

Choose language

Select your preferred language