Loops in VBA: Optimize Your Programming

This tutorial is essential for understanding how loops in VBA can simplify your tasks in Excel. Loops are fundamental in programming, and understanding their functionality will help you create more efficient programs.

What is a Loop in Programming?

A loop is the cyclical repetition of an activity, limited to a finite number of repetitions. A loop can be interrupted either by reaching the predetermined number of repetitions or by fulfilling a specific condition. For more information on conditionals, check out our tutorial on Conditionals in VBA.
Definition of a Loop in Programming
Figure 1. Definition of a Loop in Programming.

Types of Loops in VBA

In VBA, there are two main structures for implementing loops: For / Next and Do / Loop. Each has unique characteristics that make it suitable for different situations. Below, we will explore both types with practical examples.

For Next Structure

The For Next structure allows you to perform a repetitive action from a starting number (NI) to an ending number (NF). Below is an example of how to structure a For loop:
NI NF Total Repetitions
1 10 10
10 19 10
81 91 10
The number of repetitions must be an integer. The For Next structure is declared as follows:
For Variable = NI To NF Step increment Loop declaration
Repetitive Activity Activity
Next Loop declaration

Example of the For Next Loop in VBA

Next, we will see how to find the last occupied cell in a range using a For Next loop:
Example of For Next Structure
Figure 2. Example of For Next Structure.
Sub Tutorial5a_Loops()
For i = 1 To 10
  If Cells(i + 1, 1) = "" Then
    LastRow = i 
    Exit For
  End If
Next
MsgBox ("Last Row: " & LastRow)
End Sub
In this code, the program checks if the cell is empty, and if so, it stops and displays the last occupied row.

Do Loop Structure

The Do Loop structure does not automatically increment the repetition variable. It offers three modes that allow for more flexible control:

Do Mode

This form allows you to declare the loop and specify the exit condition. It should be used carefully to avoid infinite loops.
Do Loop declaration
Repetitive Activity Activity
Variable=Variable+1 Control of repetition count
Loop Loop declaration

Example of the Do Loop in VBA

The following example shows how to find the last occupied row using a Do Loop:
Example of Do Structure
Figure 3. Example of Do Structure.
Sub Tutorial5b_Loops()
i = 2
Do
  If Cells(i, 1) = "" Then
    LastRow = i - 1
    Exit Do
  End If
  i = i + 1
Loop
MsgBox ("Last Row: " & LastRow)
End Sub

Do While Mode

This mode executes as long as a specified condition is met. Let’s see how to apply it:
Do While Structure
Figure 4. Do While Structure.
Sub Tutorial5c_Loops()
i = 2
Do While Cells(i, 1) <> ""
  'Repetitive Activity
  i = i + 1
Loop
LastRow = i - 1
MsgBox ("Last Row: " & LastRow)
End Sub

Do Until Mode

This mode executes until a specified condition is met. Here’s an example:
Example of Do Until Structure
Figure 5. Example of Do Until Structure.
Sub Tutorial5d_Loops()
i = 2
Do Until Cells(i, 1) = ""
  'Repetitive Activity
  i = i + 1
Loop
LastRow = i - 1
MsgBox ("Last Row: " & LastRow)
End Sub
As you can see, the loop executes until it finds the first empty cell.

Conclusion

With what you've learned in this tutorial, you'll be able to use loop structures in VBA with ease. It is advisable to avoid the Do mode due to the risk of infinite loops. Instead, opt for For Next, Do While, or Do Until for safer and more effective control. Want to know more? Contact us...

Using the If Conditional in VBA (If, ElseIf, Else, End If)

In this tutorial, we will explore the benefits of programming, one of which is the ability for the computer to "make decisions" using conditionals.

What is a Conditional?

A conditional is an evaluation made within the flow of information (one or more variables) that determines whether a specified condition is met. Based on the answer, different actions will be taken.

How to Write a Conditional in VBA?

To write a conditional (If in VBA), we need to evaluate a variable and give instructions on what to do if the condition is met. This evaluation is performed using the If command.

Example of If Conditional in VBA: Movie Tickets

Let's imagine we are creating a system for selling movie tickets, where the ticket price depends on the viewer's age. In this case, we define the following rules:
  • Children aged 12 or younger will receive a "Preferential" ticket.
  • Adults older than 12 will receive a "Regular" ticket.
To implement these rules in VBA, we will use an If conditional structure that evaluates the age entered in cell B2. If the age is less than or equal to 12, "Preferential" will be assigned to cell C2. Otherwise, "Regular" will be assigned. Here’s the corresponding code:

Sub AssignTicket()
    Dim age As Integer
    ' Read age from cell B2
    age = Range("B2").Value

    ' Evaluate the condition
    If age <= 12 Then
        Range("C2") = "Preferential" ' Ticket for children
    Else
        Range("C2") = "Regular" ' Ticket for adults
    End If
End Sub
In this example, if the user enters a value in cell B2 (e.g., 10), the system will evaluate the condition:
  • If 10 <= 12 is true, cell C2 will show "Preferential".
  • If the user enters 15, the system will evaluate 15 <= 12, which is false, and cell C2 will show "Regular".

