12.5 Sub Procedures
Sana opens a shift report with an empty title and date. She wants a named action she can run again each morning. A VBA Sub gathers those instructions into a procedure. You will create one small Sub, then have two clearly named Sub procedures share a helper that receives the worksheet, title and report date.
Give one procedure one understandable job
Start with the outcome on the sheet
FreshGo is a fictional team serving a Blinkit-style delivery operation. The names, dates and workflow in this lesson are invented. The team wants a handoff workbook with a short heading, a report date and the usual amount calculations below. A person preparing the workbook has to name it consistently. They can press a command to write a few values and format the date. That repeated action is small enough to turn into a first procedure and small enough to check cell by cell.
A procedure is a named group of instructions. In VBA a Sub begins with a declaration specifying its name and optional parameters. It ends with End Sub. The name allows another part of the workbook or a person in the Macros dialog to call the instructions as one action. A Sub performs actions and does not return a value like a Function. It may still write values into the workbook, display messages or change a variable passed to it under the relevant argument rules. Those effects and its intended scope belong in the description of the procedure.
- Declaration: The line
Public Sub PrepareDailyReport()declares a public procedure named PrepareDailyReport. An empty pair of parentheses here means this procedure has no parameters. A public no-argument Sub in a standard module is a useful starting action for the Macros dialog in Excel. - Body: The instructions below the header do the work in order. They can name the destination object, put a value in a cell, set its display format and then show a message. Place broad explanations beside the section they describe, as a comment, so the next reader understands the intended effect.
- End: Reaching End Sub finishes this routine. An Exit Sub can end its execution early, for example when an input check fails. When one procedure calls another, the caller resumes after that call when the called procedure completes normally. An unhandled error can interrupt that path.
- Visibility: A private helper in a standard module is callable from procedures within that module. Its name need not appear to the spreadsheet operator as a command. Share a public entry point for the actions a real user should invoke. Put dependency checks and any target selection at a clear place in the code.
Make room for both the day and the figures
Use A1 for the title and A2 for a date. A real Excel date can be calculated and formatted. Changing how the date is displayed does not replace it with a text label. For example entering a date and formatting it as day, month and year leaves it usable as a date. The code asks Excel to use the desktop system date in the first example. A later example takes a fixed report date from the caller, so you can practise the same layout even when the training takes place on different days.
Give the procedure a narrow write scope. It can fill A1, format the title and change A2. A few test amounts and the total below the heading should remain intact. If your project grows to include a separate summary operation, give that job another name and test it separately. A procedure called PrepareDailyReport should not hide actions that send the file or edit more worksheets without making that behavior clear.
Remember: A clear Sub name describes the workbook action. The entry line shows who can call it and what a caller must supply. The body provides exactly the effects you can test.
Follow a call from start to finish
A public entry point supplies the details to a private helper
The Morning and Afternoon sheets have the same heading positions. The titles and dates can differ. Instead of copying every statement to two places, let each public routine choose a sheet and give a private helper the three values it needs. The helper can still act on the worksheet object supplied to it and write A1 and A2. It does not need to know which shift is active on screen. If the analyst decides to standardize the heading format, they can change the shared helper once and verify both public routes.
- Parameter: A name in the procedure declaration, such as
target As Worksheet, tells the procedure what input it expects. It exists under that name while the procedure runs. - Argument: The actual value supplied by the caller. A named worksheet object, a title string and one Date value are the arguments for this example. Order and type matter unless you deliberately use named arguments where supported.
- ByVal: Pass the value of an argument into its parameter. A text parameter can be reassigned inside the helper without replacing the text variable in the caller. For a worksheet object, the transferred value is an object reference. The helper can still change the cells of that same worksheet. Reassigning its local reference is different from editing the workbook object it points to.
- ByRef: A parameter can refer to the caller's variable so the procedure can change its value. VBA's default parameter passing is ByRef unless you specify otherwise. When you want a helper to read values while it performs a clearly specified worksheet action, using explicit ByVal on these arguments makes that intent easier to see.
Read the punctuation in a call
For a helper with arguments, a direct call on a line by itself can list the arguments after the procedure name without wrapping the list in parentheses. If you use the optional Call keyword, place the argument list inside parentheses. These are two ways to express the same call in this lesson. Choose one line in the practice module. Adding both causes two executions. The declaration of the helper still uses parentheses around its parameter list.
WriteReportHeading ws, headingText, reportDay
Call WriteReportHeading(ws, headingText, reportDay)
VBA allows you to split a statement across physical lines using a continuation: a space and underscore at the end of the continued line. This is useful when a parameter list becomes too long for the code window. Keep the procedure declaration itself short enough to skim. Use the apostrophe character for a comment. A comment explains a choice such as which cells belong to the report heading. It does not run and will not change a cell even if it mentions a command.
Lab one. Write a small report header with one Sub
Build a two-row fixture you can check
Make a copy called SubPractice.xlsm in approved desktop Excel. In that workbook create a Report sheet and a Notes sheet. The code and worksheets should stay together throughout this exercise. In the Report sheet reserve A1 for the title and A2 for the date. Put one amount in B5 and another in B6, then use the formula in B7 to sum them. Type “Keep this Notes text” on the Notes sheet. That gives you a marker in a different worksheet to confirm its contents did not change.
| Worksheet | B5 | B6 | B7 |
|---|---|---|---|
| Report | 90 | 105 | 195 |
| Morning | 80 | 120 | 200 |
| Afternoon | 85 | 75 | 160 |
B7: =SUM(B5:B6)
Begin with the Report row in the table. Keep the other two rows for Lab two. On Report, verify B7 is 195 before you run any code. In the VBA editor find the project for SubPractice and add a standard module. The code below applies the title and today's system date to that project's Report sheet, then confirms both instructions ran. Review the write range before leaving the editor. Use the trusted workbook you made and leave your normal program policy in place.
Option Explicit
Public Sub PrepareDailyReport()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Report")
' Keep these styles within the two heading cells.
ws.Range("A1").Value2 = "FreshGo Maharashtra - Daily Report"
ws.Range("A1").Font.Bold = True
ws.Range("A2").Value = Date
ws.Range("A2").NumberFormat = "dd-mm-yyyy"
MsgBox "Report header ready.", vbInformation
End Sub
Run only the project you just prepared
- Read the declaration and body. Check that the standard module belongs to SubPractice and the visible Report worksheet exists there. The procedure sets its worksheet reference at the start. No action depends on the selection for this example.
- Save the workbook as the macro-enabled kind. In the VBA editor you can place the cursor inside PrepareDailyReport, then run the current procedure with the editor's Run command or F5 where supported. Alternatively choose PrepareDailyReport in Developer Macros. Keep the focus out of the VBA code while using the worksheet's Macros dialog.
- After acknowledging the message, inspect Report A1 and A2. The heading should read FreshGo Maharashtra - Daily Report in bold. A2 should show the current date of your desktop in day-month-year form in a compatible display. Compare the date to your local system day. If your textbook calendar differs, this live result is allowed to differ.
- Inspect B5, B6 and B7, and the Notes text. The formulas should yield the same 195 and the markers remain. Run this same Sub again from Notes to prove that it finds the named Report after you change tabs. If your environment cannot execute it, draw the before-and-after cells on paper and use the visible source code to predict the contents.
- After the run, check the value in A2. Use the formula
=ISNUMBER(A2)in an unrelated practice cell or temporarily view another date format. Excel dates are stored as serial numbers, so the number test can be true even while you see a date. The displayed format is distinct from storing the date as text. Remove the temporary test cell when you finish.
Notice the difference between contents and format: There are four small writes in the procedure and a final message. Two statements affect A1 and two affect A2. A global change to the workbook's date settings is unnecessary. If a sheet is protected or a lookup fails, do not infer success from a message you remember from a prior run.
Lab two. Reuse a helper on two exact worksheets
Share the action while keeping its inputs explicit
Create Morning and Afternoon worksheets in the same practice workbook. Use B5, B6 and B7 as in the table. Give them different amounts so their totals identify the intended report. Leave A1 and A2 empty on each sheet. Paste the two public commands and the private helper at the end of the same standard module, beneath the first procedure. Keep the one Option Explicit declaration at the very top.
Public Sub PrepareMorningReport()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Morning")
WriteReportHeading ws, "FreshGo Morning", DateSerial(2026, 11, 24)
MsgBox "Morning header ready.", vbInformation
End Sub
Public Sub PrepareAfternoonReport()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Afternoon")
Call WriteReportHeading(ws, "FreshGo Afternoon", DateSerial(2026, 11, 25))
MsgBox "Afternoon header ready.", vbInformation
End Sub
Private Sub WriteReportHeading(ByVal target As Worksheet, _
ByVal headingText As String, _
ByVal reportDay As Date)
target.Range("A1").Value2 = headingText
target.Range("A1").Font.Bold = True
target.Range("A2").Value = reportDay
target.Range("A2").NumberFormat = "dd-mm-yyyy"
End Sub
Compare the two calls from the other worksheet
- While you are viewing Afternoon, run PrepareMorningReport from the Macros dialog. Read Morning A1 as FreshGo Morning and A2 as the date for 24 November 2026. Morning B7 should remain 200. Afternoon A1:A2 should still be empty and its total should stay at 160. Use the workbook-specific Macros scope so similarly named entries elsewhere do not confuse the test.
- Now view Morning and run PrepareAfternoonReport. Afternoon A1 and A2 receive FreshGo Afternoon and 25 November 2026. Thanks to the same helper, its date and header use the same style as Morning. Go back to Morning and verify its earlier title and date are unchanged. If two different headings appear on just one sheet, look for a missed worksheet qualifier.
- Compare the first and second call syntax. The first command uses a no-Call call with a comma-separated argument list. The second uses Call and enclosing parentheses. In both forms the expressions inside DateSerial still use their own parentheses. The arguments agree with the same declaration. This is one reusable implementation with two ways of spelling a Sub call.
- Temporarily change the first caller's review date to 26 November using the corresponding DateSerial argument. Rerun only the morning command. Expect its A2 to move to 26 November and the afternoon date to stay at 25. Restore the original constant in the lab code and verify normal output. The date changed because of one caller's input, not because you needed a second implementation.
- Enter a temporary spelling error in an isolated copy's call, then use the editor's Compile command if available. An undefined procedure name is useful evidence about the call path. Restore the correct name, compile again and discard or save the isolated copy after verifying the original practice file is unaffected.
Track the point where control returns
Start the morning procedure
The public command finds Morning in this workbook and prepares an exact heading and date.
Give the arguments to the helper
The helper's target points to Morning and reportDay contains 24 November 2026. Afternoon stays untouched even if it is visible.
Write the two heading cells
The helper fills Morning A1 and A2, then sets their style. It does not need to sum the report data.
Continue in the caller
Once the helper completes normally, the caller displays the message. Verify the actual two headings and the independent amount of 200.
Trace argument passing with a third quick experiment
Observe a value inside a helper and back in its caller
Consider three boxes packed before a delivery cutoff. The caller's counter starts at three. A helper wants to demonstrate adding one without changing the count the caller will use. A separate helper is supposed to let the caller retain the increment. Both can use a parameter called count. The important change is which kind of parameter the helper declares. Follow the print output, which is easier to prove than a screenshot after both helpers have finished.
Public Sub TraceCountArguments()
Dim packedBoxes As Long
packedBoxes = 3
AddOneLocally packedBoxes
Debug.Print "Back after ByVal:", packedBoxes
AddOneForCaller packedBoxes
Debug.Print "Back after ByRef:", packedBoxes
End Sub
Private Sub AddOneLocally(ByVal count As Long)
count = count + 1
Debug.Print "Inside ByVal:", count
End Sub
Private Sub AddOneForCaller(ByRef count As Long)
count = count + 1
Debug.Print "Inside ByRef:", count
End Sub
- Place the three procedures in the standard module of your own practice workbook. Choose the TraceCountArguments entry from Developer Macros. It prints four trace lines in Immediate, without changing any cell. Use only this known input and keep the usual workbook policy.
- On the first call, the ByVal helper receives a Long numeric value equal to three. It increments its own parameter to four and prints four. When it finishes, the original packedBoxes remains three. The caller prints three.
- On the second call, the ByRef helper receives the caller's Long variable by reference. Increasing that parameter increases packedBoxes. The second helper prints four, and the caller prints four on the last line.
- If you choose to test another start, use an isolated practice version and change packedBoxes from three to seven. Before running, predict eight, seven, eight and eight. The whole procedure resets its local variable at the start of each run, so a rerun from the original code prints the same four values.
| Moment | Printed value | Reason |
|---|---|---|
| Inside ByVal | 4 | Only the copied parameter changed |
| Back after ByVal | 3 | The caller kept its variable |
| Inside ByRef | 4 | The helper changed the caller's variable |
| Back after ByRef | 4 | The new value is visible to the caller |
Connect the trace to the worksheet argument
Goal and mechanism meet here. Marking a worksheet parameter ByVal says the helper gets a copy of the caller's object reference. The copied reference still identifies the same worksheet. The helper can use it to change A1 or A2. This is different from changing which worksheet the caller's variable points to. If you want a helper that only inspects a worksheet, its code must restrict its effects to reads. A parameter modifier describes argument passing. Test the actual body for the effects the user cares about.
Likewise, declaring a Date parameter ByVal is useful when the helper takes a single report date. The caller supplies an actual Date expression, such as the result of DateSerial. The helper writes that date into the cell, then chooses the display format. It is not a request for the helper to change the desktop's date or the caller's date variable. The extra trace shows how to reason about changes to variables. The heading lab shows how to reason about changes to objects the variables describe.
Review each action's effects and dependencies
Choose a fixed value or data from the caller
The first routine chooses the current date during every run. That works for making a heading for today's empty sheet. Suppose the workbook still describes yesterday's orders. Opening it today and pressing the routine would replace the date with the current system day. The header could look correct while the report label is wrong for those rows. In a real handoff identify whether the heading means a preparation date or the business date of the underlying orders. If it means the latter, decide where the checked business date comes from before passing it to the helper.
- Single use: Put enough information in the public command that an operator can run it intentionally without supplying code. The first training procedure takes no arguments and writes the current date. Its limitation is documented and testable with a simple number check.
- Reuse: Make repeated behavior a helper when multiple callers can provide the exact piece that differs. Morning and Afternoon share the format and cells. Their title and date differ. The public procedures pick the worksheet and make the correct call.
- Hidden dependency: A worksheet's active status is an input if the code uses ActiveSheet. Another user can change it by clicking a tab. The helper in the second lab receives a worksheet instead. Verify the effect while the other sheet is selected to prove this separation.
- Early exit: If the right layout is missing, a real public procedure could display a useful message and leave before writing. If a private helper exits normally without doing the work, the caller proceeds to its next line. A final success message should depend on whether the expected writes happened, not simply on whether the helper returned. A function can report a success value, or you can validate before calling the helper.
- Partial results: These tiny routines write several properties in order. One successful statement may change a cell even if a later statement fails. Work on a copy and inspect the actual two cells. A later error-handling lesson shows how to report where failures happen. For operational automation you need a policy for recognizing and recovering from a partial output.
Say what the caller resumes after
Follow PrepareMorningReport down from its first line. The worksheet lookup establishes the target and the call supplies title and date. For the duration of the call, the private routine runs its four writes in order. When it reaches End Sub, VBA returns to the line after the call in PrepareMorningReport. That is the point where the message appears. If you wanted to check the resulting sheet before this message, this is where to put that test. A comment inside the helper does not automatically make the caller wait for a different event.
Two common variations are worth tracing on paper. If you switch the worksheet argument in PrepareMorningReport to Afternoon while keeping its title, the helper writes FreshGo Morning on the wrong sheet. The exact same private code is still valid. The bad pairing was made in the public routine. If you change the private helper to put the date in A3, both public paths will now change A3. In the first case inspect the argument value. In the second inspect the helper's implementation. Their outward symptoms can look similar until you compare both sheets independently.
Check that your action has a stable boundary
An account manager could put a button beside each public call. Name one Prepare morning header and the other Prepare afternoon header, and require a separately verified calculation before the report leaves the owner's workflow. Compare the spreadsheet result with the instruction rather than concluding from the button label. We use the distinct totals of 200 and 160 as controls. They should survive in each sheet because neither code route is responsible for the amount calculation. This is especially helpful when a colleague later adds new private helpers to the same module.
Predict the display: If you call the morning command from Notes on a machine where today's actual date is different, Morning still receives the fixed report date in that command. In the first lab, the Report sheet receives the desktop's current date. Explain the different results by pointing to both arguments and the assignment statement.
Fix the named procedure before adding new actions
Five common situations with separate checks
- No macro in the dialog: Check that the entry point is a public no-argument Sub in a standard module. Filter the dialog to the expected workbook. A private helper with arguments is deliberately called by a public procedure in the same module. Running the helper by itself would omit its three required inputs. The file must retain the VBA and the app must support running it.
- Compile reports a missing procedure: Compare the name after Call with the name declared after Private Sub. They should refer to the same implementation in the module. Check whether you pasted the caller and helper into different modules, which can make a private helper unavailable to the intended caller. Place them together for this lab. If an existing name is already defined, give the new practice routine an unambiguous name before wiring another control.
- Compile points to a line break: Check how you pasted the long helper declaration. Each continued line should end with a space and underscore. The next line holds the continuation of the same statement. If you put a comment on the wrong line or include a typographic quote copied from formatted text, it can disrupt the statement. Use the exact code or write a shorter one-line declaration while learning.
- The date format looks different: Verify both the stored date and its display. A2 may show a number in General format or a row of hash marks when too narrow. Read the value in the formula bar, widen the column if the display is cramped, and use the separate date format as written for the lab. If Excel actually has text instead of a date, changing the display format alone cannot convert it into a date value.
- The report was on the wrong sheet: Read the public caller's worksheet lookup and the helper's destination. The two checks are different. A sub can correctly apply a heading to a worksheet after being handed the wrong object. Reproduce on a fresh copy, use one distinct title per sheet and compare the two unchanged total formulas along with the written heading.
Add a useful third caller on paper
A supervisor asks for an evening preparation action. Keep a predictable grid. If Evening contains only the same sample layout, the new caller can ask the workbook for Evening and pass its own title and report day to the shared helper. Choose quantities 65 and 50 in B5 and B6, so B7 should read 115. Pick a fixed date, such as 26 November 2026, and write a short specification: “PrepareEveningReport writes FreshGo Evening and the agreed date to Evening A1:A2 and retains 115 below.” If the worksheet locations change, decide whether your helper needs an explicit destination range before asking every caller to use it.
Test your proposed addition mentally before extending the workbook. The new public command can appear in the Macros dialog, while the helper stays private. Running Evening from Morning cannot change the two other headings if every worksheet lookup and passed object is correct. A copy of the helper pasted inside each public command would mean three implementations to keep in sync. Keeping one correctly scoped helper lets you review a format change with three independent caller tests.
Confirm the actual report date and its display
In the ordinary Gregorian setup for the lab, write an independent check for Morning A2. Use an unused exercise cell with an equality comparing A2 to Excel's DATE function with year 2026, month 11 and day 24. That comparison should be true after the morning run, even if you temporarily choose a longer display style. Test the next day's date for Afternoon separately. In localized Excel use the corresponding function name and list separator. If the check fails, first check which sheet was written and confirm whether A2 contains a date value or text.
The unit of the date matters too. Comparing against 24 November is a date-only check for this exercise. If you later use a timestamp, its time fraction can make it unequal even when it displays the same day. State whether your routine stores a date or a full timestamp before building an independent test around it.
Read a possible support handoff
Here is an example of a note another learner can follow: “Open SubPractice in approved desktop Excel. On any tab, pick PrepareMorningReport from This Workbook. Read FreshGo Morning and 24 November in the Morning header and 200 in its amount formula. Check the Afternoon marker, title and amount independently.” The name of the command is clear because it begins with a verb. The output is clear because the note names both cells and values. The preservation check protects against the procedure unintentionally reaching across reports.
If the person cannot run VBA, they can still trace the declaration, DateSerial argument, write statements and returns. They can try both dates on a paper template and read the amount formula. Record whether the behavior was predicted or observed. This skill is especially useful when you cannot safely run an unfamiliar procedure to find out which workbook it intends to edit.
Quick checks
Follow the name, input and effect
Which part of a Sub tells you what arguments it expects?
The declaration lists the parameters inside parentheses. In WriteReportHeading, it lists a Worksheet, a String and a Date. The caller supplies actual arguments matching those meanings. A procedure with empty parentheses takes no arguments in this lesson.
Does setting ByVal on the Worksheet argument protect that sheet from edits?
The helper receives a copy of the reference to the sheet. It can still use that reference to change the same worksheet object. The declaration does not promise the body is read-only. Review the two Range assignments and their formatting effects to verify the actual result.
What happens to packedBoxes on the first and second helper calls?
It starts at three. The ByVal helper prints four inside, while the caller still prints three. The ByRef helper then increments the caller's variable from three to four. Both its own print and the caller's final print show four.
When do you use parentheses around a Sub call's argument list?
Use them when the call begins with Call, as in the afternoon procedure. With the direct no-Call form shown for the morning, list the arguments without enclosing the entire list. A nested function such as DateSerial still has its own parentheses for the values it receives.
Why do Morning and Afternoon receive different date values if they use the same helper?
Each public procedure explicitly supplies its own date. The helper receives the argument, stores it in that sheet's A2 and applies the same display format. It processes a different input for each call. A date set with DateSerial is repeatable independently of the current system day.
Which result should a newly prepared Report header leave untouched?
The inputs in B5 and B6 still total one hundred ninety-five through the B7 worksheet formula. The macro changes the title and date near the top. Inspect the Notes marker too. A changed total would reveal an effect outside the procedure's intended scope or an unrelated data change.
Interview and discussion
Justify small procedures using a report example
When would you use a Sub rather than a worksheet Function?
Use a Sub for the visible action of writing and formatting the two header cells. It can accept parameters and have workbook effects. Use a function when the caller needs a value, such as a fee or independently calculated total. A worksheet UDF should return its result through its formula cell instead of clearing other ranges.
Why do the first lab's commands mention ThisWorkbook?
The public procedure finds its named worksheet in the workbook that owns the code. This keeps the known example independent of the tab the person currently views. Moving the code into a different project would change what ThisWorkbook refers to, so the workbook containing the module belongs in the test plan.
How would you test that a change in the shared date format is correct?
Update the helper in a practice copy and run both public commands. Read the two DateSerial values and confirm their new display while the underlying dates and amount formulas remain right for both sheets. Because both public routines call this helper, test both paths even if only one previously needed the change.
Should a private routine display every success message?
That depends on who calls it. A helper can perform a narrow shared action, while each caller shows a message in the appropriate shift's terms. If a helper may exit early after checking something, arrange for the caller to know whether the action succeeded before printing its success message.
What checks tell you whether a worksheet changed or a caller's variable changed?
Read the worksheet and the variable separately. In the heading exercise, the ByVal reference still lets the helper change A1 and A2. In the counter exercise, inspect the four Immediate messages to observe the caller remaining at three after ByVal and moving to four after ByRef. The two experiments exercise different kinds of changes.
Six recall cards
- Procedure shape
Sub starts one named action and End Sub finishes it. Put one understandable job in its body.
- Public entry point
Use a public no-argument Sub in a standard module for a command a person can invoke from the worksheet's Macros dialog.
- Private teammate
A helper can live in the same module and receive explicit inputs from its callers. Two reports can share one implementation.
- Arguments
Pass the correct Worksheet, title and date at the call. Use parentheses with Call when supplying the whole argument list.
- Reference effects
ByVal copies the argument value. For a worksheet reference the copied value still points to the same object.
- Final proof
Check both changed header cells and the amount that must survive. Compare the corresponding cells on the other worksheet too.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.