You are on page 1of 33

Excel Macros

LEVEL 1

Sreejith R
Module IV

VBA or Excel, Level 1: The Visual Basic Editor, Fundamentals of Excel


VBA, Recording Macro & Understanding Code behind, Editing,
Writing and Saving as Macro Excel Objects -Object Hierarchy,
Application, Workbook, Worksheet, Range. Variables and Constants,
Data types, Variable Levels, Declaring Variables. Effective Decision
Making, If/And/Or, Select Case, Loops, Types of Loops, Loop Pitfalls.
User Defined Functions
Module IV

The Fundamentals of Excel VBA, the Visual Basic Editor, Objects and Properties.
Excel Objects - Workbook Included, Object Hierarchy, Application, Workbook, Worksheet, Range,
Command Bars. Variables and Constants, Data types, Variable Levels, Declaring Variables, Constants.
Loops, Types of Loops, Loop Pitfalls.
Effective Decision Making, If/And/Or, Select Case, Dates and Times. Workbook and Worksheet
Events.
Debugging and Error Handling, Prevention, Good Habits, Runtime Errors.
Excel Worksheet Functions in VBA, Specific Examples, Excels Built-In Features.
User Defined Functions
An Introduction to VBA
- What is VBA
An abbreviation for Visual Basic for Applications
Official name is "Visual Basic, Applications Edition."
VBA is Microsoft's common application programming (macro) language for
Word, Excel, Access, etc.
Also being implemented in other Microsoft applications such as Visio and is
at least partially implemented in some other applications such as AutoCAD...
VBA and VB have a lot in common, but they are different. VB is a
programming language that lets you create standalone executable programs.
An Introduction to VBA
- What Can You Do With VBA

Write Macros to Automate Labor-Intensive and Repetitive Tasks

Create User-Defined Functions to Achieve Complicated Functionality

Create Standard Windows Menu/Tool Bars for Interface

Interact with Other Windows Programs (like Matlab)

I/O with External Files

Database Operation ….
An Introduction to VBA
- VBA- Object Based Programming Language

C++, Java, etc. are OOP (Object Oriented Programming) Language

VBA is an Object Based Programming Language

What is Object?
An Introduction to VBA
- VBA Object Based Programming Language
 Concepts – Containers or Collections
 A Group of Similar Objects Share Common Properties, Methods and Events
 Such as Workbooks, Worksheets, etc.
 Worksheets is a collection of all the Worksheet objects in the specified or
active workbook.
 Worksheets(1) refers to the 1st worksheet of current active workbook.
 Worksheets (“mooring”) refers to the worksheet named “mooring”.
An Introduction to VBA
- VBA Object Based Programming Language

 Concepts – Objects
 The term Excel Objects (collectively referred to as the Excel
Object Model) refers to the entities that make up an Excel
workbook, such as Worksheets, Rows, Columns, Cell
Ranges, and the Excel Workbook itself.
 Such as Workbook, Worksheet, Range, Cell, Chart, Name,
etc.
 Worksheets(1) is an Object Referring to the First Sheet
 Range("A1:B15") is an Object Referring to a Range
 Cells(1,1) or Range(“A1”) is an Object Referring to Range
“A1”
An Introduction to VBA
- VBA Object Based Programming Language

 Concepts – Properties
 Properties are the Physical Characteristics of Objects
and Can be Measured or Quantified.
 Properties for Collections
 - Worksheets.Count (Read Only)
 - Worksheets.Visible = True (Read and Write)
 Properties for Object
 - Range("A1:B15").Rows.Count (Read Only)
 - Range("A1:B15").Font.Bold = True (Read and Write)
An Introduction to VBA
- VBA Object Based Programming Language

 Concepts – Methods
 Methods are the Actions that Can be Performed by
Objects or on Objects
 Methods for Collections
 - Worksheets.Add
 - Worksheets.Delete
 Methods for Objects
 - Range("A1:B15").ClearContents
 - ActiveCell.Copy
An Introduction to VBA
- VBA Object Based Programming Language

 Concepts – Events
 Objects Can Respond to Events, Such as Mouse Click,
Double Click on a Cell, Active a Worksheet,
Open/Close/Save a Workbook, etc.
 Worksheet Events –
 Such as Activate, Deactivate, Change, Selection
Change, Before Double Click, etc.
 Workbook Events-
 Such as Activate, Deactivate, Open, Before Close,