Nested If Conditionals in VBA

Sometimes, it is necessary to evaluate a second condition after the first evaluation. This is called a "Nested Conditional". The structure will be similar to the following:

Example of Nested If Conditional in VBA

Continuing with the movie ticket example, we could add an additional evaluation. Suppose we want to offer "Preferential" tickets to senior citizens (aged 60 or older) as well. The code might look like this:

Sub AssignCompleteTicket()
    Dim age As Integer
    age = Range("B2").Value

    If age <= 12 Then Range("C2") = "Preferential" ' Ticket for children ElseIf age > 59 Then
        Range("C2") = "Preferential" ' Ticket for seniors
    Else
        Range("C2") = "Regular" ' Ticket for adults
    End If
End Sub

Using Or and And (Logical Operators) in VBA Conditionals

It is also possible to evaluate multiple conditions in a single conditional using the logical operators And and Or.

Examples of Using Or and And in VBA Conditionals

If we want to consider an age range for "Regular" tickets, we can use the And operator:

Sub AssignTicketWithOperators()
    Dim age As Integer
    age = Range("B2").Value

    If age > 12 And age < 60 Then
        Range("C2") = "Regular"
    Else
        Range("C2") = "Preferential"
    End If
End Sub
Similarly, using the Or operator, we can evaluate if a ticket is "Preferential" for anyone under 13 or over 59:

Sub AssignTicketWithOr()
    Dim age As Integer
    age = Range("B2").Value

    If age < 13 Or age > 59 Then
        Range("C2") = "Preferential"
    Else
        Range("C2") = "Regular"
    End If
End Sub

Conclusions

As you have seen, there are various ways to program decision-making instructions in VBA, and each method has its advantages. With practice, you will improve your ability to write more compact and error-free code. Want to know more? Contact us...

Complete Guide to Variables in VBA: Learn to Declare and Use Them

What Are Variables in VBA and Why Are They Used?

Variables are fundamental elements in any programming language, including VBA. They allow you to store and manipulate data, such as numbers, text, and more complex structures. By declaring variables properly, you optimize memory usage and improve the execution speed of your code. Real-Life Analogy: Imagine organizing a wardrobe. If you do it neatly, you can quickly find your clothes and make better use of the space. The same principle applies to variables in programming: by managing them correctly, you optimize their usage and capacity. Proper variable management contributes to the organization and efficiency of code. Proper variable management contributes to the organization and efficiency of code.

What Is Variable Declaration in VBA?

Variable declaration involves instructing the system to reserve a memory space according to the type of variable needed. Although it is not mandatory to declare variables in VBA, doing so prevents slowdowns in the program since VBA won't have to determine the type of variable each time it encounters an undeclared one.

Types of Variables in VBA

Variables in VBA occupy different amounts of memory based on their type. Here are some common types of variables:
Variable Type Name in VBA Memory Size (bytes) Value Range Example
Boolean Boolean 2 True or False Answer = True
Integer Integer 2 -32,768 ↔ 32,767 Cant = 5
Double Precision Double 8 ±1.79769313486232 × 10^308 Pi = 3.14159265
Currency Currency 8 -922,337,203,685,477 ↔ 922,337,203,685,477 Amount = 5.5
String String 1 per character Any text Prod = "Car"
Variant Variant Varies Varies based on data type Total = Pi * Cant
VBA automatically assigns the Variant type to undeclared variables. It is advisable to declare the variable type to optimize memory usage and enhance performance.

Levels of Variables in VBA

In VBA, variables can be public (Public) or private (Private), depending on their accessibility level:
Variable Type Used in
Private A single procedure (routine or function) within the same module
Public All procedures across all modules
Private variables can have the same name in different procedures since they are not shared. In contrast, public variables maintain their value while the macro is running.

How to Declare a Variable in VBA?

To declare a variable, follow these steps:
  1. Open the VBA command editor (you can refer to our first tutorial on macros in Excel).
  2. Use the Dim statement to declare the variable.
Example of Declaration:
Dim pi As Double
In this case, we are reserving space for the variable pi, which will hold a double precision number. Display the Result: To print the value, use MsgBox:
MsgBox(pi)

Tips for Using Variables in VBA

  • To require VBA to always declare variables, use Option Explicit at the beginning of any module. This helps you avoid declaration errors.
  • If you forget to declare a variable, VBA will highlight the error, making it easy to identify and correct.
  • Use the CTRL + Space combination to access a menu of declared variables when typing.

About Variable Names in VBA

Choose descriptive names for your variables, as this facilitates code understanding. Here are some rules to follow:
  • The first character must always be a letter.
  • VBA is case-insensitive; Var and var refer to the same variable.
  • Spaces and certain symbols are not allowed in names.
  • The maximum number of characters for a variable name is 255.
Want to know more? Contact us…  

Ultimate Guide to Using the Macro Recorder in VBA

Welcome to our comprehensive tutorial on using the Macro Recorder in VBA (Visual Basic for Applications). Whether you're an Excel beginner or a seasoned user looking to automate repetitive tasks, the Macro Recorder is an invaluable tool. In this guide, we'll cover everything you need to know about the Macro Recorder, including step-by-step instructions and tips for optimizing your workflows.

