top of page

VBA: Understanding Workings and Subroutines a Guide to Automation in Excel and Beyond

  • Writer: Fakhriddinbek
    Fakhriddinbek
  • Oct 8
  • 4 min read

Updated: Oct 25

Visual Basic for Applications (VBA) is the scripting language embedded in many Microsoft Office applications, including Excel, Word, and PowerPoint, enabling users to automate tasks and create powerful macros. At the core of VBA programming are subroutines — blocks of VBA subroutines code that perform specific tasks.


In this comprehensive guide, you'll learn:

  • How VBA works behind the scenes to execute macros

  • The concept and structure of subroutines (Subs)

  • How to create, call, and manage subroutines

  • Step-by-step examples of subroutine usage in Excel

  • How AI tools can help you write and debug VBA code involving subroutines

  • Best practices for writing clean and maintainable VBA code

  • FAQs addressing common questions about VBA workings and subroutines


How VBA Works: The Basics of VBA Execution

When you write VBA code, it doesn’t run automatically. Instead, VBA waits for a trigger — such as running a macro manually, clicking a button, or responding to an event like opening a workbook.


VBA Execution Flow

  • Code Organization: VBA code is organized in modules, which contain subroutines and functions.

  • Subroutines Execution: When a macro runs, VBA executes the code within the subroutine from top to bottom.

  • Event Handlers: VBA can respond to events like clicking buttons, changing cells, or opening files, triggering relevant subroutines automatically.

  • Interaction with Objects: VBA manipulates Office objects — such as worksheets, ranges, and charts — to perform actions.


What is a Subroutine (Sub) in VBA?

A subroutine, commonly called a Sub, is a named block of code that performs a task but does not return a value.


Subroutine Syntax

Sub SubName()

' VBA statements here

End Sub


  • SubName is the name you give the subroutine.

  • The code between Sub and End Sub defines what the subroutine does.


Example: A Simple Subroutine

Sub ShowMessage()

MsgBox "Hello, this is a VBA subroutine!"

End Sub


To execute this, you open Excel’s Developer tab, click Macros, select ShowMessage, and press Run. A message box appears with the greeting.


Step-by-Step: Creating and Running Your First Subroutine in Excel


Step 1: Open the VBA Editor

  • Press Alt + F11 in Excel.


Step 2: Insert a New Module

  • In the Project Explorer, right-click your workbook.

  • Click Insert > Module.


Step 3: Write the Following Simple Subroutine

Sub WelcomeUser()

MsgBox "Welcome to VBA automation!"

End Sub


Step 4: Run the Macro

  • Switch back to Excel.

  • Go to Developer > Macros.

  • Select WelcomeUser and click Run.


Excel VBA setup with an empty spreadsheet. A dialog box says "Welcome to VBA automation!" and VBA code displays in the editor.
Excel sheet with a VBA code module displayed, featuring a "Welcome to VBA automation!" message box, demonstrating how to initiate basic automation in Microsoft Excel using Visual Basic for Applications.

You should see the welcome message pop up — congratulations, you’ve created and run your first VBA subroutine!


Calling Subroutines: Modular and Reusable Code

Writing code inside subroutines helps keep your programming organized. You can call subroutines from other subroutines, enabling modularity and reusability.


Example: Calling One Subroutine from Another

Sub Greet()

Call DisplayMessage

End Sub


Sub DisplayMessage()

MsgBox "This message is from DisplayMessage subroutine."

End Sub


When you run Greet, it calls DisplayMessage which performs an action.

You can simplify Call by writing:

Sub Greet()

DisplayMessage

End Sub


Passing Arguments to Subroutines

Subroutines can accept parameters (arguments) to make them more flexible.


Syntax

Sub MySub(parameter1 As String, parameter2 As Integer)

' Use parameters in code

End Sub


Example

Sub GreetUser(userName As String)

MsgBox "Hello, " & userName & "!"

End Sub


Sub RunGreeting()

GreetUser "Alice"

End Sub


RunGreeting calls GreetUser passing “Alice” which customizes the message.


How AI Tools Can Assist with Writing and Debugging Subroutines

AI-Assisted Code Generation

  • ChatGPT: Generate VBA subroutines from simple English instructions (e.g., “Write a VBA subroutine to sum values in column A”).

  • GitHub Copilot: Suggest code completions and entire subroutine templates inside VS Code.


AI Debugging and Explanation

  • Paste problematic VBA code or error messages into AI chat tools for troubleshooting advice.

  • Get explanations of subroutine behaviors and best practices.


Practical Example: Automating a Subroutine That Deletes Blank Rows in Excel

Step 1: Open VBA Editor and Insert Module


Step 2: Paste the following code into the module:

Sub DeleteBlankRows()

Dim lastRow As Long

Dim i As Long

With ActiveSheet

lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

For i = lastRow To 1 Step -1

If Application.WorksheetFunction.CountA(.Rows(i)) = 0 Then

.Rows(i).Delete

End If

Next i

End With

End Sub


Excel sheet with numeric data on left, VBA editor with code for deleting blank rows on right. Green logo in bottom left corner.
Excel spreadsheet displaying numerical data on the left and a VBA editor on the right, featuring a script designed to automate the deletion of blank rows in the active sheet.

Step 3: Run the macro to remove blank rows from the active sheet.


Excel with data on left and VBA code for deleting blank rows on right. Green and red accents. Text: Welcome to VBA automation.
Excel VBA script for automating the deletion of blank rows, alongside a spreadsheet filled with numerical data, displayed in the Visual Basic for Applications editor and Excel interface.

Best Practices for Using Subroutines in VBA

  • Use meaningful and descriptive names.

  • Group related code into reusable subroutines.

  • Keep subroutines focused on a single task.

  • Comment your code to clarify intent.

  • Pass parameters to avoid hardcoding values.

  • Avoid excessively long subroutines; break into smaller pieces.


Frequently Asked Questions (FAQ)

Q1: What is the difference between a subroutine and a function in VBA?

A: Subroutines perform actions but do not return values; functions return values and can be used in worksheet formulas.


Q2: Can subroutines have parameters?

A: Yes, parameters allow passing data into subroutines for dynamic operation.


Q3: How do I call one subroutine from another?

A: Simply use the subroutine’s name in your code, optionally with arguments.


Q4: Can I run multiple subroutines in sequence?

A: Yes, you can call multiple subroutines in any order inside a master subroutine.


Q5: How can AI help me learn or debug VBA subroutines?

A: AI tools can generate VBA code snippets based on your requests, explain code, and help identify and fix errors.


Q6: What is the best editor to write VBA subroutines?

A: The VBA Editor inside Microsoft Office apps (Alt + F11) is the default and best for VBA development.


Q7: Can VBA subroutines interact with Excel objects like sheets and ranges?

A: Absolutely! VBA subs can manipulate worksheets, ranges, charts, and more.


Start Building Your Own VBA Subroutines Today!

Ready to automate your workflows and master VBA programming? Begin by creating simple subroutines to perform routine tasks and gradually advance to modular, parameterized code.

Explore AI tools like ChatGPT and GitHub Copilot to accelerate your learning and coding process. Experiment, test, and refine your macros for greater efficiency.


Take control of your Excel automation — write your first VBA subroutine now and unlock powerful productivity gains!

Comments


bottom of page