Before Saving, Before Print, New Sheet.
An Introduction to VBA
- VBA Object Based Programming Language

 Concepts – Referring To
 Use brackets () to refer to member object
 Worksheets(“mooring”)
 Use dot . to refer to child object or object’s
properties and methods
 Worksheets(“mooring”).Range(“A1:B3”).Font.Bold
An Introduction to VBA
- VBA Object Based Programming Language

 Concept Collections
(worksheets)
Summary

Objects
(worksheet)

Properties Method
name Add

Event
Activate
Variables
Variables are programmer-defined names.
Variables can store values that can change while the application is
running.
Variables store values in computer memory.
A program code statement can change the value at any time.
A value for a variable exists only while a program is running.
Constants

Constants store values that are specified at design time.


 Constants remain the same while the application is running.
Programmers can change a constant’s value at design time.
Types of constants include:
 Intrinsic—specific to an application
 User-defined—created by a programmer
 Conditional compiler—defined in the host application
Data Type
Computer cannot differentiate between the numbers (1,2,3..) and strings (a,b,c,..). To make this differentiation,
we use Data Types. VBA data types can be segregated into two types
 Numeric Data Types
 Non-numeric Data Types

Numeric Data Types


Data Types
String Data Types
Decision Making
Decision making allows the programmers to
control the execution flow of a script or one of
its sections. The execution is governed by one or
more conditional statements.
Following is the general form of a typical
decision making structure found in most of the
programming languages.
VBA Decision making Structures
Loops
There may be a situation when you need to
execute a block of code several number of times.
In general, statements are executed sequentially:
The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control
structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement
or group of statements multiple times. Following is
the general form of a loop statement in VBA.
Loops in VBA
Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all the remaining statements in the loop are NOT
executed.
VBA supports the following control statements. Click the following links to check
their detail.
Variable Declaration
Dim num As Integer
num = 1234

Dim password As String


password = "Admin#1"
Sample Method
Private Sub say_helloworld_Click()
Dim password As String
password = "Admin#1"
Dim num As Integer
num = 1234
Dim BirthDay As Date
BirthDay = DateValue("30 / 10 / 2020")
MsgBox ("Passowrd is " & password & Chr(10) & "Value of num
is " & num & Chr(10) & "Value of Birthday is " & BirthDay )
End Sub
Const Declaration

Const MyInteger As Integer = 42


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

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
Decision Making if-else
Private Sub if_demo_Click()
Dim x As Integer
Dim y As Integer

x = 234
y = 234

If x > y Then
MsgBox ("X is Greater than Y“)
ElseIf y > x Then
Msgbox ("Y is Greater than X“)
Else
Msgbox ("X and Y are EQUAL“)
End If
End Sub
Decision Making Switch Case
Private Sub switch_demo_Click()
Dim MyVar As Integer
MyVar = 1

Select Case MyVar


Case 1
MsgBox "The Number is the Least Composite Number"
Case 2
MsgBox "The Number is the only Even Prime Number"
Case 3
MsgBox "The Number is the Least Odd Prime Number"
Case Else
MsgBox "Unknown Number"
End Select
End Sub
Looping For loop

Private Sub Constant_demo_Click()


Dim a As Integer
a = 10

For i = 0 To a Step 2
MsgBox ("The value is i is : " & i)
Next
End Sub
Exam Perspective : Explain Loops in VBA
Looping is repeating the execution of certain statements more than one time.
you can distinguish between 2 loop categories

Category #1: Fixed-iteration loops, which repeat the relevant statements a set number of times.

Category #2: Indefinite loops, in which the number of iterations is more flexible.
In either case, the factor that determines the number of iterations is sometimes referred to as the loop invariant or
determinant.

classifying loops determinants in the following 2 categories:


• Numeric expressions, which can be evaluated as numbers.
• Logical expressions, which evaluate to True or False.

you can write VBA loops in several different ways.


The looping structures supported by Excel and covered in this VBA tutorial are the following:
• For… Next.
• For Each… Next.
• Do While and Do Until.
• While… Wend.
For… Next Excel VBA Loops

The basic syntax of the For… Next Excel VBA loop.


Items within square brackets ([ ]) are generally optional.

For counter = start To end [Step step]

[statements]

[Exit For]

[statements]

Next [counter]

Example:

You might also like