• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

More Tips for Debugging VBA

You are here: Home / Excel VBA / More Tips for Debugging VBA
More Tips for Debugging VBA
May 12, 2017 by Philip Treacy

After my last post on debugging VBA I received a few comments with other tips or commands people use for debugging. I'm going to have a look at these here.

Option Explicit

The first thing is using the Option Explicit statement. There are a number of Options you can use in VBA, and Option Explicit tells VBA that every variable needs to be declared before it is used.

I'm not sure why this isn't a default really as using variables that aren't declared can only lead to trouble. Let's look at an example.

Let's say we have a variable called val and we to use it calculate a result.

Sub MoreDebugging()

    Dim result as long

    result = val * 2

End Sub

If you run this without the Option Explicit statement, the code will run, but result will contain 0 as val has not been declared or assigned a value.

This seems obvious in a simple example like this, but if you have dozens, or hundreds of lines of code, and you use variables without declaring them, it can lead to all sorts of problems.

Adding Option Explicit to the top of the code module tells VBA to check that all variables are declared, and if they are not, you'll get a 'Variable not defined' error.

Option Explicit

Sub MoreDebugging()

    Dim result as long

    result = val * 2

End Sub

Stop

In my last post I talked about breakpoints. Using the Stop statement is like using a breakpoint, except it's part of the code and will remain there until you remove it.

Option Explicit

Sub UsingStop()

    Debug.Print "Hello"

    Stop

    Debug.Print "Goodbye"

End Sub

When you execute the code above, the code pauses at the line where Stop is. You can then step through the code (F8) or continue execution (F5).

Make sure you remove any Stop statements from your code after you are finished writing or debugging it.

Debug.Assert

Using this is like using a conditional breakpoint. If a certain condition is met, then break (pause code execution).

Option Explicit

Sub Assert()

    Dim num as integer

    num = 1

    Debug.Assert num > 0

End Sub

In the above code num is given the value 1. Debug.Assert will pause execution if the test num > 0 is false.

This is a funny one because it is halting code execution if the test condition evaluates to False, rather than True as you might expect.

? instead of Debug.Print

This one only works in the Immediate Window, not in your code.

To check the value of something you can type debug.print SomeVar and the value is shown in the Immediate Window.

Rather than type debug.print all the time, just use ? e.g. ? SomeVar will print the value of SomeVar

MsgBox

Personally I don't use this much as I don't like my code being interrupted and then having to click a button on a message dialog before execution can continue. I just prefer using debug.print statements. But it is one option for you to see the value of variables.

Rather than using debug.print to show things in the Immediate window, use MsgBox to display things in the Excel application.

Option Explicit

Sub MyMsgBox()

    Dim num as integer

    num = 1

    MsgBox "The value of num is " & num

End Sub

More Tips for Debugging VBA

More Debugging Posts

debugging vba code

Debugging VBA Code

Understanding how to debug your code is vital. Learn what to do when your macros won't work. How to discover where things are going wrong and fix it.

More Excel VBA Posts

Display All Matches from Search in Userform ListBox

Display All Matches from Search in Userform ListBox

Search a range for all partial and full matches of a string, and display matching records (entire rows) in a userform listbox. Sample code and userform.
animating excel charts

Animating Excel Charts

Use animation correctly to enhance the story your data is telling. Don't animate your chart just for some eye candy. Sample code and workbook to download.
dynamic data validation lists in userforms

Dynamic Data Validation Lists in Userforms

Data validation lists using the same source that are dynamically modified to prevent the same choice being made in each list.
show report filter pages for power pivot pivottables

Show Report Filter Pages for Power Pivot PivotTables

PivotTables created from Power Pivot can't use the 'Show Report Filter Pages' option. But this piece of VBA allows you to do just that.
charting real time data in excel

Charting Real Time Data in Excel

Receive data in real time and chart the data as it arrives. Can be used to chart things like stock prices or sensor readings. Sample code and workbook
select multiple items from drop down data validation list

Select Multiple Items from Drop Down (Data Validation) List

Choose multiple items from a data validation (drop down) list and store them all in the same cell. Sample workbook with working VBA.
Excel Calendar (Date Picker) to Use in Worksheets and Userforms

Multi-Language Excel Calendar (Date Picker) for Worksheets and Userforms

Easy to use, highly customizable and multi-language. This date picker is implemented as a userform that is simple to integrate into your workbook.
automating and emailing pivot table reports

Automating and Emailing Pivot Table Reports

Automate the creation and distribution of pivot table reports with some VBA. Send reports to multiple email recipients using Outlook.
search for data with userform

Searching for Data With a User Form

Search a list of records (like a table) using a user form, and then populate the fields of the search form when the record is found.
Checking values in range objects with vba

Checking Values in Range Objects With VBA

Use built in tools or your own code to examine the values contained within Range objects in VBA. Sample code to download.


Category: Excel VBATag: debugging
Previous Post:debugging vba codeDebugging VBA Code
Next Post:Excel ThemesExcel Themes

Reader Interactions

Comments

  1. Donald Parish

    May 13, 2017 at 3:40 am

    Nice, I’ve used VBA for 20+ years, and never used Stop 🙂

    Reply
    • Catalin Bombea

      May 14, 2017 at 1:58 am

      And you should never Stop 🙂
      Cheers,
      Catalin

      Reply
    • Jacques Raubenheimer

      May 18, 2017 at 11:09 am

      Well, people warn against Stop for good reason, as it could cause your code to bomb out later (e.g., when someone else is using your workbook), if you ignore Philip’s injunction: “Make sure you remove any Stop statements from your code after you are finished writing or debugging it.”
      And let’s face it, it’s easy to forget to go back and remove all the stops.
      But there is a middle road, because there are some contexts where Stop is just plain useful.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Current ye@r *

Leave this field empty

Sidebar

More results...

Featured Content

  • 10 Common Excel Mistakes to Avoid
  • Top Excel Functions for Data Analysts
  • Secrets to Building Excel Dashboards in Less Than 15 Minutes
  • Pro Excel Formula Writing Tips
  • Hidden Excel Double-Click Shortcuts
  • Top 10 Intermediate Excel Functions
  • 5 Pro Excel Dashboard Design Tips
  • 5 Excel SUM Function Tricks
  • 239 Excel Keyboard Shortcuts

100 Excel Tips and Tricks eBook

Download Free Tips & Tricks

Subscribe to Our Newsletter

Receive weekly tutorials on Excel, Power Query, Power Pivot, Power BI and More.

We respect your email privacy

Guides and Resources

  • Excel Keyboard Shortcuts
  • Excel Functions
  • Excel Formulas
  • Excel Custom Number Formatting
  • ALT Codes
  • Pivot Tables
  • VLOOKUP
  • VBA
  • Excel Userforms
  • Free Downloads

239 Excel Keyboard Shortcuts

Download Free PDF

Free Webinars

Excel Dashboards Webinar

Watch our free webinars and learn to create Interactive Dashboard Reports in Excel or Power BI

Click Here to Watch Now

mynda treacy microsoft mvpHi, I'm Mynda Treacy and I run MOTH with my husband, Phil. Through our blog, webinars, YouTube channel and courses we hope we can help you learn Excel, Power Pivot and DAX, Power Query, Power BI, and Excel Dashboards.

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk – For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.