0% found this document useful (0 votes)
2 views

Excel_VBA_Introduction_Post_Course_Reference

Excel VBA (Visual Basic for Applications) is a programming language that automates tasks and creates custom functions in Excel. It allows users to write macros for repetitive tasks, manipulate data, and interact with other applications, with examples including displaying message boxes, automating data entry, and looping through ranges. The document also covers decision-making structures, loops, debugging tools, and the Macro Recorder for saving time on repetitive tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Excel_VBA_Introduction_Post_Course_Reference

Excel VBA (Visual Basic for Applications) is a programming language that automates tasks and creates custom functions in Excel. It allows users to write macros for repetitive tasks, manipulate data, and interact with other applications, with examples including displaying message boxes, automating data entry, and looping through ranges. The document also covers decision-making structures, loops, debugging tools, and the Macro Recorder for saving time on repetitive tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Excel VBA Introduction

What is Excel VBA?


Excel VBA (Visual Basic for Applications) is a programming language developed by Microsoft that allows you to automate
tasks and create custom functions in Excel. VBA can be used to write macros, which are sequences of instructions that
Excel can execute to perform repetitive tasks, manipulate data, and interact with other applications.
What is Excel VBA and why should I learn it?

Here are some examples of Excel VBA

Example 1: Displaying a Message Box


A simple example of VBA is displaying a message box.

Open the VBA Editor:


Press Alt + F11 to open the VBA editor.
Insert a new module by clicking Insert > Module.
Write the Code:
Sub ShowMessage()
MsgBox "Hello, World!"
End Sub

Run the Macro:


Press F5 or go back to Excel, press Alt + F8, select ShowMessage, and click Run.
This will display a message box with the text “Hello, World!”.

Example 2: Automating Data Entry


You can use VBA to automate data entry tasks. For instance, you can write a macro to enter a specific value into a cell.

Open the VBA Editor:


Press Alt + F11 to open the VBA editor.
Insert a new module by clicking Insert > Module.
Write the Code:
Sub EnterValue()
Range("A1").Value = "Automated Entry"
End Sub

Run the Macro:


Press F5 or go back to Excel, press Alt + F8, select EnterValue, and click Run.
This will enter the text “Automated Entry” into cell A1.

Example 3: Looping Through a Range


VBA can also be used to loop through a range of cells and perform actions on each cell.

Open the VBA Editor:


Press Alt + F11 to open the VBA editor.
Insert a new module by clicking Insert > Module.
Write the Code:
Sub LoopThroughRange()
Dim cell As Range
For Each cell In Range("A1:A10")
cell.Value = "Processed"
Next cell
End Sub

Run the Macro:


Press F5 or go back to Excel, press Alt + F8, select LoopThroughRange, and click Run.
This will change the value of each cell in the range A1:A10 to “Processed”.

These examples illustrate how VBA can be used to automate tasks.


Macros: A Hidden Time Saver in Excel
Excel VBA Introduction
The Macro Recorder in Excel
The Macro Recorder in Excel is a tool that allows you to record a
sequence of actions and then play them back to automate repetitive
tasks. Here’s how you can use it with examples:

Example 1: Formatting a Range of Cells


Imagine you frequently need to format a range of cells with a specific
style, such as bold text and a yellow background.
Start Recording:
Go to the Developer tab. If you don’t see it, you can enable it from
Excel Options.
Click Record Macro.
Name the Macro:
Give your macro a descriptive name, like FormatCells.
Optionally, assign a shortcut key and choose where to store the macro.
Perform the Actions:
Select the range of cells you want to format.
Apply the desired formatting (e.g., bold text, yellow background).
Stop Recording:
Click Stop Recording on the Developer tab.
Now, whenever you run the FormatCells macro, Excel will automatically
apply the formatting to the selected range.

Example 2: Inserting a Header and Footer


Suppose you need to insert a specific header and footer in multiple worksheets.
Start Recording:
Name the Macro:
Name your macro, such as InsertHeaderFooter.
Perform the Actions:
Go to the Insert tab, click Header & Footer.
Enter the desired header and footer text.
Stop Recording:
Now, you can run the InsertHeaderFooter macro to quickly add the header and footer to any worksheet.

Example 3: Creating a Simple Report


Imagine you need to create a report that involves copying data from one sheet to another and applying some basic
formatting.
Start Recording:
Name the Macro:
Name your macro, such as CreateReport.
Perform the Actions:
Copy the data from the source sheet.
Paste it into the destination sheet.
Apply any necessary formatting, such as bold headers and borders.
Stop Recording:
Now, you can run the CreateReport macro to automate the report creation process.

