VBA Macros

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

VBA Macros

Automation in MS Excel
Overview

©2020 Grant Thornton India LLP. All rights reserved.


What are Macros?
A macro is a set of computer instructions
• A computer program
• Activated by an event
• That tells the computer what to do

Macros

Automate Tasks Automate Tasks


by Recording by Programming

©2020 Grant Thornton India LLP. All rights reserved.


View Developer Tab to start using Macros
File > Options > Customize Ribbon > Tick the Developer option on right side

11 22
3

©2020 Grant Thornton India LLP. All rights reserved.


Visual Basic Editor and Components

Menu Bar

Toolbar

Project
Explorer

Code
Properties
Window
Window

©2020 Grant Thornton India LLP. All rights reserved.


Macro Recording

©2020 Grant Thornton India LLP. All rights reserved.


Recording a Macro
• Name the macro
• Shortcut key - fill in a letter in the available space; this allows you to run the macro by holding down
the CTRL key and pressing the chosen letter on the keyboard
• Description - Description of the macro
1 Once done, remember to
click on ‘Stop Recording’
2

Click on Visual Basic to view the code.


3 The recorded macro is stored in Module

©2020 Grant Thornton India LLP. All rights reserved.


Rules relating to Macro Name

A macro name needs to follow the following set of rules:

• Cannot contain a space

• Cannot start with a number (however a macro name can definitely contain a number, like Macro1 is
valid while 1Macro is invalid name)

• Cannot contain special characters; however, underscore _ is allowed

• Cannot repeat

©2020 Grant Thornton India LLP. All rights reserved.


Essentials of Code Writing

©2020 Grant Thornton India LLP. All rights reserved.


Overview of VBA Procedures
VBA procedure Sub Procedure Function Procedure
• Set of instructions given to the
“Robot” to execute
• Perform tasks such as
performing calculations,
analyzing data, etc.
• Run line by line from
beginning to end in the code

VBA has two types of


procedures
• Sub procedure - a subroutine
which performs a task
• Function procedure - this is
used to create user defined
functions (UDF)

©2020 Grant Thornton India LLP. All rights reserved.


Syntax of Sub Procedure

Sub MacroName()
….
….
….
(code comes here)
….
….
….
End Sub

©2020 Grant Thornton India LLP. All rights reserved.


Variables and Data Types
• Variables are like buckets which hold some
content for you
• Each variable has a
✓ Name
✓ Data Type

Syntax for declaring a new variable


Dim VariableName As DataType

• Dim MyPassword As String


• Dim Counter As Long
• Dim TaxAmt As Double

For instance,
• MyPassword = “Password*01” (text value)
• Counter = 100 (non-fractional number)
• TaxAmt = 200.15 (fractional number)

©2020 Grant Thornton India LLP. All rights reserved.


Methods to run Sub procedure
• While in VB Editor, place the cursor anywhere in the code and press F5 key or click on green
color play button

• Insert a shape in Excel sheet -> Right click on shape -> Click on Assign Macro and select the code.
The code shall run when you click on the shape later

• While in Excel sheet, press Alt F8 or click on


Macros option available in Developer tab &
Select the code -> Click on Run

• Use shortcut key combination assigned to macro to run it. You may assign shortcut key while
recording a macro. Alternatively, for a written code, press Alt F8 -> Select the code -> Click on
Options -> Assign shortcut key

• Insert Form Control Button and assign macro to it, or use ActiveX Control Command Button to call
macro or write macro

©2020 Grant Thornton India LLP. All rights reserved.


Using Excel Functions in VBA
• There are in-built VBA functions while for some cases, we may want to use Excel functions which
otherwise aren’t available in VBA functions list
• In order to call Excel functions in VBA, the syntax is –

Application.WorksheetFunction.ExcelFunction

For instance,
• Application.WorksheetFunction.RANDBETWEEN( )
• Application.WorksheetFunction.PROPER( )
• Application.WorksheetFunction.VLOOKUP( ) etc.

©2020 Grant Thornton India LLP. All rights reserved.


Debugging VBA Code
• Debugging is the process of identifying and correcting bugs (errors) in your program
• If there are any issues in the code, the code shall not run at all or code execution would be
interrupted in between
• Further the macro may work with one set of data while it may show an error with some other data

Upon clicking Debug button, statement causing such error is


Example of Run Time Error
highlighted in yellow shade and [break] is shown at the top

Click on Reset button


