Yes, you should use Function for code that returns a value (like calculations) and Sub for procedures that perform actions (like writing data). The choice depends on whether your VBA code needs to output a result or just execute tasks—this distinction ensures your macros are modular and efficient.
VBA (Visual Basic for Applications) in Excel lets you automate tasks, but writing code incorrectly can create messy, difficult-to-maintain macros. The difference between Function and Sub is foundational: Sub is for standalone routines that don’t return values, while Function is for reusable code blocks that return a single value. This guide covers when to use each, how to call them correctly, and common pitfalls—all explained with practical examples you can test in your own workbook.
What You'll Need
- A working Microsoft Excel file (any version from 2010 or later supports VBA).
- The Developer tab visible in Excel’s ribbon—this is where you enable macros and write VBA code.
- A basic understanding of Excel formulas (like
=SUM()or=VLOOKUP()) to understand howFunctionoutputs work. - Optional: A text editor like Notepad++ or Visual Studio Code for managing VBA projects with multiple modules.
Step-by-Step: Call Function vs Sub in VBA
1. Enable the Developer Tab (Prerequisite)
- Open Excel and click File > Options.
- In the Excel Options window, select Popular from the left menu.
- Check the box for Show Developer tab in the Ribbon and click OK.
- Now you’ll see the Developer tab. If you don’t, restart Excel.
2. Open the VBA Editor
- Click the Developer tab in Excel’s ribbon.
- Click Visual Basic (or press Alt + F11 for a keyboard shortcut).
- The VBA Editor will open, showing a window titled Project Explorer (left panel) and your workbook as a module.
3. Creating a Simple Function
- In the Project Explorer, right-click on ThisWorkbook (or any sheet name) and select Insert > Module. This creates a blank module for your code.
- Type the following code to create a
Functionthat returns the square of a number:Function SquareNumber(ByVal InputNumber As Double) As Double SquareNumber = InputNumber ^ 2 End Function - Explanation:
Function SquareNumber: Names the function (must start with a letter, no spaces).ByVal InputNumber As Double: Declares the input parameter as a value (not a reference) and specifies it’s a number.As Double: Specifies the function returns a number.SquareNumber = InputNumber ^ 2: Assigns the calculated value to the function name, which will be returned when called.
- Close the VBA Editor to return to Excel.
4. Using the Function in Excel
- In any Excel cell (e.g.,
A1), enter:=SquareNumber(5)Excel will return25because 5 squared is 25. - Try other values like
=SquareNumber(3.5)to see it works with decimals.
5. Creating a Sub Procedure
- Return to the VBA Editor (Alt + F11).
- Add this code to the same module to create a
Subthat writes data to a worksheet:Sub WriteDateToSheet() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Sheet1") 'Change "Sheet1" to your sheet name ws.Range("A1").Value = "Last Updated: " & Now() End Function - Explanation:
Sub WriteDateToSheet(): Names the procedure (no return type).Dim ws As Worksheet: Declares a variable of type Worksheet.Set ws = ThisWorkbook.Sheets("Sheet1"): Sets the variable to reference Sheet1.ws.Range("A1").Value = "...": Writes text to cell A1.
6. Running the Sub Procedure
- Return to Excel. You cannot call a
Subdirectly from a cell like a function—it must be run via the Macro dialog or assigned to a button. - Press Alt + F8 to open the Macro dialog.
- Select WriteDateToSheet and click Run.
- The current date and time will appear in cell A1 of Sheet1.
7. Calling a Function from Another Function or Sub
- Modify the
WriteDateToSheetsub to call yourSquareNumberfunction:Sub WriteDateAndSquare() WriteDateToSheet Dim result As Double result = SquareNumber(4) 'Calls the function and stores the result MsgBox "The square of 4 is: " & result 'Shows the result in a message box End Function - Run WriteDateAndSquare from the Macro dialog (Alt + F8).
- You’ll see a message box with the square of 4 (16) and the date/time written to Sheet1.
8. Passing Values Between Functions and Subs
- Create a function that returns a string and a sub that modifies it:
Function GetGreeting(ByVal Name As String) As String GetGreeting = "Hello, " & Name & "!" End Function Sub DisplayGreeting() MsgBox GetGreeting("Excel User") 'Passes the string to a message box End Function - Run DisplayGreeting from the Macro dialog. You’ll see the message: "Hello, Excel User!".
Common Mistakes
Even experienced VBA users make these errors, which can cause macros to fail or behave unexpectedly:
- Using
Subto return a value:- Incorrect: Trying to use a
Subto calculate a result and assign it to a variable (e.g.,Dim x As Double: x = MySub()). - Why it fails:
Subprocedures don’t return values—they execute actions. - Fix: Convert the code to a
Functionif you need a return value.
- Incorrect: Trying to use a
- Forgetting to assign a value to the function name:
- Incorrect: Writing
Function SquareNumber(ByVal x As Double): SquareNumber = x * x + 1(accidentally adding 1). - Why it fails: The function returns an incorrect value because the assignment is wrong.
- Fix: Ensure
SquareNumber = x * x(no extra operations unless intentional).
- Incorrect: Writing
- Calling a
Subfrom a formula:- Incorrect: Entering
=MySub()in a cell. - Why it fails: Excel formulas only work with functions that return values.
Subprocedures cannot be referenced this way. - Fix: Use a
Functionfor formula calls or trigger theSubvia a button/macro.
- Incorrect: Entering
- Ignoring variable scope:
- Incorrect: Declaring variables inside a function/sub but using them outside their scope.
- Why it fails: VBA variables are local to their block unless declared as
Publicor in a module-level scope. - Fix: Use
Publicfor shared variables or pass values explicitly between functions.
Tips for Better VBA Code
Follow these practices to write cleaner, more maintainable VBA code:
- Use
Functionfor calculations:- If your code performs a calculation (e.g., summing a range, formatting data), wrap it in a
Functionso it can be reused in Excel formulas or other macros. - Example: A function to calculate VAT from a price is more flexible than a sub that updates a worksheet.
- If your code performs a calculation (e.g., summing a range, formatting data), wrap it in a
- Use
Subfor actions:- If your code modifies data, triggers events, or interacts with the user (e.g., opening a file, sending emails), use a
Sub. - Example: A sub to export data to a PDF is better suited than a function.
- If your code modifies data, triggers events, or interacts with the user (e.g., opening a file, sending emails), use a
- Name your functions/sub descriptively:
- Avoid generic names like
Calc1. Use names that describe the purpose, likeCalculateTaxorEmailReport.
- Avoid generic names like
- Use
Option Explicit:- At the top of every module, add
Option Explicit. This forces you to declare all variables, catching typos early. - Example:
Option Explicit Function SquareNumber(ByVal InputNumber As Double) As Double
- At the top of every module, add
- Avoid global variables:
- Use module-level variables sparingly. Instead, pass values as arguments or return them from functions.
- Example: If you need to share data between functions, return it from a function and pass it to another.
- Test your functions in the Immediate Window:
- In the VBA Editor, press Ctrl + G to open the Immediate Window.
- Type
?SquareNumber(3)and press Enter to debug quickly without running the full macro.
Troubleshooting
If your VBA code isn’t working as expected, follow this troubleshooting order:
1. Check for Syntax Errors
- In the VBA Editor, press F7 to run the macro in debug mode. If there’s a red underline, it highlights the error.
- Common syntax errors:
- Misspelled keywords (
FunctionvsSub). - Missing semicolons or colons (e.g.,
SquareNumber = InputNumber ^ 2must have no extra spaces). - Incorrect variable declarations (e.g.,
Dim InputNumber Aswithout specifying the data type).
- Misspelled keywords (
2. Verify Parameter Types
- If you pass the wrong data type (e.g., a string where a number is expected), the function may return unexpected results or cause errors.
- Example: Passing
"5"(a string) to a function expecting a number will fail unless you convert it withCDbl("5").
3. Ensure Functions Are Returning Values
- If your function doesn’t return a value (e.g., missing the assignment statement), it will return
0for numeric types orEmptyfor strings. - Example: If you write
Function SquareNumber(ByVal x As Double)without assigning a value, it will return nothing.
4. Check Macro Security Settings
- If macros aren’t running, Excel’s security settings may block them.
- Click File > Options > Trust Center > Trust Center Settings > Macro Settings.
- Select Enable all macros (not recommended for untrusted files) or Disable all macros with notification to test.
5. Debug Step-by-Step
- Set breakpoints by clicking the left margin of the VBA Editor (a red dot appears).
- Run the macro (F5) and pause at each breakpoint to inspect variables.
- Use F8 to step through code line-by-line.
6. Rebuild the VBA Project
- If your code is corrupted, close the VBA Editor and reopen it.
- Go to Tools > Import/VBAProject > Import File to reload your module.
- As a last resort, delete the module and recreate it.
Frequently Asked Questions
Can I use a Function to modify data like a Sub?
No, functions are designed to return a single value. If you need to modify data (e.g., write to a worksheet), use a Sub instead. Functions can only return one value, while Sub procedures can perform multiple actions.
Why does my Function return 0 or Empty?
This happens if you forget to assign a value to the function name (e.g., SquareNumber = is missing). Ensure every function has an assignment like SquareNumber = InputNumber ^ 2. Also check for typos in the function name or missing End Function.
How do I call a Function from another workbook?
You can reference functions from another workbook by qualifying the workbook name. In the calling workbook’s module, use:
Function CallExternalFunction(ByVal WorkbookName As String, ByVal FunctionName As String, ByVal Param As Variant) As Variant
Workbooks(WorkbookName).VBAProject.VBComponents("Module1").CodeModule.Run FunctionName, Param
End Function
Note: This requires the target workbook to be open and its VBA project accessible. For security, avoid calling external functions unless trusted.
Can I return multiple values from a Function?
No, VBA functions can only return a single value. To return multiple values, use one of these workarounds:
- Return a custom object or array.
- Use a
Subto pass values via parameters. - Store results in a worksheet range and reference it.
Function GetMultipleValues() As Variant
GetMultipleValues = Array(10, 20, 30) 'Returns an array of values
End Function
How do I know if a macro is a Function or Sub?
Check the header of your code:
- A Function starts with As [Type] (e.g., Function SquareNumber(ByVal x As Double) As Double ).
- A Sub starts with (no return type, e.g., Sub WriteDateToSheet() ).
Why can’t I use a Function in a formula like a built-in Excel function?
Excel formulas only work with functions that are declared as Function in your workbook. If your custom function isn’t returning a value correctly or isn’t declared in the correct module, the formula will show an error (#NAME?, #VALUE!, or #N/A). Verify:
- The function is saved in a module (not in
ThisWorkbookor a sheet module unless intended). - The function is named without spaces or special characters.
- The syntax matches Excel’s expectations (e.g., parentheses and arguments).
How do I assign a Sub to a button in Excel?
To run a Sub with a button:
- Insert a button: Go to the Developer tab > Insert > Button (Form Control). Draw the button on your sheet.
- Right-click the button and choose Assign Macro.
- Select your
Subfrom the list (e.g., WriteDateToSheet) and click OK. - Click the button to run the macro. If the button doesn’t appear, ensure the Developer tab is enabled and Form Controls are available.