Sie sind auf Seite 1von 30

Introduction to Excel VBA

HKCAREERS BEGINNERS MANUAL


HKCareers Free Resource

TABLE OF CONTENTS

1. Introduction
2. VBA Overview
3. Excel Macros
4. Excel Terms
5. VBA Macro Comments
6. VBA Message Box
7. VBA Input Box
8. VBA- Variables
9. VBA- Constants
10.VBA- Operators

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

INTRODUCTION
VBA stands for Visual Basic for Applications, an event-driven programming language from
Microsoft. It is now predominantly used with Microsoft Office applications such as MS-
Excel, MS-Word and MS-Access.

This tutorial teaches the basics of VBA. Each of the sections contain related topics with
simple and useful examples.

VBA OVERVIEW
Visual Basic for Applications or VBA is basically a programming language that is built into
Microsoft office applications such as MS-Excel, MS-Word, and MS-Access to simplify time-
consuming or complicated tasks. VBA offers a lot of flexibility to the Microsoft products. It
opens a lot of possibilities and is a powerful tool to use. As an event-driven programming
language that follows a logical flow which imitates clicks, keystrokes and other events, it
helps to integrate user-defined functions into a spreadsheet or workbook. It thus reduces the
complexity of calculations which are otherwise too tedious. It has a series of features that
help to simplify otherwise complicated operations in Excel.

Despite being a relatively simpler tool to learn, VBA not only has great application in regular
accounting and finance related tasks, but finds its place in advanced systems related to
Robotics, Machine Learning, and of course Automation. You can build customized
applications and solutions to enhance the capabilities of those applications.

Excel VBA is the most handy tool for finance and accounting students as it allows creation of
very powerful tools in MS Excel using linear programming.

Application of VBA
VBA helps in augmenting the basic inbuilt functions that MS-Excel provides, which can be
insufficient for performing complex calculations. For instance, it is very hard to calculate the
monthly repayment of a loan using Excel's built-in formulas. Rather, it is easy to program a
VBA for such a calculation. Hence, in Excel, VBA can be used to write functions or
applications and run complicated processes. It can also be used to make sophisticated
workbooks in Excel. Excel VBA has pre-defined parts called ‘features’ which are specifically
included to make programming easy in Excel. It helps to integrate user-defined functions into
a spreadsheet or workbook.

VBA ─
EXCEL
MACROS

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

With Excel VBA you can automate tasks in Excel by writing so called macros. In this chapter,
we will look at the step-wise procedure to create a simple macro.

Accessing the VBA Editor

To open a VBA window, press "ALT+F11" in your Excel window. The screenshots below
should be able to guide you through the steps.

Step 1: Enable the 'Developer' menu in Excel by clicking on File → Options

Step 2: Drill down on ‘Customize the Ribbon’ tab → check 'Developer' tab → Click 'OK'.
(you can locate the Developer tab below the View tab)

*Source: Google

Step 3: You will now see the 'Developer' ribbon in the menu bar

*Source: Google

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

*Source: Google

Step 4: Click the 'Visual Basic' button to open the VBA Editor.

*Source: Google

Step 5: Start scripting by adding a button. To assign a macro (one or more code lines) to the
command button, execute the following steps.

Click Insert → Select the button

*Source: Google

Step 6: Right-click and select 'Properties'

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

*Source: Google

Step 7: Edit the Name and Caption as shown in the following screenshot.

*Source: Google

Step 8: Now double-click the button and the sub-procedure outline will be displayed as
shown in the following screenshot.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Step 9: Start coding by simply adding a message.

*Source: Google

Step 10: Click the button to execute the sub-procedure. The output of the sub-procedure is
shown in the following screenshot.

*Source: Google

VBA ─ EXCEL TERMS

In this section, we will discuss the commonly used excel VBA terminologies which we will
encounter in the following sections. Hence it is important to understand them at this stage.

Line of Code

This a VBA instruction as we have seen above. Generally speaking, it performs one task.

Sub

A sub is made up of one or more lines of code. We create a sub so that VBA will process the
instructions we give it. To do this we get VBA to Run the sub. When we “Run” the sub,
VBA goes through all the lines of code and carries out the appropriate actions. A macro and a
sub are essentially the same thing.

