Excel VBA - The Beginner's Guide To Excel VBA Programming
Excel VBA - The Beginner's Guide To Excel VBA Programming
Preface
Welcome to the world of Visual Basic for Applications (VBA)! This eKindle
book is designed to be your companion on a journey of discovery into the
versatile and powerful realm of VBA programming.
Why VBA?
In the pages ahead, you will find a comprehensive guide to understanding and
harnessing the capabilities of VBA. Our aim is to provide you with a
structured and hands-on learning experience. Here's what you can expect:
Foundations of VBA: We will start with the basics, ensuring that even those
who have never written a line of code can follow along. You'll learn about
variables, data types, and fundamental programming concepts.
Real-World Applications: VBA is not just about theory; it's about solving
real-world problems. You will explore how VBA can be used to automate
repetitive tasks, create custom functions, and build user interfaces.
Tips and Best Practices: Along the way, we'll share valuable tips, best
practices, and pitfalls to avoid, based on years of experience in VBA
development.
Advanced Topics: As you progress, we'll delve into more advanced topics
like error handling, working with external data sources, and optimizing your
VBA code for performance.
We're excited to embark on this VBA journey with you. Whether your goal is
to automate tedious tasks, create customized solutions, or simply explore the
world of programming, you've made a great choice by picking up this eKindle
book.
Happy coding!
Disclaimer
The following disclaimer provides important information regarding the
eKindle book titled "Visual Basic for Applications (VBA) Course":
Educational Purpose: This eKindle book is intended to serve as an
educational resource to assist readers in learning about Visual Basic for
Applications (VBA) programming. It is not a substitute for professional
advice or consultation related to specific software development projects or
business needs.
Limited Liability: The author and publisher shall not be held liable for any
damages, losses, or consequences arising from the use or misuse of the
information provided in this eKindle book. Readers are encouraged to seek
professional guidance when making critical decisions or implementing VBA
solutions in real-world situations.
Copyright and Usage: All content within this eKindle book, including text,
code samples, images, and illustrations, is subject to copyright protection.
Readers are permitted to access and use this content for personal educational
purposes only. Any unauthorized distribution, reproduction, or sharing of this
eKindle book's content is prohibited.
Contents
• Chapter 1: Excel VBA Tutorial Author: Umesh M anral
• Chapter 2: Macros
• Chapter 3: VBA Editor
• Chapter 4: VBA MsgBox
• Chapter 5: VBA InputBox
• Chapter 6: VBA Comments
• Chapter 7: VBA Dim
• Chapter 8: VBA Variables
• Chapter 9: VBA Constant
• Chapter 10: VBA Arithmetic Operators
• Chapter 11: VBA Logical Operator
• Chapter 12: VBA Comparison Operator
• Chapter 13: VBA Select Case
• Chapter 14: VBA Loops
• Chapter 15: VBA For Loop
• Chapter 16: VBA For Each Loop
• Chapter 17: VBA Do Until Loop
• Chapter 18: VBA Do While Loop
• Chapter 19: VBA String Operator
• Chapter 20: VBA String Functions
• Chapter 21: VBA LEFT Function
• Chapter 22: VBA Right Function
• Chapter 23: VBA LEN Function
• Chapter 24: VBA TRIM Function
• Chapter 25: VBA MID Function
• Chapter 26: VBA Split Function
• Chapter 27: VBA Instr Function
• Chapter 28: VBA Date Format
• Chapter 29: VBA ARRAY Function
• Chapter 30: VBA Workbooks Open
• Chapter 31: Excel VBA Range
• Chapter 32: VBA Functions
• Chapter 33: VBA Option Explicit
• Chapter 34: VBA Error Handling
• Chapter 35: Excel VBA Objects
• Chapter 36: VBA Events
Chapter 1: Excel VBA Tutorial
VBA (Visual Basic for Applications) is a language that is common to visual
basics that can only work through a host application (Excel, in our case).
VBA can be used in all office versions, right from MS Office 97 to MS Office
2013 and some other latest versions that are available.
What is VBA?
Excel VBA allows you to write instructions for a variety of applications using
English-like statements. Excel VBA is easy to use, as you simply drag and
drop interface controls. Excel can also be enhanced by adjusting its behavior
of it.
Application of VBA
VBA can be used for both personal and business purposes. For personal use,
you can automate routine daily tasks using simple VBA macros.
VBA can be used to create powerful custom programs that draw on Excel’s
power for business use.
VBA Basics
For a starter, it’s very important you know about the basics before starting or
planning on writing any coding. Below are some valuable basics you need
before starting: Variable: Variables are memory locations. For you to work
with VBA, you will need to declare variables.
For Example: Suppose we have (4a+5b), where a= 3 and b=5. The variable
‘a’ could contain the number 3 and the variable ‘b’ could contain the number
5. In this given expression, a and b are the variables.
• TRUE
• FALSE
• NOT: Logical not
• AND: Logical and
• OR: Logical or
• EQV: Logical Equivalence
• If Statements
This Excel VBA training assumes that you are an absolute beginner to VBA,
but it is beneficial to know the basics of Excel and how the functions in Excel
work to increase your learning speed and understanding. you should install
MS Office, and mainly MS Excel on your computer system.
Audience
Our VBA tutorial is designed for beginners to help them understand the basics
of VBA. This tutorial will provide enough knowledge of VBA from which
you can take yourself to a higher level of expertise.
Chapter 2: Macros
Author: Umesh M anral
What is Macros?
If you spend all day creating reports in Microsoft Excel, you know the power
of this program; however, if you haven’t yet used macros, you don’t know half
of it.
Macros simplify the repetitive keystrokes that you use in Excel to create and
edit spreadsheets, which speeds up your production and reduces the time you
have to spend staring at an electronic spreadsheet every day by reducing the
number of keystrokes required to complete common commands.
Macros Basics
If you wish to run macros, you must enable macros and only run macros that
you believe to be from a reliable source. Macros have many benefits for those
who use them. They eliminate the risk of human error that increases with
repetitive keystrokes and tasks.
Step 2: Navigate to Customize Ribbon tab and the Developer checkbox by the
left side of the window.
Step 3: Click on the OK button.
Author: Umesh M anral Step 4: Create an Excel Workbook in a drive “D” or any other
drive and save it with name “xyz” or whatever name you want.
Step 5: Open the file which you created or if it is already opened then no
need to re-open it.
Step 9: The Record Macro dialogue box will appear on the screen. Give your
macro a name and assign the shortcut which will activate the macro then click
the OK button. Author: Umesh M anral
Step 10: Click on the Cell A1. Type here “This is my first macro”. Step 11:
Click on the “Home” and fill the yellow color in cell A1.
After completing above the steps, you will get your output in the workbook as
shown in the below screenshot:
To finish the macro, click on the Stop Recording macro option as shown in the
below screenshot.
Step 12: Click on the Developer >> Visual Basic >> Module1 then another
window will appear. You will find the recorded macro script in the module.
Author: Umesh M anral
Step 13: Save the file with extention “Excel Macro-Enabled Workbook
(.xlsm)“ or “Excel Binary Workbook (.xlsb)“.
Step 14: Click on the Macros button then another window will appear. Select
that macro name Macro1and click on the Run button.
The recorded macro will help you to perform your daily task whenever you
require. Author: Umesh M anral
Chapter 3: VBA Editor
The Visual Basic Editor, also known as VBA Editor, VB Editor, or VBE
Editor, is a separate application that first needs to be familiarized with to
work with VBA in Excel. It is part of Excel and appears whenever you open
an Excel workbook. By default, it is hidden and must be activated to view it.
Excel VBA is a powerful software tool that allows the automation of Excel
tasks. It can be used to automate repetitive tasks as well as more complex
applications.
Having access to the VBA editor means that you can edit your own VBA code
or check prerecorded macros.
Here are (3) Good Ways to get the Code in the VBA Editor
1. When you record a Macro, it generates a new module in the VBA Editor
automatically and inserts the code in that module.
2. VBA code can be written manually in VBA Editor.
3. Code can be copied from some other workbook or some other source as
you can paste it into the VBA Editor.
This is the easiest and fastest method that almost everybody prefers using
when accessing the VBA Editor. For you to do this, hold the ALT + F11 to
open the Editor window. This shortcut acts as a toggle so that when you use it
again, it will return you to the Excel application (without closing the VB
Editor).
NOTE: The shortcut for the Mac version is Opt + F11, or Fn + Opt + F11.
Using the Developer Tab
To open the Editor, let’s check out the following steps:
Step 1: Firstly, open the Excel window on your device.
Step 2: Click on the Options button.
Author: Umesh M anral
Step 5: Direct your cursor to the OK option and click on the OK button to
make the Developer appear on the main window.
Step 6: The Developer Tab will appear in the Ribbon at the top of the
window.
Step 7: Select the Visual Basic option or click Alt+F11 on your keyboard.
Step 8: The VBA window will appear. You can pay attention to the below
image. Author: Umesh M anral
Step 4: it will open the VBA Editor and also open the code window to that
worksheet object. Author: Umesh M anral
This method not only opens the VB Editor but also opens the code window for
that worksheet object, which is useful when you want to write code that only
applies to a particular worksheet. It is usually the case when worksheet events
are involved.
Syntax
1. Prompt
2. Buttons
3. Title
An Optional Parameter. In the message dialog box, you can specify the
message title you want, which is displayed in the title bar of the MsgBox. If
you don’t provide anything, it will display the application’s name.
4. Helpfile
An Optional Parameter. This is a String expression that identifies the Help file
to use for providing context-sensitive help for the dialog box.
5. Context
An Optional Parameter. It is a numeric expression that identifies the Help
context number assigned to the appropriate Help topic.
Note: All the arguments in square brackets are optional. Only the ‘prompt’
argument is mandatory.
Before we go into the analysis of the VBA code and how the MsgBox looks,
here is a table that lists all the different button constants you can use.
Author: Umesh M anral
The above values are logically divided into four groups: The first group (0 to
5) specifies the buttons to be shown in the message box. the second group (16,
32, 48, 64) describes the look of the icon to be displayed; the third group (0,
256, 512, 768) specifies which button should be the default; and the fourth
group (0, 4096) defines the message box’s modality.
Return Value
The MsgBox function can return one of the following values which can be
used to specify the button the user has clicked in the message box.
Author: Umesh M anral
Examples:
If we want to display a message box with Yes, No, and Cancel buttons, you
can make the coding as shown in the below code.
Executes the above function by clicking on the run button on the VBA window.
It displays a “Hello World” message box within a message box and an
“Yes”,”No”, and “Cancel” button.
After clicking the ‘No’ button, the value of the button (7) is stored as an
integer and displayed as a message box to the user, as shown in the following
image. This value can be used to determine which button was clicked by the
user.
Syntax
InputBox (prompt, title, default, xpos, ypos, helpfile, context). All are
optional parameter except prompt.
Context: It is a number expression that helps to find the Help context number.
The Help author will assign this number to a relevant help subject. The
presence of the helpfile is required for providing background information.
How to Create InputBox?
Here are the steps you need to take in VBA to make an input box:
Step 1: Create a new module in the Visual Basic Editor.
Step 2: Select the newly added module by double-clicking it, and then enter
the macro’s name “InputBox_Example”.
Step 3: Type the word “InputBox,” and the syntax of the InputBox will show
up.
Step 4: Change the Prompt to “Prompt Name,” the Title to “Information,” and
the Default to “Enter Here.”
Example:
The area of a rectangle can be determined by having the user enter values into
two input boxes at runtime (one for length and one for width).
Step 1: Use the function name and click Enter to carry out the same as in the
picture below.
Step 2: First
input box (Enter x Value) appears upon execution. Enter a value.
Author: Umesh M anral
Step 3: The width input box appears after the first value has been entered.
Step 4: When you have typed in the second number, hit the OK button. The
region appears as in the screenshot below.
Author:
Umesh M anral
Chapter 6: VBA Comments
VBA Comments. Comments are lines of code skipped over when the code is
run. In the coding, these are shown as green text. Descriptions of the code are
provided in the comments. A comment is any remark in the VBA code after an
apostrophe. Knowing the proper usage of comments is crucial when working
with large and complex code. Comments assist us in understanding which
section of the code accomplishes what. It is beneficial for the sake of
progress.
Step 5: Click on Comment Block and move it to the menu bar. It will simulate
a menu button in appearance.
Step 6: Select Uncomment Block and add it to your ToolbarToolbar by
clicking and dragging it there. It’ll have the appearance of a menu button.
Author: Umesh M anral
Step 10: Follow steps 7–9 again for the Uncomment Block, this time by right-
clicking on it and entering “&” in the Name field. In the drop-down menu that
appears, choose both the Image and the Text options.
Step 11: A shortcut for commenting and uncommenting has been made in the
VBA code editor. The keyboard shortcut for commenting a line is Alt + C,
while the one for uncommenting it is Atl + U.
Just type the Rem keyword at the beginning of a line to add a comment to that
line. No quotation marks or apostrophes are required.
Here are some rem keyword limitations:
Put at least one space before the Rem keyword at the beginning of your
comment. Rem must always be the first word of a line and cannot be used
between lines to comment on the entire line.
Syntax
Dim [Insert Variable Name] as [Insert Variable Type]
The four varieties of Dim statements are as follows:
1. Basic Variables
It keeps only one value. It can be a Long String, Date, Double, or Currency.
2. Variant
VBA determines the data type at runtime. Even if it is best to avoid them,
there are times when adaptation is necessary.
3. Object
It is a type of variable with several associated procedures (called “subs” or
“functions”) and properties (values).
The Three Types of Objects are:
4. Array
Array is a group of objects or variables.
1. Procedural Level
2. Module Level
In the declaration section of a code module, variables at this level are created
with the Dim or Private statement. These variables are private to the module
and accessible only from its processes. However, the external module has no
access to these variables. The most common usages of Private and Dim are at
the module and procedure levels, respectively.
3. Project Level
It is where you will put all of your public variables and where you should
only use public statements in your general declarations. The public keyword
allows us to declare these variables at the very start of the default module. It
can be used for any module and will be deleted when the workbook is closed.
Example:
An integer is a type we employ when declaring the data itself. Take three
integer variables that you have declared using the Dim keyword.
Step 1: Declare the integer variables x, y, and z.
Step 2: The MsgBox function helps show the value of the z variable.
Author: Umesh M anral Step 3: Hit the Run button, and the code produces the
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size
and layout of the variable’s memory; the range of the values that can be stored
within that memory; and the set of operations that can be applied to the
variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive.
For example, you can’t write a variable name that starts from a
number”1_helloworld”, the appropriate way to write is, “helloworld1”. It’s
not clear that a variable name cannot start with a number.
3. You cannot start with special characters like @, &, #, (.), (!) or cannot have
spaces because all these are not allowed.
4. Keyboards are not considered variable names.
It is important you declare the variables before using them by assigning names
and data types in VBA.
There are two main variable declarations in VBA: implicitly or explicitly.
Implicitly: let’s check the below example to know more about variables
declared implicitly. Author: Umesh M anral Explicitly: let’s check the below example
to know more about variables declared explicitly.
if Option Explicit is specified, the code will interrupt because it is missing
the required Dim statements for LngVariable and StrVariable.
Step 2: After clicking, the Record Macro will appear. You can enter the
macro name such as Macro1.
Step 3: Click the OK button
Author: Umesh M anral
Step 4: At the top of your screen, direct your cursor to Stop Recording and
click on it.
Step 5: Open the macro editor and insert the code for the variable in Macro1.
Step 6: Execute the code for Macro1, and you will get the results below in
your sheet.
Let’s look at a simple VBA way of declaring variables. We will explain the
four types of variables, such as string, Integer, Long, and Date.
Step 1: Before, we inserted a Command Button in the excel sheet.
Step 2: Go to the Macros and select a created Macro, click on the “Step Into
“button and It opens the code window as shown in the below screenshot.
Step 3: Write down your code to declare the variables.
Author: Umesh M anral
Step 4: After the process, click on the Save button and save your file or press
(Ctrl S). 1. Click on the Excel icon to return the Excel sheet and you will get
the Design Mode “ON” as shown in the below screenshot.
2. Turn off the Design Mode before clicking on the command button and then
click on the Command button. It will show the variables as an output for the
range we declared in the code.
Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal. There are also
enumeration constants as well The constants are treated just like regular
variables except that their Values cannot be modified after their definition.
Example:
In VBA you are allowed to declare constants as values can be defined only
once and cannot be modified. Let’s start with a constant declaration
Syntax
In VBA, we must assign a value to the declared constants, since if we attempt
to modify the value of the constant, an error is thrown.
Example:
2. You will get the code and enter the following code.
Step 5: In the screenshot below, you will see that button named
CommandButton1 has been created.
Division: This operator is used to divide numbers i.e, you can divide the
numerator by the denominator.
Example:
Assume variable A holds 8 and variable B holds 2, then
Bit-Shift Operation
Bit shifting is a process on all of the bits of a binary value that shifts them by a
known number of places to the left or right, which is often used when the
operand is treated as a sequence of bits rather than a whole. In other words,
the operand is treated as individual bits that stand for something, and not as a
value.
The pattern can be shifted into the right with >> operator or into the left with
<< operator. The data type of the pattern operand is Byte, SByte, Short,
UShort, Integer, UInteger, Long, or ULong.
Arithmetic shifts are not circular, meaning the bits shifted off one end of the
result are not redefined at the other end. Also, the arithmetic shift moves all
the digits in the binary number along to the right. The vacated positions of the
bit by a shift are set as follows:
Example:
In the below example, shifts the Integer value left or right both.
Bitwise Operations
Step 1: First add a Button to the excel sheet as we have shown that before.
The Main Excel VBA Logical Operators are AND, OR, and NOT.
The AND Operator also Accepts Multiple Arguments and Returns True or
False. The And Operator Requires That all of the Individual Elements be True
Before the Expression is Correctly Completed. The AND Operator Will
Return False if Three Expressions are Joined Together, and two of Them
Return True, but one Returns False.
Example:
The first Expression Returns True, and the Second Returns False. When you
Combine the two, the Whole Statement Returns False. We can Have Twenty
true Expressions, but if one of Them is False, Then the Entire Expression
Would be False.
The OR Operator Allows you to Test Multiple Conditions, but What you're
Really Trying to Determine is Whether the Combined Statement is True or
False. If you Have Multiple Conditions, and one of Them Returns true, Then
the Expression in its Entirety will Return True.
Example:
The First Expression in the Code Below is True, While the Second
Expression is False, and if I Combine the Two, the Whole Expression is True
Because at Least one of the Expressions was True by Itself. If the First
Expression had Resulted in False, the Entire Expression Would have also
Resulted in False.
Using the Not Operator, you can Return the Opposite of What Your Expression
Would Have Returned Without the Not Operator, either as a Stand-Alone
Basis or in Conjunction with the Or and “And Operators” Discussed Earlier.
In the Example Below, I Give the Regular Expression on the First line and
Give the Expression Using the Not Operator on the Following Line.
Author: Umesh M anral
Author: Umesh M anral
Chapter 12: VBA Comparison Operator
VBA Comparison operators can be used to compare numbers or strings and
perform evaluations. Expressions using comparison operators do not return a
number value, as do arithmetic expressions. Comparison expressions return
either 1, which is true, or 0, which is false. Some comparison operators
include equal to, less than, greater than, and not equal to.
In VBA, compression operators include less than (<), greater than (>), equal
to (=), less than equal to (<=), greater than equal to (>=), and not equal to
(<>).
The following examples show the comparison operators defined for VBA
This operator sign can be used to find out whether one thing is equal to
another. The result will be TRUE or FALSE. If one thing is greater than
another, then TRUE is produced, and False is produced.
Example:
This symbol determines whether one number is greater than the other, and is
also a logical VBA operator with a return of either TRUE or FALSE.
Example:
4. Greater Than Equal to (> =)
The greater than equal to operator is used to check if the first value is greater
than or equal to the second value and returns True or False.
Author: Umesh M anral
This sign checks whether one number is less than the other number. It is also a
logical operator in VBA, where the result is either TRUE or FALSE.
Example:
The VBA Select Case Statement is also known as Switch Case in Many other
Languages Such as:
• Java
•C+
• C#
• and JavaScript
Note that, if a Match is not Found in any of the Case Statements, the
Conditions will Surely be False. In This kind Case, the Code of the Case Else
Statement is Executed.
Analysis
• In the FIRST part, it’s Important you Specify the “Test Expression” on
Which all the
Conditions get Tested.
• After That, in the SECOND Part, you Need to Specify the Case to Test (That
Means
Condition to Test).
• Now in the THIRD part, you Need to Write Another case Where you Need
to test if
the Condition in the Second Part is not TRUE.
• In the end, in the FOURTH part, you Need to Specify an Outcome that
Should Come
When Both the Above Cases are not TRUE.
Below are Some Examples that Explain the Execution of the Select Case
Statement. Example 1:
We Will Find a Condition Where i = True with the Help of the Select Case
Statement.
Author: Umesh M anral
If the condition is true, then the “Case True” block of the code will be
executed. Otherwise, the “Case False” block of the code will be executed.
In the Above Example, we Used the InputBox Function to get Values from the
User. Now Execute the Code and enter the Values of i.
Case 1: If the User Enter the Values of i and Press the OK Button.
You can see the Values of i is
“Two”. After Clicking on the OK Button, it will Show the Following Output.
Example 3:
In This Example, we Check the Multiple Conditions Within a Single Case
with the Help of the Select Case Statement.
This Code Will Check the Weather a Number is Even or odd When a User
Enters any Number From 1 to 10.
If you Take a Look, you will see That We Used (” “) to Compare Multiple
Conditions Within a Single Case Statement.
Author: Umesh M anral
Execute the Code by Using the Run Button and Enter any Number Start 1 to
Loops are used to repeat a set of statements as many times as necessary until a
given condition is met. A loop statement allows you to repeatedly execute a
statement or group of statements.
First, you must understand how to use loops to get the most out of Excel and
VBA. Following is the general form of a loop statement in VBA.
For Loop
It executed a sequence of statements and compressed the code that controls the
loop variable.
For loop, a variable runs through a sequence of values within a specified
range on each cycle. Then, for each value in VBA, the code is executed inside
the loop.
Author: Umesh M anral
The For loop above sets the variable i to the numbers 1, 2, 3,…, 10 and then
runs the VBA code inside the loop for each of these numbers. The loop thus
adds each element of the Integer i to the variable.
Do While Loop
This loop checks for a condition and executes the loop body while that
condition is True. Author: Umesh M anral
The do…While loop statement
Do Until Loop
This loop is the opposite of the Do While loop, in Do Until, the rules for
ending the loop are specified. Therefore, if the condition is FALSE, the
statement inside the loop will be executed, but if the condition is TRUE, the
loop will be closed.
The Do…Until loop statement
Loop control statements change execution from its normal sequence so that all
remaining statements in the loop are not executed when execution leaves a
scope. VBA supports the following control statements:
2. Exit do Statement
Exit Do is used when you wish to come out of the Do Loop after meeting
specific criteria. Author: Umesh M anral
Chapter 15: VBA For Loop
As we’ve mentioned already, loops are used to repeat a set of statements as
many times as necessary until a given condition is met. They help to refract
your code, reducing the number of specifically coded actions that must be
performed to improve the speed and efficiency of your applications.
Flow Diagram
1. If you want to have, you’re For loop end before the final value is reached,
you will need to add an Exit For a statement to your code, which will exit the
loop and continue on to the next line of code outside the loop if your code
continues. As an example, you could stop the loop when you push a button.
2. A VBA For Loop can be used to cycle through several numerical values in
sequence simply with a For Next Loop, while a more complex VBA For Each
Loop can cycle through more complex objects (such as workbooks in your
spreadsheet) in sequence.
3. VBA For Loops can be embedded within other logical statements, such as
an If or Do While statement, so you can build more complex decision-making
into your code. Author: Umesh M anral
Syntax
The For loop executes a block of code a specific number of times.
Example:
Explanation:
4. The next statement is increment the counter by the step value and returns to
the for the statement, which repeats the code if the counter value does not
exceed the “End_value” of
10.
5. Assuming the counter is equal to the End_value, the loop will be continued,
or it will be stopped only when the End_value exceeds.
Nested For Next Loops
A nested loop is a loop that is encased in another and is commonly used for
working in two dimensions, such as restarted printing stars in rows and
columns, as shown below. You can use the nested for loop to get the more
complex automation done in excel. There would be a “For Next” loop within
a “For Next” loop.
For example: Suppose you want to read all the worksheets name in all open
workbooks in your system.
Exit For Statement
When we need to exit the For loop based on a set of criteria, we use an Exit
For statement. When Exit For is executed, the control jumps to the next
statement immediately after the For loop.
Flow Diagram
Example:
In the following example, Exit For is used. If the Counter’s value reaches 4,
the For Loop is exited, and the control moves to the next statement
immediately after the For Loop.
Author: Umesh M anral
Chapter 16: VBA For Each Loop
A For Each loop is used to execute a statement or a group of statements for
each element in an array or collection.
A For Each loop is similar to a “For” Loop, but the loop is run for each
element in an array or collection. In this type of loop, the step counter will be
absent because it is mostly used with arrays or File system objects in order to
recursively operate.
Syntax
In VBA, you can build a cycle through a set of collections using the “For
Each” loop. Here are some examples of collections using the For Each loop
in the excel VBA, such as:
With the “For Each” loop (also known as the “For Each -Next” loop), you do
not need to know how many items exist in a collection as the “For Each” loop
will automatically go through each object and perform the specified action.
For example, if you wanted to read all the worksheets name in a workbook,
the code would be the same whether the workbook had 1 or 20 worksheets.
Author: Umesh M anral Example:
Suppose you have a workbook where you want to protect all the worksheets.
Such as:
In the code above, the variable ‘sht’ is denoted as a worksheet object, which
tells VBA that ‘sht’ should be interpreted as a worksheet object in the code.
Use the Statement ‘For Each’ to browse through each ws (which is a
worksheet object) in the collection of all the worksheets in the active
workbook.
Unlike other loops in which we have tried to protect all the worksheets in a
workbook, this one does not need to be concerned about how many
worksheets are in the workbook, as we don’t need to count them to run the
loop.
For Each loop ensures that all objects are analyzed one by one.
Now, to go Through all the Open Workbooks and Read all the
Workbooks Name
It can be useful to save all of the workbooks at once when working with
multiple workbooks at the same time.
The code below can do this for us:
Example:
Executes the above code, you will get the following output, such as:
Author: Umesh M anral
Chapter 17: VBA Do Until Loop
The Do Until loop is a useful Excel VBA function that repeats a series of
actions until the statement is FALSE. When the statement is FALSE, we want
the loop to end and the loop to naturally end.
Also, the condition is specified at the end of the loop, then the Do until Loops
condition is checked with each loop iteration, and a decision is made as to
whether the loop is true or false.
‘Do Until’ loops are very much like the ‘Do While’ loops.
Flow Diagram
Author: Umesh M anral
Example:
Suppose you want to show a MsgBox with the first ten integers using VBA’s
Do Until loop.
For that, you must run the loop until the next number is less or equal to 10. A
loop would be stopped when the number exceeded 10.
Here is the VBA code to run this loop and display the result in a message box.
The above loop continues to work until the value of ‘i’ becomes 11. As soon
as it becomes 11, the loop ends (as the ‘Until’ condition becomes True).
Syntax
Author: Umesh M anral
Flow Diagram
Example:
The following example uses the Do…Until loop to check the condition at the
end of the loop. Even if the condition is True, all statements within the loop
are executed at least once.
After executing the code, you will get the following output in a message box.
You can exit the loop by using the ‘Exit Do’ statement: as soon as the code
executes the ‘Exit Do’ line, it exits the Do Until loop and passes control to the
next line immediately after. For example, you want to show a MsgBox with
the first 5 numbers only, then you can exit the loop as soon as the first 5
numbers are entered, as shown in the code below
In the above code, as soon as the value of ‘i’ becomes 5, Exit Do statment is
executed and the loop ends.
Author: Umesh M anral
Chapter 18: VBA Do While Loop
VBA Do while is a loop in which you have to specify a condition, and that
condition must be true for the loop to run. In other words, it first checks
whether the condition you’ve specified is true, and if it is true, it runs the
loop, and if it is false, it does nothing.
It tests the condition in each iteration and then executes the statement. For
example, if you need to add worksheets to Excel, but the total count of the
worksheets is 12 or lower. In this case, you can write the code using the do-
while loop.
NOTE: “The Do … Loop While Statements” check the condition at the end of
the Loop. We have two types of syntax in the Do while loop. So, let’s check
on the two types:
Syntax 1
Author: Umesh M anral
Syntax 2 Do… While Loop Statement
There is an alternate Syntax for Do…while loop. The code block is executed
first and then the while condition is checked.
Flow Diagram
Example 1:
It tests for the condition in each iteration and then executes the statement. For
example, suppose you want to show a MesgBox with “i” Count numbers in
Excel when the total numbers of the “i” Count is 10. In this case, you can
write the code using the do-while loop.
Below is the VBA code that will run this Do While loop and then show the
result in a message box.
Author: Umesh M anral The stated loop continues to work until the value of ‘i’
becomes 10. Immediately the loop becomes 11, the loop ends (as the While
condition becomes False).
Example 2:
we will use Do…while loop to check the condition at the end of the loop in
this example. The statements inside the loop should execute at least once,
even if the condition is False.
After the execution of the code, you will get the following output.
For example, you can concatenate the value of “Hello” and “World” in a
single string.
Alphabets
Str1 = “AnyText”
Numbers
Str2 = “17”
Special Characters
Str3 = “!@#$”
String Operator in VBA
str1 = “Hello”
str2 = “World”
For Example, strValue = str1 & ” ” & str2
Output: Hello World
Example:
Step 1: Add a Button to the Excel Sheet as we Have shown in the Previous
Article. 1. Change the Name Property Such as cmdBtnConatenate.
Several string functions in VBA let the user change the characters in a string
and work with text data in the code. Here are the top six string functions that
we frequently utilise while dealing with string information in our daily lives:
Syntax
Len (String)
Program: Find out how long the string “Hello World” is by using VBA Macro.
Output
Hit the F5 key to execute the code and get the result. You will get the MsgBox
in your Excel sheet showing output 11.
Syntax
Program: Write a VBA macro that uses the LEFT function to get “Robin
Simon” as the first name from the string.
Author: Umesh M anral
Output
Press the F5 key to execute the code and get the result.
Values can be taken from the right side of the string, similar to the left side.
Syntax
RIGHT (String, Length)
Program: Write a VBA macro that uses the RIGHT function to get “Robin
Simon” as the first name from the string.
Output
Author: Umesh M anral
Tap the F5 key to run the code and get the result.
Syntax
MID (String, Start As Long, [Length])
Program: Write a VBA programme to get the characters in the middle of the
string.
Output
Enter the F5 key to run the code and obtain the result.
The TRIM function in VBA helps clean up data. It will eliminate any space
characters that don’t belong in the string. This function is easy to use. It takes
as a parameter a string value that you want to trim.
Syntax
TRIM (String)
Program: Write a VBA programme with the MID function to remove the extra
spaces from the string “Hello, Do you love VBA?”
Output
Hit the F5 key to execute the code and obtain the result.
The VBA Instr String function can help you find where a specific character is
in the string you give it.
Syntax
The VBA Left function takes a string and gives back a string-based result. If
the string argument given to this function is Null, it will return Null. As its
name suggests, the VBA Left function only takes the characters on the left side
of the String. When the LEFT and the InStr function are used, we can find the
space in VBA. It makes it easy for the user to tell which word is in the given
String.
Syntax
Left (String, Length)
Parameter
String (required): The String argument denotes the length of the String we
want to extract. Length (required): It is the number of characters from the left
portion of the specified String you want to get.
Example:
Here are the steps for writing a VBA macro to use the VBA Left function to
get the first name from the given String:
Step 1: Open the tab for the VBA developer. Open the Excel worksheet, click
on the ribbon tab, the developer window, the visual basic editor, or just press
Alt+F11.
Step 2: You will see the VB Editor window. Next, you need to do a module.
Click on Insert on the ribbon, then click on Module.
Author: Umesh M anral
Step 3: You’ll see that VBA adds a new window for the Module. The
programme’s first step is to declare the variables and then to name your
macro.
Step 4: Now add the LEFT function. We will put the String in the arguments
and 5 in the length argument because we want to get the first five characters
from the left side of the String. Put the value of fetch into our variable, and
then use MsgBox to return the variable.
Output
Either click Run or press the F5 key to run your macro. It will cause VBA to
launch a MsgBox showing the first five characters of your String, starting from
the left.
The VBA RIGHT function takes a string and gives back a string-based result.
If the string argument given to this function is Null, it will return Null. As its
name suggests, the VBA RIGHT function takes only the rightmost characters
from the String. The space can be found when the RIGHT function is used
with the InStr function.
It makes it easy for the user to tell which word is in the given String. The
worksheet also has the RIGHT formula. The VBA RIGHT function can only
be accessed through the worksheet function class. So, VBA also has the built-
in RIGHT function.
Syntax
RIGHT (String, Length)
Parameter
String (required): The length of the String to be extracted is represented by the
String argument.
Length (required): The length argument tells you the number of characters
from the right portion of the String you want to get.
Example:
Find the last name from the string “Hello World”.
The VBA RIGHT function is one of the built-in functions frequently used by
Excel users to retrieve data from the right side of a String or user-supplied
value.
Here are the steps for writing a VBA macro to use the VBA RIGHT function
to get the first name from the given String:
Step 1: Go to File > New > VBA Developer. Go to the Excel worksheet,
click on the ribbon tab, then on the developer window and visual basic editor,
or press Alt+F11.
Step 2: You will see the VB Editor window. The following measure is to do
a module. Select Module from the Insert menu in the ribbon.
Author: Umesh M anral
Step 3: You will see that VBA adds a new window for the Module. Initiate
the programme by declaring the variable and introducing your macro name.
Step 4: After that, we’ll add the RIGHT function. In the arguments, we will
pass the String. In the length argument, we will give 5 since we want to get the
first five characters from the right segment of the String.
Step 5: Put the obtained value in the variable, and then use MsgBox to return
the variable.
Output
Either click Run or press the F5 key to run your macro. You’ll see that VBA
launches a MsgBox showing the first five characters of your String from the
right.
People often confuse the Len function with the Excel worksheet function.
Since it is a built-in function for both worksheet and VBA, it has the same
syntax, arguments, and output (both return the length of a string). The LEN
function is available in the Microsoft Visual Basic Editor as a VBA function
that can be useful in a macro.
Syntax
Len (Expression)
Parameters
Expression (required)- This parameter is either a string or a variable whose
length you want to figure out.
Return
The Len function in VBA returns the number of characters in the supplied
String if the Expression is of String or variant data type or the number of bytes
needed to keep the variable if the Expression is of integer, long, single, or
double data type.
Example:
Obtain the length of the string “Hello World”.
The LEN string function is the most popular in VBA. It instantly gives back
the number of characters in the String or the value specified. This way, it
assists users across a range of logical frameworks.
Step 1: Open up your Excel file. You can open the Visual Basic window by
clicking on Developer Window > Visual Basic Editor or pressing Alt + F11.
Step 2: You will see the VB Editor window. Next, you need to build a
module. Click on Insert on the ribbon, then click on the Module.
Author: Umesh M anral
Step 3: A module will be added. Our macro will be explicitly written in this
module window. Initiate the programme by giving the programme’s name and
then declaring the variable.
Step 4: Calculate the String length using the VBA LEN function. It will ask
you for the Expression later in the function. Next, pass the String (“Hello
World”).
Next, we will put the obtained value in the variable and use MsgBox to show
the function’s output.
Output
Either click Run or press the F5 key to run your macro. You will get the
It will eliminate all the extra areas between your String’s characters. So, in
Excel, we use the TRIM function to eliminate “leading spaces, trailing spaces,
and in-between spaces” in regular Worksheet functions. There is also a TRIM
function in VBA. It works the same way as the Excel function, with a tiny
difference.
The TRIM function in VBA helps to get rid of any extra spaces in your data.
The syntax for both VBA Trim and Worksheet Trim is the same. It can only
eliminate spaces at the start and last of a word. We can trim a lot of data at
once without looking at how many extra areas are in the cells. There is little
chance that any extra space will be saved.
Syntax
TRIM (String)
Parameter
String (Required): The parameter is the String from which you will remove
extra spaces at the beginning, end, and in between.
1. Leading Space
The spaces that come before a value in a cell are called leading spaces (if
any).
2. Trailing Space
The spaces that come after the last number in a cell are called trailing spaces
(if any).
3. In-Between Space
In-between Space is the space that comes at the last of each word. In-Between
space is anything that has more than one space character. By default, there
should be one space character after every word.
Example:
Get rid of the extra spaces in the String. ”Hello World”
Here are the steps to write a VBA macro to use the VBA TRIM function to get
rid of any extra spaces in a given string:
Author: Umesh M anral
Step 1: Open the tab for the VBA developer. Go to the Excel worksheet, click
on the ribbon tab, and then click on the developer window. Tap on the visual
basic editor or press Alt+F11.
Step 2: You will see the VB Editor window. Next, you need to do a module.
Click on Insert on the ribbon, then click on Module.
Step 3: Insert the Moule window. Start with the macro name and then the
variable declaration.
Step 4: The next step is to provide the TRIM function with the desired String.
Save the result of the TRIM function in the variable. When finished, the output
will be shown using the VBA MsgBox function.
Author: Umesh M anral
Output
You can activate the macro by selecting Run from the VBA ribbon toolbar or
pressing the F5 key. A MsgBox will be displayed in Excel immediately.
When you press CTRL + SPACE in the Visual Basic for Applications (VBA)
macro window, a drop-down menu called VBA IntelliSense displays. When
you press the spacebar after typing MID, the syntax will appear. The function
will return a Null value if the string argument provided is Null. If the start
number parameter’s value is greater than the text string argument’s length, the
VBA MID function will return a null string.
Syntax
Mid(string_to_search, starting position, number_of_characters)
Parameter
Example:
Find the middle name from the string “Robin Mark Simon”.
Step 2: You will see the VB Editor window. Next, you need to do a module.
Click on Insert on the ribbon, then click on Module.
Author: Umesh M anral
Step 3: The VBA adds a new window for the Module. Start the programme
by implementing the name of your macro and declaring the variables.
Step 4: Next, add the VBA MID function. In the arguments, we will give the
String, the start character, which is 6, and the length, which is 5, as we want to
get the first four characters of our middle substring.
Output
Either click Run or press the F5 key to run your macro. So, you will see that
VBA will throw a MsgBox with the middle String in it.
The SPLIT String function divides a string into substrings based on the
delimiter that is given. It gives back a one-dimensional array that starts at 0
and holds the parts of substrings. The VBA Split function is one of the
String/Text Functions that come with the programme. In the Microsoft Visual
Basic Editor, the code for this function is written in VBA macro. But you can
also use Split in Excel spreadsheets as a function.
Syntax
Split (Expression, [Delimiter], [Limit], [Compare])
Parameter
1. Expression (required)
The parameter is the input string that you will split based on the delimiter.
2. Delimiter (Optional)
This parameter shows the delimiter used to split the String. It usually includes
the “Expression” argument. For example, suppose you have a string “Hello,
World! “. In this case, a comma is a delimiter with the Split function to
different substrings. If you don’t give a value for this argument, the default is
the space character.
3. Limit (Optional)
An optional parameter lets the user say how many substrings they want to
return in total. For example, if you only want to get the first three substrings
from the String, you would put 3 in this argument. If you don’t give a value for
this argument, the default is -1, which provides you with all the substrings.
4. Compare (Optional)
It returns the type of comparison the user wants to use in the SPLIT function
when evaluating the substrings.
• When compare is 0, it means that the comparison is binary. It’s useful when
your delimiter is a text string, like “XYZ,” since this is case-sensitive. The
letters ‘XYZ’ and ‘xyx’ will look different.
• When compare is 1, 1 shows the Text comparison. It helps if your delimiter
is a text string, like XYZ. Though you have “xyz” in the “Expression” String,
it will be seen as a delimiter.
VBA Split is a built-in function that helps quickly divide a string into
substrings based on the delimiter that is given. The following are the steps to
creating a VBA macro to use the Split function to divide your String:
Step 1: Navigate to the VBA developer tab or press Alt + F11, which is a
keyboard shortcut, or by going to developer window > visual basic editor.
Step 2: You’ll see the VB Editor. Next, you need to do a module. Right-click
on the VBA Project, then click Insert, then click Module.
Step 3: Insert the Moule window. Create the macro and then declare the
variable. Following that, present a method known as Result ().
Check out the macro code below:
Step 4: Call the Split function, give it the string “Textstr,” and store the value
in the result method.
Author: Umesh M anral
Check out the macro code below:
Output
Tap the F5 key to execute the code and get the results. As a result, the Split
function breaks up the string ‘StrText’ into smaller strings and stores each in
the StrResult array. The following substrings will be available in the backend:
For instance, if you want to find the position of ‘x’ in ‘Excel’, using the Excel
VBA InStr function would return 2.
• [Start]: An optional parameter. This is an integer value that tells the InStr
function the starting position from which it should start searching.
• String1: A required parameter. This is the main string and can also be
referred to as the parent string) in which you want to search.
• String2: A required parameter. This is the substring that you are searching
for.
• Compare: An optional parameter. It specify the string comparison to be
used.
The compare argument settings are analyze in the below table:
• InStr is a VBA function and not a worksheet function, so you cannot use it in
a worksheet.
• The InStr function returns 0 if it cannot find the substring within the main
string.
Example 1:
In this example, I will use the InStr function to find the position of ‘r’ in the
word “Hello World”. You can follow the coding in the below screenshot.
Either you can run the above code using the F5 key, or you can also run the
code manually if you like, and you will get the following output, such as
Example 2:
Suppose, I want to find the position of ‘R’ in the sentence “Hello World”. We
will use the compare argument as vbBinaryCompare, as shown in the below
screenshot. Author: Umesh M anral
In conclusion, you can now execute the above program, the supplied compare
argument as vbBinaryCompare InStr function returns the zero because there is
no uppercase “R” letter exists in the word “Hello World”.
• Date Function
• Time Function
Dates can be formatted in Excel VBA in two distinct methods
• NumberFormat property of cells
• The VBA Format function. For example, Variables
Syntax
Format (Optional): It is a format that the user sets up for the expression.
There is no restriction on whether or not we utilise our custom-defined format
or predefined named formats.
FirstDayOfWeek (Optional): The value states the first day of the week. If
the format function is not given a declaration for the first day of the week, it
will assume Sunday as the first day. It can have any of the following values:
FirstWeekOfYear (Optional): It is a value that tells the first week of the
year. If the first week of the year is not specified, the format function assumes
that the first week starts on the 1st.
Author: Umesh M anral
Example:
Step 1: Move to the Developer tab and choose Visual Basic from the list.
The VBA Array function returns a variant with an array of the same data type.
The function quickly and easily initialises an array in your macro module. The
VBA Array function is often useful to store many values in the variable.
If no arguments are given, a zero-length array is created. You can store either
a twodimensional or a multi-dimensional array by using the Array Function in
your programming language. An array’s position starts at 0 instead of 1. The
first row and column are represented by Array (0).
Syntax
Array(arglist)
Parameters
Example:
Use the Array Function in VBA to store string values
Follow the steps below to use the VBA Array Function to store String values:
Step 1: Open up your Excel file. You can open the Visual Basic window by
clicking on Developer Window > Visual Basic Editor or pressing Alt + F11.
Step 2: You will see the VB Editor window. Next, you need to do a module.
Click “Insert” on the ribbon, then click “Module”.
Author: Umesh M anral
Step 3: A module will be added. Our macro will be written in this module.
Launch the program by giving the programme’s name, followed by
“declaring” the variable.
Step 4: Now involve the Array function, passing five strings as input. We will
use MsgBox and watch window to display VarArray(0), VarArray(1),
VarArray(2), VarArray(3), and VarArray(4) later on.
The Array length was determined with the help of the UBound and LBound
functions.
Output
Click the Run button on the VBA toolbar, or hit the F5 key, to activate the
macro. Also, you can hit the F9 key, to show watch window.
Author: Umesh M anral
Click on VarArray () to ‘Add Watch’ winow. You will see that Excel shows
the watch window expression right away.
VBA will open MsgBox showing the array’s size.
Syntax
“Workbooks.Open Filename:=” File_Name”
“File Name” is the name of the Workbook file that we want to open. When we
need the Workbook’s file name, we need to give the file’s path, name, and
extension, such as (.XLSX), (.xlsm), (.XLS), etc.
Workbooks.Open Method
Example:
Let’s say you want to open a file called “Test File” in Excel. This file is
stored on the computer in the D drive.
The “Test File” Excel file, saved on the system’s D drive, opens
automatically. There is no subfolder to get to the file, so the path given is
apparent. The Macro will fail to run if the correct file path is not specified or
an incorrect file name is given. Therefore, the file’s name and location should
be accurate.
Application.GetOpenFileName Method
The limitations of Workbooks are overcome by using this technique. While the
prior approach worked, it had issues whenever the path or file name was
modified. You can search for a file on your computer using the Application
GetOpenFileName method. The tool makes it easy to track down the stored
data. The VBA Workbooks are still required to access the file. It has five
arguments.
Example:
Follow the steps below to open the saved file:
Step 1: Navigate to the Developer menu and pick the Visual Basic sub-menu.
Step 2: Give a name to your Macro by typing the following into the code box.
Step 3: Write the statement that makes Filename a variable.
Step 5: If the Filename is not equal to false, the next step is to write an If-
Then statement in the code that will open the specified Excel file.
Step 6: Hit Run to put the preceding code into effect. It opens up a dialogue
box.
Using Visual Basic for Applications (VBA), Excel may be programmed with
recorded macros that can then be played out automatically. The result is a
more rapid and precise execution of the repetitious tasks. As part of executing
the macros, VBA locates the cells where the actions above are to be taken.
The range object in VBA is helpful for such situations. The VBA range
property is valuable in various cases, much like the worksheet property.
Syntax
Range (Cell1, [Cell2]) As Range
1. Object Qualifier
It tells the location of the object. The item is stored in a workbook, also
known as a worksheet.
2. Property
This holds information about the object.
3. Method
It describes the operation that the object will carry out. Example: Methods
include sorting, formatting, selecting, cleaning, etc., performed on a range of
data.
When referencing a VBA object, be sure to use the provided hierarchy. The
dot operator (.) separates these three parts in the following way:
Application. Workbooks. Worksheets. Range
Range Property
The cells in a Worksheet can be accessed via a number of its properties. Most
actions on Excel worksheets, such as “A1,” “A3:C6,” and others, share a
typical argument with the range property.
Syntax
Application.Workbooks(“Book1.xlsm”).Worksheets'(“Sheet1”).Range(“A1”)
The Range property is quite versatile and is useful for various purposes.
These responsibilities involve:
The Cell property is quite analogous to the Range, except for its “item”
property, which helps to refer to specific cells in a spreadsheet. The
programming loop can benefit from cell property.
For Example:
Cells.item(Row, Column)
• Cells.item(1,1) or
• Cells.item(1, “A”)
Syntax
Range(“A1”).offset(Rowoffset:=1, columnoffset:=1).Select
Author: Umesh M anral
Chapter 32: VBA Functions
VBA Functions. A function is a group of statements that together perform a
task. Every C program has at least one function, which is the main one, and all
the most trivial programs can be defined as additional functions.
Program codes can be divided into separate functions depending on the user’s
initiatives but logically the division usually is to allow each function to
perform a specific task.
You can place a function into a module. Let take a look at the following steps:
Step 1: Navigate to the Developer checkbox and click on the Visual Basic
editor.
Step 2: Click on the Insert button and select the Module option from the drop-
down menu.
Syntax
For example, suppose a function named Sum in the following code, such as:
Author: Umesh M anral
Explanation:
In this example, two arguments (of type double) and a return type (of type
double) are used. The function name Sum is used to indicate which result you
wish to return, such as (x + y). Then, using the function’s name (Sum) and a
value for each argument, you can call this function from elsewhere in your
code.
To do this, you must insert a command button on your worksheet and include
the code below and write the function in worksheet cells:
Explanation:
You can use another variable sumValue to store the result. The function returns
a value, so you have to detect these values in your code. You can also change
this variable by displaying its value in a worksheet cells.
After write the functions in Cells (A1) on the sheet, the following message
will appear.
Example:
VBA has a solution called “Option Explicit Statement” to ensure this doesn’t
happen. The statement is at the top of the code, which means that any user
must define the variable. It is also important because it shows which variable
has yet to be determined.
Above, there is a blue sentence that says “Option Explicit”. Now, when we
run the code, we get the following error.
Step 1: Select the Tools tab in the VB Editor’s headers, and then click on
Options from the list of options that appears.
Author: Umesh M anral
Step 2: When you click on Options, a box like the one below will open.
Step 3: Choose the “Require Variable Declaration” option and click OK.
Start the module again to notice the changes in the VB Editor. The VB Editor
will now have the Option Explicit option for any module.
Examples:
Write a VBA command button to implement Option Explicit.
Step 1: Open Excel and click the Developer tab ->Visual Visual Basic-
>Insert Module.
Author: Umesh M anral
Step 3: Write code to display a MsgBox with the value 30 whenever the Run
icon is clicked.
Step 4: Click on Run icon on the top of VBA editor. Now a MsgBox displays
30.
Step 5: We will manually add the option explicit
statement to the top of your code.
Step 6: Click the Run icon again, and this time the compile error appears.
Author: Umesh M anral
Types or Error
There are three common forms of VBA programming errors. They are:
• Syntax Errors
• Compile Errors
• Runtime Errors
• Logical Errors.
1. Syntax Errors
Syntax errors (compile errors) occur at the interpretation time for VBScript.
In the following code, for instance, we get a syntax error because we spelt the
name of an object wrong (worksheet instead of worksheets).
Example:
VBA will show a Syntax error when you run the above code.
2. Compile Errors
Compile errors arise when in the code something got missing that is essential
for the macro to operate. When dealing with VBA, there are often cases where
the syntax is proper on a single line of code, but a mistake appears when the
entire project's code is examined. The following are some frequent causes of
compilation errors:
• Using the For loop without the Next statement
• Using the Select statement in your macro without the End Select statement
• Defining a Sub or Function that doesn't exist in your programme
• Calling a Sub or Function with the incorrect parameters
• Option Explicit is at the top of your code, but variables are not declared at
the top.
Example:
Using If without End IF
VBA will show a compile error when you run the above code.
3. Runtime Errors
Exceptions and runtime errors are the same things. These errors happen when
the code is being run after it has been interpreted.
Author: Umesh M anral Example 1:
When you try to run the above macro, you'll get a runtime error because the
syntax is correct, but variable length is exceed as Integer length is between
(-32,768 to 32,767). Example 2:
VBA will show a Run-Time error when you run the above code.
4.
Logical Errors
The most challenging error to fix is a logical error, as even a single misstep
can change the entire outcome. In addition, logical mistakes are difficult to
identify because their location is tied directly to your company's reasoning.
These aren't the result of a syntax or runtime error like the others. Instead, they
occur when the user modifies the script in some way that breaks the
programme logic and causes the user to receive unexpected results.
Author: Umesh M anral Example:
VBA will show a Logical error when you run the above code. As the value is
divided by zero.
What is VBA Error Handling?
Error Handling is how you deal with different programming errors when your
code runs. Handling errors will make your code look more professional and
ready to handle errors. It is recommended to employ error handling techniques
whenever there is any possibility of an error occurring.
• Go To Line
• Go To 0
• Go To -1
• Resume Next
1. Go To Line
The error-handling method starts the error-handling routine at the line in the
given line argument. If there is an error at compile time or run time, it moves
the programme flow to the line specified in the same method.
Example:
2. Go To 0
It turns off the current procedure's error handler, sets it to "Nothing," and
shows a message box that explains the error.
Example:
3. Go To -1
Author: Umesh M anral
The error-handling function disables the existing exception in the current
operation, clears the error, and resets it to nil, allowing the user to create a
second error trap. Example:
4. Resume Next
This error-handling method says that the error will be ignored whenever a
run-time error happens. The control will move to the statement right after the
one where the error occurred, and execution will continue from there.
Example:
Visual Basic isn’t an object -oriented language, but it handles projects. The
VBA object has functions, properties, data, and child objects. Excel objects
have several characteristics. VBA objects hide implementation details.
Memory is allocated when a VBA element is inserted.
Components of Object
The components of an object are helpful in a programme. The following are
the three main parts of the object.
1. Property
It lets the user read a value from the object or write it in the application
window.
2. Method
They help to perform some actions with the object data. The procedures are
carried out within a method.
3. Event
When VBA code runs, events occur.
1. Application Objects
When creating macros in Visual Basic for Applications (VBA), the most
popular object to work with is the Excel VBA Application Object.
Applications objects allow you to conduct a wide range of tasks on Excel
files using a variety of applications. It has the following characteristics:
In Excel, the workbook object is also quite common. Workbooks (with the
XLSX file extension) are where Excel’s magic happens (by default). Each
object associated with the active Workbook in Microsoft Excel is stored in
the Workbook object, which is a part of the Workbook collection. A
workbook in Excel can have n sheets (the sheets are only restricted by
memory). Excel provides users with four distinct kinds of sheets, which are as
follows:
• Excel Worksheets
• Excel 4.0 XLM macro sheet
• Chart sheets
• Excel 5.0 dialogue sheet
Example:
Use VBA to make a programme to close the workbooks.
3. Worksheet Objects
The worksheet is the most common sort of sheet used in spreadsheets. Each
cell on a worksheet serves as a storage location for the worksheet’s
associated data, numbers, Author: Umesh M anral
comments, and formulas. In a worksheet cell, you can enter numeric data, text,
dates and times, Boolean values (True or False), or the result of a calculation
or function. All worksheets in a given workbook are stored in the Worksheets
collection, which is a part of the Worksheet object.
Example:
Create a programme to hide your worksheet using the worksheet object, as
shown in the example.
4. Range Objects
The range is the most frequently utilised object that aids in automating VBA
activities when working with Excel sheets. A Range object can execute
various operations on several Ranges in an Excel Worksheet. Each cell or
range of cells on a worksheet is represented by a Range object contained
within a Worksheet object.
VBA events are actions or occurrences that happen within an application, and
you can write code (event handlers) to respond to these events. Events allow
you to create interactive and dynamic applications by triggering specific
actions or functions in response to user interactions or other system events.
VBA has a plethora of events like this for which you can write custom code.
As soon as an event occurs, any code you have associated with it will be run
immediately. When Excel detects an occurrence, it does this automatically.
You need only create the necessary code and insert it into the proper event
subroutine.
These events occur at the workbook level in Excel. Examples include opening
or closing a workbook, saving it, or changing its structure. Common
workbook events include Open, Close, BeforeSave, and SheetChange.
2. Worksheet Events
3. Chart Events
Chart events are related to charts in Excel and can be used to trigger actions
when users interact with a chart. It includes clicking on a data point or
resizing a chart. The common chart events include MouseDown,
BeforeDoubleClick, and DragOver.
4. UserForm Events
UserForms are custom dialog boxes or forms that you can create in Excel.
Events related to UserForms allow you to control user interactions with the
form elements, such as buttons, text boxes, and combo boxes. Some of the
common UserForm events include Initialize, Click, and Change.
5. Application Events
Access to the workbook triggers the Workbook Open event. When an Excel
workbook is opened, the user will be greeted with this notice. The event can
be altered such that a prompt appears every time a user opens a worksheet.
In the editor, choose the sheet for which you want to run event-based
instructions, and then click Worksheet
When the user’s selection shifts, the SelectionChange event is automatically
added:
Here is a code that highlights the currently selected cells in a spreadsheet and
unhighlights them when the selection changes:
Output:
Author: Umesh M anral
For example, when you’re done with the sheet, delete the contents of rows A2
through A10.
For example, if the clicked cell is in column C, insert the current date on
right-click:
If the Cancel variable is set to True, the right-click event will be cancelled
(and the context menu will not appear).
This event occurs whenever there is a change to the sheet’s cell content:
In short, VBA events are the secret sauce that transforms static software into
dynamic, userfriendly marvels. Harnessing these events empowers developers
to craft custom solutions, making work in Microsoft Office applications a
breeze. Don’t miss out on the magic of VBA events – they are your ticket to
automation excellence!