Open In App

Debugging VBA Code in Excel

Last Updated: 30 Jan, 2023

A

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

When we use VBA to write code in excel or when we any programming language to write code we may encounter errors that need to be analyzed, checked, and fixed. To overcome this problem most IDEs and programming languages support debugging. Debugging is the process of executing your programming codes step by step and checking which the steps currently compiler is executing, what are their values, and what is their output, we will use debugging. Alternatively, we can also execute each programming statement one by one and check the output, it is almost similar to debugging but it is not convenient and took a lot of time. To learn more in detail about debugging please refer to Software Engineering | Debugging.

Debugging VBA Code

In this example, we will use the following sub-procedure to understand the VBA debugging process.

‘define a sub procedure
Sub fun()

‘declare 3 variables
Dim a, b, i As Integer
a = 0
b = 0

‘iterating
For i = 1 To 5

a = a + 1
b = b + 1

Next

End Sub

VBA-Snippet

 

Now, we will run our VBA macro. For this Click On Run Button In Toolbar.

Running-VBA-Code

 

Once, we run our VBA code, the entire program gets executed at once.

Getting Started with Debugging

To start with debugging process, we need to observe the values of each and every statement before and after execution. We can observe it in Locale Window. To insert the Locals Window in our VBA editor we will go to View > Locals Window.

 Adding-Locals-Window

 

Once, we click on the Locals Window option, it will add locals window at bottom of our VBA Editor.

 Locals-Window

 

This Locals Window will show the currently debugging Expression, its current Value, and the Type of the expression currently getting executed.

Step into Function (F8)

The Step Into function is used to execute the code step by step, it highlights the currently executing step in yellow color. In order to debug the sub-procedure, we need to Place The Cursor Inside VBA Editor > Toolbar > Debug > Step Into (F8).

Note: We can also use a shortcut F8 for calling Step Into function.

Step-into-(F8)

 

Once, we click on Step Into, it will start debugging and we can get the currently executing expression, its value, and type from the local’s window.

Debugging

 

Furthermore, we can use the shortcut for Step Into – F8 and the values of the variables in the local’s window get updated. In case we need to execute the entire program in one go, we need to click on the Run button from the toolbar window.

Debugging

 

Step over Function (Shift + F8)

The Step Over function is used for escaping the sub-procedure. For example, if we have a sub-procedure inside another sub-procedure and we want to escape it while debugging as soon as the cursor reaches that procedure we will call Step Over function, and it will escape that particular procedure.

Note: We can also use a shortcut as Shift + F8 for calling the Step Over function.

Here, we will add one more sub-procedure to our existing procedure. For this, we need to first add a module and define a sub-procedure. To add a module go to VBA Project > Right-Click > Insert > Module.

 Inserting-Module

 

This will insert a module.

Module

 

Now, we will insert a sub-procedure in our inserted module.

‘define a sub-procedure
Sub addition()

‘declare 3 variables
Dim a, b, res As Integer
a = 1
b = 2
res = a + b

End Sub

 Sub-Procedure

 

We will call our addition() sub-procedure in our main procedure.

Calling-Sub-Procedure

 

Now, if we debug our sub-procedure, as soon as the debugger reaches to Call addition step, it will move to our addition procedure.

If we want to avoid our debugger to move to the addition() procedure, we need to call the Step Over(Shift + F8) function when the debugger reaches to Call addition step.

Step out Function (Ctrl + Shift + F8)

The Step Out function is used to move out of the sub-procedure. Let’s understand it with the above example. If we want to escape the call of addition sub-procedure but, by mistake, we have called it by pressing too many Step Into(F8) functions. Then to move out of the sub-procedure we can call Step Out(Ctrl + Shift + F8), it will move out our debugger from the currently executing procedure

Breakpoints (F9)

When we execute our code, the breakpoint is a line where the debugger will pause and wait. For example, if there are thousands of lines of code and we want to keep track of a particular line of code, we can use breakpoint there. To place a breakpoint we need to place our cursor where we want the breakpoint and then press F9 or we can simply click inside the margin area beside the editor line.

Watch Window

As above, we have seen using the Locals Window we can keep track of all the variables. But, If we want to keep track of only one variable we can use Watch Window to keep watch on a single variable. In order to insert the watch window, we need to go to View > Watch Window.

Inserting-Watch-Window

 

Once, we click on the Watch Window option, it will get inserted at the bottom of the VBA editor.

Watch-Window

 

We will be using the following sub-procedure to use the watch window.

‘define a sub procedure
Sub fun()

‘declare 3 variables
Dim a, b, i As Integer
a = 0
b = 0

‘iterating
For i = 1 To 5

a = a + 1
b = b + 1

Next

End Sub

In order to add a variable to the Watch Window, we need to Select Variable > Right-Click > Add Watch.

Add-Watch

 

Once, we click Add Watch option a popup will come we need to click on the OK button.

 Add-Watch-Variable

 

This will inset the variable to the Watch Window.

Variable-Added-To-Watch-Window

 

Now, if we will debug our VBA code, we can watch over the variable in the Watch Window.



A

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

How to Insert and Run VBA Code in Excel?