(blue colour square)
post correcting code

©2020 Grant Thornton India LLP. All rights reserved.


Conditional Statement

©2020 Grant Thornton India LLP. All rights reserved.


If-Then-ElseIf-Else Statement
• You may use Conditional Statements in order to check for conditions and get results accordingly

Syntax Example:

If Condition Then
Result
ElseIf Condition Then
Result



Else
Result - You may use multiple Elseif statements to check
End If for multiple conditions
- Note that ElseIf is a single word

©2020 Grant Thornton India LLP. All rights reserved.


User Defined Function (UDF)

©2020 Grant Thornton India LLP. All rights reserved.


User Defined Functions – Function Procedure
• Customized function or User defined function (UDF) can be created by using function procedure
• The code writing part is essentially the same except that the variables to be used are declared in the
first statement of the code within the brackets
• The result of function procedure is displayed in excel cell wherein the UDF is entered

Syntax:
Function FunctionName(Variables)
….
….
(code comes here)
….
….
End Function

©2020 Grant Thornton India LLP. All rights reserved.


Loops in VBA

©2020 Grant Thornton India LLP. All rights reserved.


Loops
• Loop refers to repeating a task (block of VBA statements) a number of times either for a fixed number
of times or linked to some condition

Loop Categories

Repeating a task Repeating a task Repeating a task in


a given no. of times based on condition(s) each element of a group

For Next Loop Do Until Loop For Each Loop

©2020 Grant Thornton India LLP. All rights reserved.


For Next Loop
• For Next loop is used for repeating a task a defined no. of times

Example:
For Counter = 1 To N


… (statements)


Next

©2020 Grant Thornton India LLP. All rights reserved.


Do Until Loop
• Do Until loop is used for repeating a task until a condition is true

Example:
Do Until Condition


… (statements)


Loop

©2020 Grant Thornton India LLP. All rights reserved.


For Each Loop
• Looping may also be done through each object in a collection of objects
• This is done by using For Each Loop

For instance,
✓ Each Sheet in a collection of Sheets in Workbook → For Each WkSht In ActiveWorkbook.Worksheets
✓ Each Cell in a collection of Cell Range → For Each Cell In Range(“B1:B100”)
✓ Each Chart in a collection of Charts in a Sheet, etc. → For Each Cht In Sheets(“Sheet1”).ChartObjects

Syntax: Example:

For Each Element In Collection



… (statements)

Next

©2020 Grant Thornton India LLP. All rights reserved.


Event Driven Codes

©2020 Grant Thornton India LLP. All rights reserved.


Overview of Event Driven Codes
This involves arranging the sub procedure to be run automatically based on a particular event

For instance,
• Workbook open
• Before workbook close
• Worksheet is activated
• Before a worksheet is deactivated
• Data in a cell is entered or edited

Example of Worksheet Activate Event:


A message box would be displayed when a given worksheet is activated

©2020 Grant Thornton India LLP. All rights reserved.


Auto code execution based on change in a cell
Example of Worksheet Change Event:
The code is executed when there is change in value in cell C14

©2020 Grant Thornton India LLP. All rights reserved.


Macro Security & Code Protection

©2020 Grant Thornton India LLP. All rights reserved.


Check your Security Settings
• Macros can be built with malicious intent, so we need to be careful if macros are to be enabled or not;
hence the need to check the security settings
• Macros need to be enabled for the application to run properly

1
2

©2020 Grant Thornton India LLP. All rights reserved.


Check your Security Settings … cont’d
• Disable all macros without notification: Macros will not work
• Disable all macros with notification: When you open a workbook with macros, you will see a
prompt message with an option you can click to enable macros
• Disable all macros except digitally signed macros: Only macros with a digital signature are
allowed to run
• Enable all macros: This option is not recommended as potentially dangerous code can run

Of the above options, the second one viz. ‘Disable all macros with notification’ is recommended

Just because an Excel workbook contains a macro, it is no guarantee


that the macro will be executed. It all depends on the security setting
and whether the user chooses to enable or disable macros.

©2020 Grant Thornton India LLP. All rights reserved.


Protecting the Code
• Click on Developer tab while present in any 2 1
excel worksheet
• Click on Visual Basic to open the Visual
Basic Editor
• Right click on the relevant VBAProject and
then click on VBAProject Properties to
lock project for viewing and give password

3
5

©2020 Grant Thornton India LLP. All rights reserved.


Questions

You might also like