Video 3: Declaring Variables, MsgBox And Debug.Print

In this lesson, we’ll talk about declaring variables in our scripts, as well as MsgBox and Debug.Print. Declaring variables is good practice in all of your scripts, because:

  1. To help ensure you don’t have typos throughout your scripts
  2. Ensuring you’re passing proper data types into your variables (i.e. a string into a string variable, a number into an integer variable, etc.)
  3. Limiting the memory usage of your script. If you don’t declare a variable, VBA will allocate the maximum memory size to that variable (as a variant), so it can handle any data type

You can add Option Explicit above your subroutine to enforce that variables are being declared in your code. This is good practice to ensure that you don’t have typos.

Using MsgBox and Debug.Print can help you visual what your code is actually doing. MsgBox will create a prompt on the screen with the value you’re trying to show, but will stop future code from executing until the prompt is cleared.

Debug.Print will return the value to the Immediate Window. You can open the Immediate Window by clicking View > Immediate Window or CTRL +G.

A nice (and sometimes not so nice) feature of MsgBox is that it stops our script from executing until the prompt is cleared. If you need the user to complete a few steps before additional code should run (i.e. a login prompt), then you can have the user clear the prompt after they have completed the task.

Here is a list of the most common used variables.

You can learn more about MsgBox here.

Complete and Continue