What is the Macro Recorder?

The Macro Recorder in VBA allows you to record your actions in Excel and convert them into a VBA macro. This is particularly useful for users who may not be familiar with programming but want to automate tasks. The Macro Recorder captures your keystrokes and mouse clicks, generating the corresponding VBA code.

Why Use the Macro Recorder?

  • Ease of Use: No programming knowledge is required; simply perform the actions you want to automate.
  • Time-Saving: Quickly record repetitive tasks, saving you hours of manual work.
  • Learning Tool: Great for beginners to learn how VBA works by analyzing the recorded code.

Step-by-Step Guide to Using the Macro Recorder

Step 1: Enable the Developer Tab

  1. Open Excel.
  2. Go to File > Options.
  3. In the Excel Options window, select Customize Ribbon.
  4. Check the box next to Developer and click OK.
Activate Developer Tab

Step 2: Start Recording a Macro

  1. Click on the Developer tab in the ribbon.
  2. Click on the Record Macro button.
  3. In the Record Macro dialog box, enter the following:
    • Macro Name: Give your macro a descriptive name (no spaces).
    • Shortcut Key: Assign a shortcut key (optional).
    • Store Macro In: Choose where to save your macro (this workbook, new workbook, or Personal Macro Workbook).
    • Description: Add a brief description of what the macro does (optional).
  4. Click OK to start recording.
Start Record Macro

Step 3: Perform Your Actions

Now that recording has started, perform the actions you want to automate. This could include formatting cells, entering data, or creating charts. Remember, every action you take will be recorded.

Step 4: Stop Recording

  1. Once you’ve completed your tasks, go back to the Developer tab.
  2. Click on Stop Recording.
Stop Recording Button

Step 5: View and Edit the Recorded Macro

  1. Click on Macros in the Developer tab.
  2. Select your macro from the list and click Edit. This will open the VBA editor.
  3. Analyze the code and make any necessary modifications.
Edit macro button Recorded macro code  

Tips for Optimizing Your Macros

  • Keep It Simple: Start with simple tasks to understand how the Macro Recorder works.
  • Edit Recorded Code: Clean up the recorded code for efficiency. The Macro Recorder often includes unnecessary lines.
  • Comment Your Code: Use comments to explain what each part of your code does for future reference.
  • Use Relative References: If you want your macro to work regardless of where the active cell is, enable Use Relative References in the Developer tab before recording.
The Macro Recorder in VBA is a powerful tool for automating tasks in Excel. By following this tutorial, you can quickly create macros that save you time and effort. Experiment with different task. Want to know more? Contact us…

My First Macro

What is an Excel Macro?

If you're an Excel user, you’ve probably faced the need to perform repetitive tasks. Well, macros allow you to automate those repetitive tasks, saving you time and effort when working in Excel. If you want to learn how to use them, you've come to the right place! Macros in Excel are written in a programming language called Visual Basic for Applications, commonly known as VBA. The good news is that you don’t have to be a programming expert to get started in this world. In this first tutorial, we will teach you how to create your first Excel macro. The goal is to display a message that says "Hello World!". Just follow these steps:

Activate the Developer Tab in Excel

First, make sure the “DEVELOPER” tab is active in the ribbon, as it provides options of interest for programmers. To do this, open a new Excel file and check if this tab is available. Developer tab If it’s not, right-click anywhere on the ribbon and select “Customize the Ribbon…”. Then, check the “Developer” box and click “OK”. Activate Developer Tab

Access the VBA Editor

You can access the VBA editor in two ways: a) By pressing the Alt + F11 key combination b) By clicking the “View Code” button in the “DEVELOPER” ribbon. View Code Button

Add a New Module in VBA

Within the VBA environment, right-click on the project folder of your Excel workbook (usually located on the left side of the screen). From the dropdown menu, select Insert > Module. Insert New VBA Module

Write the VBA Program

We will write a program that displays the message “Hello World!”. To do this, we will create a subroutine (Sub) named “MyFirstMacro”. The name of the subroutine should not contain spaces or special characters. The subroutine starts with the word “Sub” and ends with “End Sub”. Inside the subroutine, we will define a variable of type “string” (we’ll talk more about variable types later) to store the text to be displayed. We will name this variable “strGreeting”. The code should look as follows:
Sub MyFirstMacro()
  Dim strGreeting As String

  strGreeting = "Hello World!"

  MsgBox strGreeting
End Sub

My First Macro Code

Run the Program in VBA

You can run the program in various ways: a) By pressing the F5 key b) By clicking the Run Macro button Run Macro Button c) By assigning the macro to a button. To do this, go to the “DEVELOPER” tab and select “Insert/Button”. Then click anywhere on the sheet to place the button. Excel will ask for the name of the macro associated with that button; select “MyFirstMacro” and click OK. Insert Macro Button Assign Macro Button Once you run the macro, the following message should appear: Hello world message   Congratulations! You've written your first macro.

Save the Excel Workbook with Macros Enabled

Make sure to save documents containing macros with the extension “.xlsm” (macro-enabled). Save as macro enabled   Want to know more? Contact us…