article_img
In Excel VBA stands for (Visual Basic for Application Code) where we can automate our task with help of codes and codes that will manipulate(like inserting, creating, or deleting a row, column, or graph) the data in a worksheet or workbook. With the help of VBA, we can also automate the task in excel to perform all these tasks we need to insert and run the VBA code properly which we will discuss in this article. Steps to Insert and Run VBA Code in Excel To use the VBA code properly in Excel we need to change the default macro security settings of excel for that we need to follow further steps Step 1: Click on the "File" menu at the left top of the excel tab. Step 2: Select "Options" to get the "Excel Options" window. Step 3: Select "Customized Ribbon" in the "Excel Options" Window and then select the "Developer" check box in the "Main Tabs". Step 4: Then return to the main Excel window to select the "Developer" ribbon and then click on "Macro Security" in the "Code" group. Step 5: Click on "Macro Settings" to select "Disable all macros except digitally signed macros". Now, to insert and run the VBA in Excel so that we can write codes we need to follow further steps: Ste
Read More

How to Run Code from a Module in Excel VBA

article_img
VBA Macro is for developers. In Excel, the macro is a piece of code written in VBA and VBA is Microsoft's programming language, it stands for Visual Basic for Applications. The module is a file with a .bcf extension that stores the code written in the Visual Basic for Applications editor. Let's learn, how to run a code from a module in Excel VBA. Run a code from the Module in Excel VBAStep 1: Go to the Developer Tab, Under the code section you will find Visual Basic. Now click on Visual Basic. Step 2: Microsoft Visual Basic for Applications(VBA) dialogue box appears. In the Menu bar, go to Insert Tab, and click on Module. Step 3: A Module named Module1 is created under the VBA project. Step 4: Write the code you want to run in Microsoft excel. For example, a message box will appear stating "Learning geeks for geeks". Step 5: In the Tools bar. Click on the run button. You can also press F4(Fn + f4) on your keyboard to run the module code. Step 6: The code pauses and the Microsoft VBA editor minimizes and a message box appears in the MS Excel worksheet. Click Ok. The code resumes and the Microsoft VBA editor maximizes again. Scope of Module in VBA The scope of the module in VBA
Read More

A

7 Best ChatGPT Plugins for Debugging and Code Optimization

article_img
ChatGPT's recreation-changing natural language AI has global programming buzzing. Developers are jumping at integrating this powerhouse technology to boost efficiency. One of the tools on hand is tapping ChatGPT plugins for debugging and code optimization. These plugins can feature supply code to pinpoint bugs, brainstorm solutions, streamline code, populate templates, and more. This article explains the top 7 ChatGPT plugin builders need to get to know to step up debugging and optimizing code seriously. By placing these plugins to work studying and enhancing code, builders can vastly save time while accelerating the delivery of top-notch software. With the best ChatGPT plugin for debugging and code optimization to be had nowadays, supercharging debugging and code optimization are now remarkably easy to attain. 7 Best ChatGPT Plugins for Debugging and Code Optimization 1. TabNine2. GitHub Copilot3. Codex4. Eclipse IDE5. Mezmo6. Sentry7. BugsnagCan ChatGPT take a look at the code for bugs?ChatGPT's Potential to Replace CodesThe 7 Best ChatGPT Plugins for Debugging and Code Optimization1. TabNineTabNine is an AI code finishing touch device that makes sensible suggestions for debuggin
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More

Excel VBA Concatenation Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc. Some helpful links to get more insights about concatenate and using VBA in Excel : Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel? In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window.Now select Customize the Ribbon from the pop-down menu.In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now, we need to open the Visual Basic Editor. There are two ways : Go to Developer and directly click on the
Read More

Excel VBA Comparison Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Some helpful links to get more insights about Macros, VBA in Excel : 1. Record Macros in Excel. 2. How to Create a Macro in Excel? In this article, we are going to discuss various comparison operators in Excel VBA. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs in the top of the Excel window.Now select Customize the Ribbon from the pop-down menu. The Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program.Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. Comparison Operators in Excel:S.No.OperatorsDefinition 1<> Not equal operator is
Read More

A

How to Use for Each Loop in Excel VBA?

A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable.groupRequired(Must be mentioned). Name of an object collection or array (except an array of user-defined types).statementOptional (May or may not be mentioned). One or more statements are executed on each item in the group. There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable.Write the For Each Line with the variable and collection references.Add line(s) of code to repeat for each item in the collection.Write the Next line to terminate the loop. The For…Each block is entered if there is at least one element in the group. Upon entering the loop,
Read More

A

How to Use Do While Loop in Excel VBA?

article_img
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the condition at the END of the loop. Syntax 1: Do While condition [statements] [Exit Do] [statements] Loop Syntax 2: Do While [statements] [Exit Do] [statements] Loop conditionImplementing a Do While loop: Follow the below steps to implement a Do-While loop: Step 1: Define a Macro Private Sub Demo_Loop() End Sub Step 2: Define variables j=2 i=1 Step 3: Write Do While Loop. You can write condition at the beginning or at the end Do While i < 5 Step 4: Write statements to be executed in loop msgbox "Table of 2 is : " & (j*i) i=i+1 Step 5: End loop. Now let's take a look at some of the examples. Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True
Read More

How to Use For Next Loop in Excel VBA?

article_img
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [code block to execute] statement 1 statement 2 statement 3 . . statement n Next [counter] Here we can use the counter or any other variable to run them as many times as we need. Example: When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA. We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs. A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement. The flow of the control in for loop:The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.Then the second
Read More
three90RightbarBannerImg