Viewing and Editing the Macro


You can view and edit the VBA code generated by the Macro Recorder:

Open the VBA Editor:


Press Alt + F11 to open the VBA editor.
Find Your Macro:
In the Project Explorer, find the module where your macro is stored (usually Module1).
Edit the Code:
You can edit the VBA code to refine your macro or add more functionality.
These examples illustrate how the Macro Recorder can save you time by automating repetitive tasks in Excel.
Excel VBA Introduction
Excel VBA Decision code
Let’s dive into the decision-making structures in Excel VBA: IF and SELECT CASE.

IF Statement
The IF statement is used to execute code based on whether a condition is true or false. Here’s a basic example:

Sub CheckValue()
Dim score As Integer
score = 75

If score >= 90 Then


MsgBox "Grade: A"
ElseIf score >= 80 Then
MsgBox "Grade: B"
ElseIf score >= 70 Then
MsgBox "Grade: C"
Else
MsgBox "Grade: F"
End If
End Sub

In this example, the IF statement checks the value of score and displays a message box with the corresponding grade.

SELECT CASE Statement


The SELECT CASE statement is used when you have multiple conditions to check. It’s often cleaner and more readable
than multiple IF...ELSEIF statements. Here’s an example:

Sub CheckDay()
Dim dayOfWeek As String
dayOfWeek = "Wednesday"

Select Case dayOfWeek


Case "Monday"
MsgBox "Start of the work week!"
Case "Wednesday"
MsgBox "Midweek already!"
Case "Friday"
MsgBox "Almost the weekend!"
Case Else
MsgBox "Just another day."
End Select
End Sub

In this example, the SELECT CASE statement checks the value of dayOfWeek and displays a message box with a
corresponding message.

Both structures help control the flow of your VBA code based on different conditions.

How do I sort in Excel VBA?

How to: Excel VBA clear clipboard?

Excel VBA Uppercase, Lowercase and more


Excel VBA Introduction
The DO LOOP
The Do...Loop statement in VBA is used to repeat a block of code while a condition is true or until a condition becomes
true. Here are some examples to help you understand how it works.

Basic Do...Loop Example


This example demonstrates a simple Do...Loop that continues to run while a counter is less than 10:

Sub BasicDoLoop()
counter = 0

Do While counter < 10


counter = counter + 1
Debug.Print counter
Loop
End Sub

In this code, the loop will run as long as counter is less than 10. Each time the loop runs, counter is incremented by 1 and
its value is printed in the Immediate Window.

Do...Loop with If Statement


Now, let’s add an If statement inside the Do...Loop to demonstrate a decision-making process within the loop:

Sub DoLoopWithIf()
counter = 0

Do
counter = counter + 1

If counter Mod 2 = 0 Then


Debug.Print counter & " is even"
Else
Debug.Print counter & " is odd"
End If

Loop While counter < 10


End Sub

In this example, the loop runs while counter is less than 10. Inside the loop, the If statement checks if counter is even or
odd and prints the result.

Do...Loop with Exit Do


Sometimes, you might want to exit the loop before the condition is met. You can use the Exit Do statement for this purpose:

Sub DoLoopWithExit()
counter = 0

Do
counter = counter + 1

If counter = 5 Then
Exit Do
End If

Debug.Print counter
Loop While counter < 10
End Sub

In this code, the loop will exit when counter equals 5, even though the condition to continue looping is counter < 10.
Excel VBA Introduction
More DO LOOP examples
This example demonstrates a Do...Loop that runs a fixed number of times:

Sub SimpleDoLoop()
Do
Debug.Print "Hello, World!"
Loop Until False
End Sub

In this code, the loop will run indefinitely because the condition Until False is never met. To stop it, you would need to
manually interrupt the execution.

Do...Loop with If Statement


Here’s an example of a Do...Loop with an If statement that checks a condition:

Sub DoLoopWithIf()
Do
If Now > #12:00:00 PM# Then
Debug.Print "It's past noon!"
Exit Do
End If
Loop
End Sub

In this example, the loop will keep running until the current time is past noon. Once the condition is met, it prints
a message and exits the loop.

Do...Loop with Exit Do


This example shows how to use Exit Do to break out of the loop:

Sub DoLoopWithExit()
Do
Debug.Print "Running..."
Exit Do
Loop
End Sub

In this code, the loop will run only once because Exit Do is called immediately, breaking out of the loop.