Modules

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Modules is the area where the code is written. A module contains subs which in turn contain
lines of code. There is no reasonable limit to the number of modules in a workbook or the
number of subs in a module that can be created.

*Source: Google

To insert a Module, navigate to Insert → Module. Once a module is inserted 'Module1' is


created.

*Source: Google

Within the modules, we can write VBA code and the code is written within a Procedure. A
Procedure is a unit of code enclosed either between the Sub and End Sub statement or
between the Function and End Function statements.

Procedure
Procedures are a group of statements executed as a whole, which instructs Excel how to
perform a specific task. The task performed can be a very simple or a very complicated task.
However, it is a good practice to break down complicated procedures into smaller ones.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

The two main types of Procedures are Sub and Function.

*Source: Google
Function
A ‘function’ basically takes an input value, performs predefined operations, and returns a
value as a result of the operations. Once a function is typed in the visual basic editor, it will
be available to be called from other VBA procedures or to be used in Excel worksheets. You
need four things in order to declare a function:

- Name of the function


- Input variable(s)
- Data types of input variable(s)
- Data type of the result of the function

For example:

Function OddEven (Input_no As Integer) As String

Sub-procedures
These are similar to functions. While sub procedures never Return a value, functions may or
may not return a value. Sub procedures can be called without call keyword. Sub procedures
are always enclosed within Sub and End Sub statements.

VBA ─ MACRO COMMENTS


A macro comment is a piece of text in a macro which will not be executed by Excel VBA. It
is only there to provide you information about the macro. Hence Comments are used to
document the program logic and the user information that other programmers can utilise to
work on the same code smoothly in future.

It includes details such as developed by, modified by, and can also include incorporated logic.
Comments are ignored by the interpreter while execution.

Comments in VBA are denoted by two methods.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Any statement that starts with a Single Quote (�) is treated as comment. Have a look at the
examples below:
→ This Script is invoked after successful login
→ Written by : HKCareers
→ Return Value : True / False

Any statement that starts with the keyword "REM". Following is an example.

REM This Script is written to Validate the


Entered Input
REM Modified by : HKCareers

To insert a comment, execute the following steps.


1. Open the Visual Basic Editor
2. To let Excel VBA know that you want to insert a comment, precede the text with an
apostrophe.

*Source: Google

VBA ─ Message Box


A VBA message box is a pop-up style dialog box that you can program the behavior of using
VBA. It provides an elegant and sometimes necessary way for the end user to interact with a
workbook.

Like functions and formulas in Excel, the MSGBOX function is how we create a message
box using VBA. Before we start writing VBA code, let’s take a quick look at the syntax
requirements for the MSGBOX function.

Syntax
The syntax of VBA MSGBOX is as follows:

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

MSGBOX(Text_String , [buttons] ,[title], [helpfile, context])

Parameter Description

Text_String - This is a Required Parameter. ‘Text_String’ is the message that you want the
msgbox to display. The maximum length of ‘Text_String’ is 1024 characters. If the message
extends to more than a line, then the lines can be separated using a carriage return character
(Chr(13)) or a linefeed character (Chr(10)) between each line.

Buttons - This is an Optional Parameter. A Numeric expression that specifies the type of
buttons to display, the icon style to use, the identity of the default button, and the modality of
the message box. If left blank, the default value for buttons is 0.

Title - This is an Optional Parameter. If the title is left blank, the application name is placed
in the title bar.

Helpfile - This string parameter specifies the help file to be used for the dialog box. It is also
an optional parameter but it becomes mandatory if ‘context’ parameter is to be used.

Context - This is a numeric parameter that specifies the number assigned to the appropriate
Help topic. It is an optional parameter but it becomes mandatory if ‘helpfile’ parameter is
used. If context is provided, helpfile must also be provided.

The Buttons parameter can take any of the following 20 values:

CONTENT DESCRIPTION
vbOKOnly It displays a single OK button
vbOKCancel It displays two buttons OK and Cancel.
vbAbortRetryIgnore It displays three buttons Abort, Retry, and
Ignore.
vbYesNoCancel It displays three buttons Yes, No, and Cancel.
vbYesNo It displays two buttons Yes and No.
vbRetryCancel It displays two buttons Retry and Cancel.
vbCritical It displays a Critical Message icon.
vbQuestion It displays a Query icon.
vbExclamation It displays a Warning Message icon.
vbInformation It displays an Information Message icon.
vbDefaultButton1 First button is treated as default.
vbDefaultButton2 Second button is treated as default.
vbDefaultButton3 Third button is treated as default.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

