A Sub procedure (or subroutine) in Excel VBA is a block of code that performs a specific task when called by the main program or another procedure. Unlike functions, sub procedures don't return a value directly, though they can modify variables or objects passed to them.
Sub ProcedureName([arguments]) ' VBA code goes here ' Perform actions End Sub
Sub procedures can be called in two ways:
' Method 1: Using Call keyword Call ProcedureName(arguments) ' Method 2: Without Call keyword ProcedureName arguments
This example demonstrates a basic sub procedure that displays a message box:
Private Sub CommandButton1_Click() Call ShowWelcomeMessage End Sub Sub ShowWelcomeMessage() MsgBox "Welcome to Excel VBA Programming!", vbInformation, "Greeting" End Sub
This example shows a sub procedure that calculates and displays a salary based on hourly wage and hours worked:
Private Sub CommandButton1_Click() ' Call the salary sub with parameters Call CalculateSalary(15.5, 40) ' $15.50/hour for 40 hours End Sub Sub CalculateSalary(hourlyRate As Double, hoursWorked As Double) Dim totalSalary As Double totalSalary = hourlyRate * hoursWorked MsgBox "Total Salary: $" & Format(totalSalary, "0.00"), vbInformation, "Salary Calculation" End Sub
Note: While the Call
keyword is optional, using it makes your code more readable and clearly indicates where procedures are being called.
Functions in Excel VBA are similar to sub procedures but with one key difference: they return a value to the calling code. There are two types of functions:
MsgBox
, InputBox
, etc.)The InputBox
function displays a dialog box that prompts the user to enter text or a value. It's useful for gathering user input during macro execution.
userInput = InputBox(Prompt, [Title], [Default], [XPos], [YPos])
Parameter | Description | Optional |
---|---|---|
Prompt | The message displayed to the user | No |
Title | The title of the input box | Yes |
Default | Default text that appears in the input field | Yes |
XPos, YPos | Screen coordinates for the dialog position | Yes |
This example prompts the user for their name and displays a personalized greeting:
Private Sub CommandButton1_Click() Dim userName As String ' Get user input with InputBox userName = InputBox("Please enter your name:", "User Information", "John Doe", 500, 300) ' Check if user entered something If userName <> "" Then MsgBox "Hello, " & userName & "! Welcome to our application.", vbInformation, "Greeting" Else MsgBox "You didn't enter your name.", vbExclamation, "Notice" End If End Sub
User-defined functions (UDFs) allow you to extend VBA's capabilities by creating custom functions tailored to your specific needs.
[Public|Private] Function FunctionName([Arg As DataType, ...]) As ReturnType ' Function code ' Assign return value to FunctionName FunctionName = returnValue End Function
Scope Note: Use Public
to make the function available throughout your project, or Private
to restrict it to the current module.
This example creates a custom function to calculate the cube root of a number:
Public Function CubeRoot(number As Double) As Double ' Calculate cube root If number < 0 Then CubeRoot = -((-number) ^ (1 / 3)) Else CubeRoot = number ^ (1 / 3) End If End Function
To use this function in Excel:
=CubeRoot(27)
Here's a more practical example that calculates tax based on income:
Public Function CalculateTax(income As Currency) As Currency Const taxRate As Single = 0.2 ' 20% tax rate ' Calculate tax If income <= 10000 Then CalculateTax = 0 ' No tax for low income Else CalculateTax = (income - 10000) * taxRate End If End Function
Call ProcessData(param1, param2)
or ProcessData param1, param2
FunctionName = returnValue
In the next lesson, we'll explore Excel VBA's built-in Math Functions that can supercharge your calculations!
Call
or directly
Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page