Here’s an example of a Do Until loop in VBA that continues to run until the active cell’s value is an empty string:

Sub DoUntilActiveCellEmpty()
Do Until ActiveCell.Value = ""
' Perform some action
Debug.Print ActiveCell.Value

' Move to the next cell down


ActiveCell.Offset(1, 0).Select
Loop
End Sub

Explanation:
Do Until ActiveCell.Value = “”: The loop will continue to run until the active cell’s value is an empty string.
Debug.Print ActiveCell.Value: This line prints the value of the active cell in the Immediate Window.
ActiveCell.Offset(1, 0).Select: This moves the active cell one row down.
This loop will keep moving down the column, printing each cell’s value, until it encounters an empty cell.
Excel VBA Introduction
The FOR NEXT loop and the FOR EACH loop
Let’s dive into the FOR NEXT and FOR EACH loops in Excel VBA with some examples.
Loop Through Excel Worksheets and Workbooks

FOR NEXT Loop


The FOR NEXT loop is used when you know in advance how many times you want to execute a statement or a block of
statements. Here’s the basic syntax:
For counter = start To end [Step step]
' Statements to execute
Next counter

counter: A variable that stores the current count.


start: The initial value of the counter.
end: The final value of the counter.
step: (Optional) The amount by which the counter is incremented each
time. The default is 1.

Example 1: Simple FOR NEXT Loop


Sub SimpleForNext()
Dim i As Integer
For i = 1 To 5
MsgBox "The value of i is " & i
Next i
End Sub

This loop will display a message box five times, showing the values
from 1 to 5.

Example 2: FOR NEXT Loop with Step


Sub ForNextWithStep()
Dim i As Integer
For i = 1 To 10 Step 2
MsgBox "The value of i is " & i
Next i
End Sub

This loop will display a message box for the values 1, 3, 5, 7, and 9.

FOR EACH Loop


The FOR EACH loop is used to iterate over a collection of objects or an
array. Here’s the basic syntax:

For Each element In group


' Statements to execute
Next element

element: A variable that represents the current element in the collection.


group: The collection or array you want to iterate over.

Example 1: FOR EACH Loop with a Collection


Sub ForEachCollection()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
MsgBox "The name of the worksheet is " & ws.Name
Next ws
End Sub

This loop will display a message box for each worksheet in the workbook, showing the name of each worksheet.
Excel VBA Introduction
Example 2: FOR EACH Loop with an Array
Sub ForEachArray()
Dim arr As Variant
Dim element As Variant
arr = Array(1, 2, 3, 4, 5)
For Each element In arr
MsgBox "The value of the element is " & element
Next element
End Sub

This loop will display a message box for each element in the array,
showing the values 1, 2, 3, 4, and 5.

Debugging Tools
Here are the key debugging tools in Excel VBA:

Breakpoints
Purpose: Halt the execution of your code at a specific line.
How to Use: Click in the left margin next to the line of code where you want to set the breakpoint. A red dot will appear.
When you run the macro, it will stop at this line, allowing you to inspect the state of your program.

Step Into (F8)


Purpose: Execute your code line by line.
How to Use: Press F8 to move through your code one line at a time. This helps you see the effect of each line on your
worksheet and variables.

Step Over (Shift+F8)


Purpose: Execute the current line and move to the next one, skipping over any calls to other procedures.
How to Use: Press Shift+F8 to step over procedures, which is useful when you don’t need to debug the called procedures.

Step Out (Ctrl+Shift+F8)


Purpose: Run the remaining lines of the current procedure and return to the calling procedure.
How to Use: Press Ctrl+Shift+F8 to step out of the current procedure.

Immediate Window
Purpose: Test code snippets and evaluate expressions on the fly.
How to Use: Open the Immediate Window by pressing Ctrl+G.
You can type commands and see their results immediately.

Watch Window
Purpose: Monitor the values of variables and expressions as
your code runs.
Ask questions on our
How to Use: Right-click on a variable and select
“Add Watch” to track its value during execution.
post course learning
Locals Window
support forum
Purpose: Display all local variables and their values.
How to Use: Open the Locals Window from the View menu.
Log in using your email
It updates automatically as you step through your code.
and your post course
Call Stack
Purpose: View the sequence of procedure calls that led to
email when you
the current point in your code.
How to Use: Open the Call Stack window from the Debug
completed the feedback
menu to see the list of active procedures.
These tools can significantly help you understand and fix
issues in your VBA code.

You might also like