vbDefaultButton4 Fourth button is treated as default.


vbApplicationModal This suspends the current application till the user
responds to the message box.
vbSystemModal This suspends all the applications till the user
responds to the message box.
vbMsgBoxHelpButton This adds a Help button to the message box.
VbMsgBoxSetForeground Ensures that message box window is foreground.
vbMsgBoxRight This sets the Text to right aligned
vbMsgBoxRtlReading This option specifies that text should appear as
right-to-left.

Return Values

The MsgBox function can return one of the following values which can be used to identify
the button the user has clicked in the message box.

# VALUE DESCRIPTION

1 vbOK OK was clicked

2 vbCancel Cancel was clicked

3 vbAbort Abort was clicked

3 vbRetry Retry was clicked

4 vbIgnore Ignore was clicked

5 vbYes Yes was clicked

6 vbNo No was clicked

Example

Function MessageBox_Demo()
'Message Box with just prompt message
MsgBox("Welcome")

'Message Box with title, yes no and cancel Buttons
a = MsgBox("Do you like blue color?",3,"Choose options")
'Assume that you
press no No
Output

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Step 1: The Function displayed above can be executed either by clicking the "Run" button on
the VBA Window or by calling the function from Excel Worksheet as shown below:-

*Source: Google

Step 2: A Simple Message box is displayed with a message "Welcome" and an "OK" Button

*Source: Google

Step 3: Clicking on OK, displays another dialog box like the one shown below, containing a
message along with "yes, no, and cancel" buttons.

*Source: Google

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Step 4: After clicking the ‘No’ button, the value of that button (7) is stored as an integer and
displayed as a message box to the user as shown here. Thus the value of the integer indicates
which button the user has clicked on.

*Source: Google

VBA ─ InputBox
This function prompts users to enter values. After entering the values, if the user clicks the
OK button or presses ENTER on the keyboard, the InputBox function will return the text in
the text box. If the user clicks the Cancel button, the function will return an empty string ("").

Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context
])

Parameter Description/ Arguments


· Prompt - This is a required parameter- the text string that you want to appear in the
input box. The maximum length of prompt is approximately 1024 characters. If the
message extends to more than a line, then the lines can be separated using a carriage
return character (Chr(13)) or a linefeed character (Chr(10)) between each line.

· Title - This is an optional text string that specifies a title to be displayed at the top of
the input box. If the title is left blank, the application name is placed in the title bar.

· Default - This is an optional text string that is displayed in the input box as the default
response if no other response is entered.

· XPos - This optional parameter is an integer specifying (in twips) the horizontal
distance (X axis) of the input box, from the left edge of the screen. If left blank, the
input box is horizontally centered.

· YPos - This optional parameter is an integer specifying (in twips) the vertical distance
of the input box from the top of the screen. If left blank, the input box is vertically
centered.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

· Helpfile - This too is an optional parameter. It is a string expression that identifies the
helpfile to be used to provide context-sensitive Help for the dialog box.

· Context - This optional parameter is a numeric expression that identifies the Help
context number assigned by the Help author to the appropriate Help topic. If context
is provided, helpfile must be provided as well.

Example 1

Let’s look at the command below:

' Request the user's name.


Dim response As String
response = InputBox( "Please enter your name" )
' The text string "response" now contains the user's input (or an empty string
' if the Cancel button was selected).

This call to the InputBox function displays the following dialog box to the user:

*Source: Google

While the dialog box is displayed, the VBA code pauses, until the user selects one of the
buttons. After the user selects one of the dialog box buttons, the InputBox function returns a
text string, as follows:

→ If the OK button is selected: The text string that has been entered into the dialog box is
returned;

→ If the Cancel button is selected: An empty text string is returned.

In the above example code, the returned text string is then assigned to the variable response
before the program continues to run.

Example 2

Let us calculate the area of a rectangle by getting values from the user at run time with the
help of two input boxes (one for length and one for width).

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Function findArea()

Dim Length As Double

Dim Width As Double

Length = InputBox("Enter
Length ", "Enter a Number")
Width = InputBox("Enter
Width", "Enter a Number")

Output
Step 1: In order to execute the above, call using the function name and press Enter as shown
below:-

*Source: Google

Step 2: Upon execution, the First input box (length) is displayed. Enter a value into the input
box.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

*Source: Google

Step 3: Once you enter the first value, the second input box (width) is displayed:-

*Source: Google

Step 4: Next, click the OK button. The area is displayed as shown in the screenshot below:-

*Source: Google

VBA─VARIABES
Variables are specific values that are stored in a computer memory or storage system. Later,
you can use that value in code and execute. The computer will fetch that value from the
system and show in the output. Each variable must be given a name. Following are the basic
rules for naming a variable.

➢ It must begin with a letter as the first character, and never with a number
➢ No space, period (.), exclamation mark (!), or the characters @, &, $, # in the name is
allowed
➢ The name length cannot can't exceed 255 characters
➢ The Visual Basic reserved keywords cannot be used as variable names

Syntax
In VBA, you need to declare the variables before using them. They can be declared either
explicitly or implicitly

❏ Implicitly: Below is an example of a variable declared Implicitly.


❏ label=hkcareers
❏ volume=4

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

❏ Explicitly: Below is an example of variable declared Explicitly. You can use "Dim"
keyword in syntax
❏ Dim Num As Integer
❏ Dim password As String

Below is the Syntax:-


Dim <<variable_name>> As <<variable_type>>

Data Types
Since the computer cannot differentiate between the numbers (1,2,3..) and strings (a,b,c,..),
Data Types are used to make this differentiation. There are many VBA data types, which can
be segregated into two main categories:
❖ Numeric Data Types
❖ Non-numeric Data Types

Numeric Data Types

This table displays the numeric data types and the allowed range of values.

Type Range of Values


Byte 0 to 255
Integer -32,768 to 32,767
Long -2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single 1.401298E-45 to 3.402823E+38 for positive values

-1.79769313486232e+308 to -4.94065645841247E-324 for negative values


Double 4.94065645841247E-324 to 1.79769313486232e+308 for positive values
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/-79,228,162,514,264,337,593,543,950,335. if no decimal is used
Decimal
+/- 7.9228162514264337593543950335 (28 decimal places)

Non-Numeric Data Types


The table below represents the non-numeric data types and the allowed range of values.

Type Range of Values


String (fixed length) 1 to 65,400 characters

String (variable length) 0 to 2 billion characters

Date January 1, 100 to December 31, 9999

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Boolean True or False

Object Any embedded object

Variant (numeric) Any value as large as double

Variant (text) Same as variable-length string

In VBA, if the data type is not specified, it will automatically declare the variable as a
Variant.

Example

Let us create a button and name it as 'Variables_demo' to demonstrate the use of variables.

*Source: Google

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Private Sub Variables_demo_Click()



Dim password As String
password = "Admin#1"

Dim num As Integer
num = 1234

Dim BirthDay As Date
BirthDay = 30 / 10 / 2020

MsgBox "Password is" & password & Chr(10) & "Value of num is" & num &
Chr(10) & "Value of Birthday is" & BirthDay

End Sub

Output
Once the script is executed, the following output shall be displayed:-

Password is Admin#1
Value of num is 1234
Value of Birthday is 12:02:08 AM

VBA─ Constants
Data whose values do not change within a certain scope should be declared as constants by
using the Const modifier.
The value of a constant is specified when it is declared (this process is called initialization).
Any attempts to alter the value of a constant then results in a compilation error.
Using constants instead of hard-code literal values is an excellent programming practice. This
makes your code more readable and easier to be modified later on if needed.

The rules for naming a constant are same as those for creating variables. The constant must
have a valid symbolic name and an expression composed of numeric or string constants and
operators (but no function calls).

➢ Only a letter must be used as the first character

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

➢ No space, period (.), exclamation mark (!), or the characters @, &, $, # can be used in
the name
➢ The name cannot exceed 255 characters in length
➢ You cannot use Visual Basic reserved keywords as variable name

Syntax

In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to
change the value of the constant.

Const <<constant_name>> As <<constant_type>> =


<<constant_value>>
Example
Here is how you can create a button "Constant_demo" to understand how to work with
constants:

Private Sub Constant_demo_Click()



Const MyInteger As Integer = 42

Const myDate As Date = #2/2/2020#

Const myDay As String = "Sunday"


MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is " &
myDate & Chr(10) & "myDay is " & myDay

End Sub

Output

This is what you will see upon execution of the script:

*Source: Google

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

VBA ─ Operators
The built-in VBA operators consist of mathematical operators, string operators, comparison
operators and logical operators. The different types of Operators are discussed individually
below. VBA supports following types of operators:

❖ Arithmetic Operators
❖ Comparison Operators
❖ Logical (or Relational) Operators
❖ Concatenation Operators

The Arithmetic Operators


In the expression: 9 minus 5 is equal to 4; 9 and 5 are called operands and - is called operator.

Following arithmetic operators are supported by VBA:

Operato
r Description
+ Adds the two operands

- Subtracts the second operand from the first

* Multiplies both the operands

/ Divides the numerator by the denominator

% Modulus operator and the remainder after an integer division

^ Exponentiation operator

Arithmetic Operators ─ Example


You can add a button and try the example below to understand all the arithmetic operators
available in VBA.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Private Sub Constant_demo_Click()



Dim a As Integer
a = 5

Dim b As Integer
b = 10

Dim c As Double

c = a + b
MsgBox ("Addition Result is " & c)

c = a - b
MsgBox ("Subtraction Result is " & c)

c = a * b
MsgBox ("Multiplication Result is " & c)

c = b / a
MsgBox ("Division Result is " & c)

c = b Mod a
MsgBox ("Modulus Result is " & c)

c = b ^ a
MsgBox ("Exponentiation Result is " & c)

End Sub

Once executed, the above script will display the following results

➔ Addition Result is 15
➔ Subtraction Result is -5
➔ Multiplication Result is 50
➔ Division Result is 2
➔ Modulus Result is 0
➔ Exponentiation Result is 100000

The Comparison Operators


Comparison operators compare two numbers or strings and return a logical (True or False)
result. The main Excel VBA comparison operators are listed in the table below:

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Assume variable A holds 10 and variable B holds 20, then -

Operato Exampl
r Description e
Checks if the value of the two operands are equal or not. If yes, then the
condition ( A == B)
==
is true. False.

Checks if the value of the two operands are equal or not. If the values are not A <> B) is
<>
equal, then the condition is true. True.
(
Checks if the value of the left operand is greater than the value of the right A> B) is
>
operand. If yes, then the condition is true. False.
Checks if the value of the left operand is less than the value of the right (
operand. A< B) is
<
If yes, then the condition is true. True.
Checks if the value of the left operand is greater than or equal to the value of (
the A >= B) is
>=
right operand. If yes, then the condition is true. False.
(
Checks if the value of the left operand is less than or equal to the value of the A <= B) is
<=
right operand. If yes, then the condition is true. True.

Comparison Operators ─ Example

These examples discussed here will be helpful towards developing your understanding of
comparison operators:-

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Private Sub Constant_demo_Click()


Dim a: a = 10
Dim b: b = 20
Dim c

If a = b Then
MsgBox ("Operator Line 1 : True")
Else
MsgBox ("Operator Line 1 : False")
End If

If a<>b Then
MsgBox ("Operator Line 2 : True")
Else
MsgBox ("Operator Line 2 : False")
End If

If a>b Then
MsgBox ("Operator Line 3 : True")
Else
MsgBox ("Operator Line 3 : False")
End If

If a<b Then
MsgBox ("Operator Line 4 : True")
Else
MsgBox ("Operator Line 4 : False")
End If

If a>=b Then
MsgBox ("Operator Line 5 : True")
Else
MsgBox ("Operator Line 5 : False")
End If

If a<=b Then
MsgBox ("Operator Line 6 : True")
Else
MsgBox ("Operator Line 6 : False")

End If

End Sub

Once executed, this script will generate the following results:-


We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Operator Line 1 : False



Operator Line 2 : True

Operator Line 3 : False

Operator Line 4 : True

Operator Line 5 : False

Operator Line 6 : True

The Logical Operators


Logical operators compare Boolean expressions and return Boolean results. Hence these also
return a logical (True or False) result. The main Excel VBA logical operators are listed in the
table below:

Assume variable A holds 10 and variable B holds 0, then:-

Operator Description Example

AND If both conditions evaluate to True then the a<>0 AND b<>0 is False
expression is True

OR Performs logical disjunction or inclusion a<>0 OR b<>0 is True


on two Boolean expressions. If either
expression evaluates to True, or both
evaluate to True, then Or returns True. If
neither expression evaluates to True, Or
returns False.

NOT Performs logical negation on a Boolean NOT(a<>0 OR b<>0) is False


expression. It yields the logical opposite of
its operand. If the expression evaluates to
True, then Not returns False; if the
expression evaluates to False, then Not
returns True

XOR Performs logical exclusion on two Boolean (a<>0 XOR b<>0) is False
expressions. If exactly one expression
evaluates to True, but not both, Xor returns
True. If both expressions evaluate to True
or both evaluate to False, Xor returns
False.

Logical Operators ─ Example

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

You can try some of the Logical operators available in VBA by creating a button and adding
the following function.

Private Sub Constant_demo_Click()



Dim a As Integer
a = 10
Dim b As Integer
b = 0

If a <> 0 And b <> 0 Then
MsgBox ("AND Operator Result is : True")
Else
MsgBox ("AND Operator Result is : False")
End If

If a <> 0 Or b <> 0 Then
MsgBox ("OR Operator Result is : True")
Else
MsgBox ("OR Operator Result is : False")
End If

If Not (a <> 0 Or b <> 0) Then
MsgBox ("NOT Operator Result is : True")
Else
MsgBox ("NOT Operator Result is : False")
End If

If (a <> 0 Xor b <> 0) Then
MsgBox ("XOR Operator Result is : True")
Else
MsgBox ("XOR Operator Result is : False")
End If

End Sub

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

When you save it as .html and execute it in the Internet Explorer, then the above script will
produce the following result.


AND Operator Result is : False

OR Operator Result is : True

NOT Operator Result is : False

XOR Operator Result is : True

The Concatenation Operators


Concatenation operators join multiple strings into a single string. There are two concatenation
operators, + and &. Both carry out the basic concatenation operation, as the following
example shows.

The + Operator has the primary purpose of adding two numbers. However, it can also
concatenate numeric operands with string operands. The + operator has a complex set of rules
that determine whether to add, concatenate, signal a compiler error, or throw a run-time
InvalidCastException exception.

The & Operator is defined only for String operands, and it always widens its operands to
String, regardless of the setting of Option Strict. The & operator is recommended for string
concatenation because it is defined exclusively for strings and reduces your chances of
generating an unintended conversion

Assume variable A holds 5 and variable B holds 10 then -

Operator Description Example


+ Adds two Values as Variable. Values are Numeric A + B will give 15

& Concatenates two Values A & B will give 510

Assume variable A = "Microsoft" and variable B = "VBScript", then -

Operator Description Example


+ Concatenates two Values A + B will give MicrosoftVBScript

& Concatenates two Values A & B will give MicrosoftVBScript

Concatenation Operators

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Following table shows all the Concatenation operators supported by VBScript language.
Assume variable A holds 5 and variable B holds 10, then:-

Operator Description Example


+ Adds two Values as Variable. Values are Numeric A + B will give 15

& Concatenates two Values A & B will give 510

Example
Here is an example of the Concatenation operator in VBScript:

Private Sub Constant_demo_Click()


Dim a as Integer : a = 5
Dim b as Integer : b = 10
Dim c as Integer

c=a+b
msgbox ("Concatenated value:1 is " &c) 'Numeric addition
c=a&b
msgbox ("Concatenated value:2 is " &c) 'Concatenate two numbers
End Sub

Below is an example to understand all the Logical operators available in VBA by creating a
button and adding the following function.
Concatenated value:1 is 15
Concatenated value:2 is 510

Concatenation can also be used for concatenating two strings. Check the screenshots below
which represent the Excel & operator and how it can be used as a worksheet function in MS
Excel:

*Source: Google

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

HKCareers Free Resource

Here are the results that would be returned once we run the string above:-

=A1 & A2
Result: “Alphabet”

=”The wondrous” & “world”
Result: “The wondrous world”

= (A1 & “male mentality”)
Result: Alphamale mentality

Disclaimer:

Data and information above are extracted from the internet and
consolidated by HKCareers. HKCareers does not own the copyrights of the

information and pictures contained in this guidebook.

We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching

Das könnte Ihnen auch gefallen