0% found this document useful (0 votes)
9 views120 pages

Training Material - VBA

The document provides an overview of Excel VBA 2016, focusing on creating and managing macros to automate tasks in Excel. It explains the concepts of macros, methods for creating them (writing and recording), and includes practical scenarios for implementing macros for various tasks. Additionally, it covers writing procedures, the difference between Sub and Function procedures, and using the Visual Basic Editor.

Uploaded by

kapeelvora81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views120 pages

Training Material - VBA

The document provides an overview of Excel VBA 2016, focusing on creating and managing macros to automate tasks in Excel. It explains the concepts of macros, methods for creating them (writing and recording), and includes practical scenarios for implementing macros for various tasks. Additionally, it covers writing procedures, the difference between Sub and Function procedures, and using the Visual Basic Editor.

Uploaded by

kapeelvora81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Excel VBA 2016

Pragati Software Pvt. Ltd.


207, Lok Center, Marol-Maroshi Road
Andheri (East), Mumbai 400 059, India.
Tel.: +91-22 3091 0000 (100 Lines)
www.pragatisoftware.com

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Visual Basic For Application (Excel)

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
What is Macro?

• A Macro is a series of commands written in logical order to


automate any repeated task.
• It is stored in Microsoft Visual Basic Module.
• It can be assigned to a Add-Ins Tab of Ribbon or button on
Quick Access Toolbar.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Creating Macros
There are two methods to create macros

• Writing: Write code for the actions in the sequence using


VBA language for the macros.

• Recording: Record your actions in Excel using Macro


Recorder. Excel has a Macro Recorder which
records the action and writes the code for the
macro.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Adding Developer Tab on Ribbon

Check this box

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Recording a Macro

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Define the Macro

Macro Name
Short cut

Macro Storage

Description

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Stop Recording

Stop
Recording

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Relative Reference Macro
If you want the macro to run
relative to the position of
the active cell, record it
using relative cell
references. On the
Developer Tab click on Use
Relative Reference so that
it is selected. Excel will
continue to record macros
with relative references until
you quit Excel or until you
click Use Relative
Reference again, so that it is
not selected.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario-1

• Create a macro to automatically add the company’s name with


the specific format in the first row to any spreadsheet.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Run your Macro

Macros can be run by

1. The shortcut (which you assign while defining


macro)

2. The name,

3. Button on Quick Access Toolbar

4. The button on worksheet

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Run the Macro by the name

1 2

Short cut key to open this dialogue box is Alt + F8.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario– 2
• Create a macro to display a product table with the table headers,
Product Name, Quantity, Price , Total and Net ,
• Table must appear always from the second row and first column,
• Excel should not accept any negative values for price and
quantity.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario – 3
• Create a macro to display the same product table (Scenario2)
but this time it should appear anywhere , where ever user wants
(Using relative reference)

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Creating Buttons on Quick Access ToolBar

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Modifying Menus or Buttons

Change Button image

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario – 4
• Create a macro which will extract region-wise sum of
salary. (Use “Salary worksheet”)
• On click of “Subtotal” button, region-wise subtotal should
be added on a new worksheet.

Click subtotal

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution

1. Sort

Continued..
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Continued..
2. Subtotal

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Second Level of Outline

Selection of Visible cells (Alt + ; )


Continued..
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Creating Button on Excel Worksheet
1 2

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario– 5
• Create a macro which will extract records from different
department and region.
• User will type the required department and region and click
filter button

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Contd…

Database Range

Criteria Range

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Editing the Recorded Macros

• Sometimes recorded macros may not give you full automation.


Then you require to edit your recorded macros.
• Or you want to add some actions in your recorded macro then
you can edit your macro.
• For example in the scenario – 5 instead of changing criteria in
excel your macro should ask which region and dept, user will
type then click ok and macro will perform filter.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario– 6
• Open Scenario – 5 and modify the code to do the following
• User should get an InputBox to type the required department
and region and click filter button

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Previous code

Modify the code as follows

Added code

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario– 7

• Create a macro to import data from a txt file (sales.txt) and


design a pivot table which shows productwise, monthwise sum
of sales.

Sales.txt
month,product,Sales in figures Sum of Sales in figures
product month Total
jan,cd,100000 cd jan 100000
feb 75000
jan,Monitor,15000 mar 12000
cd Total 187000
jan,pen drive,75000 Monitor jan 15000
feb 20000
feb,monitor,20000 Monitor Total 35000
feb,Cd,75000 pen drive jan 75000
mar 73000
mar,pen drive,73000 pen drive Total 148000
Grand Total 370000
mar,cd,12000

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution

1 2

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
3 4

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario – 8

Purpose Original Code Modified Code


For file ActiveSheet.QueryTables.Ad ActiveSheet.QueryTables.Add(C
selection d(Connection:="TEXT;c:\vb onnection:="TEXT;" &
a\sales.txt”,Destination:=Ran Application.GetOpenFilename,
ge("A1")) Destination:=Range("A1"))

For variable ActiveWorkbook.PivotCache ActiveWorkbook.PivotCaches.A


length data s.Add(SourceType:=xlDatab dd(SourceType:=xlDatabase,
ase, SourceData:= SourceData:=
"Sheet31!R1C1:R7C3").Crea Range("a1").CurrentRegion.A
tePivotTable ddress).CreatePivotTable

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Practice - 1

• Create a macro(“Report_title”) which will add a new


worksheet with following details in the existing Workbook
cell address cell content
A2 Your company name
A3 Title as “Daily report”
A4 Today’s date
A6 Sr. No.
B6 Product
C6 Quantity Sold

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Practice – 2

• Create a macro to add signature i.e. your name and designation


at the end of the data.
Note : Consider the worksheet is in the format of Practice – 1.
• This macro always adds a worksheet before current worksheet.
Modify that macro such that it will add new worksheet after
current worksheet.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Writing Procedures

• You can write code for each action you record


• All the procedures are written inside a Module.
• For writing the code you require to open Visual Basic Editor
• Alt + F11 is the shortcut to open Visual Basic Editor.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Sub Procedure vs. Function Procedure

Sub Procedure Function Procedure

It cannot return a value It can return a value

It can perform actions on excel It cannot perform actions on excel


objects objects

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Visual Basic Editor
Project Explorer
Properties Window

Edit Toolbar

Procedure Window

Object Box

Code Window

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Visual Basic Editor
Project Explores Property Window
View Code
View Object
Toggle Folders

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code Window
Object Box Procedure Window

Code
Area

Procedure View
Full Module View

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Inserting Modules
3
1

2
Type new name

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Writing code inside Modules

Double click here to activate


the code window

2
Write your code
here

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Sub Procedure

• Sub procedure is a series of Visual Basic statements enclosed


by the Sub and End Sub statements that performs actions but
doesn't return a value.

• A Sub procedure can take arguments, such as cconstants,


variables, or expressions that are passed by a calling
procedure.

• If a Sub procedure has no arguments, the Sub statement must


include an empty set of parentheses.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Macro

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Function Procedures

• A Function procedure is a series of Visual Basic statements


enclosed by the Function and End Function statements.
• A Function procedure is similar to a Sub procedure, but a
function can also return a value. A Function procedure can
take arguments, that are passed to it by a calling procedure.
• If a Function procedure has no arguments, its Function
statement must include an empty set of parentheses. A function
returns a value by assigning a value to its name in one or more
statements of the procedure.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Function Procedure

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 9

• Write a function to calculate Profit where profit is the


difference of Selling price and Cost price
• Profit function requires two arguments i.e. cost price and
selling price.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Branching a procedure

• If you want to run a block of code depending on the value of a


condition, you can use following decision structures.

 If...Then...Endif
 If...Then...Else…Endif
 If...Then...Elseif…Then…Else…Endif
 Select Case …End Select

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 10

• Write a function to check whether person is eligible for voting


or not.
• To check eligibility Vote function requires age as an argument.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 11

• Write a function to find grade of employee based on basic


salary as per given criteria(Using If Elseif)

salary grade
<8000 D
8000 – 15000 C
15000 – 25000 B
>=25000 A

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 12

• Write a function to find bonus based on grade (Using Select


Case)
Grade bonus
A 25000
B 20000
C 15000
D 10000

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 13

• Write a function to calculate DA based on region. DA is 5% if


region is either east or west or else it will be 10%
• Use OR Operator to check multiple condition.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 14

• Write a function to calculate DA based on region.


• Da is 5% if region is east and salary >10000
• Otherwise 10%
• Use AND Operator to check multiple condition.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Select Case Vs. If … End If

• Use the Select Case statement as an alternative to using ElseIf


in If...Then...Else statements when comparing one expression
to several different values.

• While If...Then...Else statements can evaluate a different


expression for each ElseIf statement, the Select Case
statement evaluates an expression only once, at the top of the
control structure.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Variables and Constants

Variable
• A variable is a named storage location that can contain data that can
be modified during program execution.
• Each variable has a name that uniquely identifies it within its scope.
• A data type can be specified or not.
• Variable names
 Must begin with an alphabetic character,
 must be unique within the same scope,
 can't be longer than 255 characters, and
 can't contain an embedded period or type-declaration character.
Constant
• A named item that retains a constant value throughout the execution
of a program. A constant can be a string or numeric literal

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Declaring Variables and Constants

• Syntax to declare a variable

DIM name_of_variable AS type_of_variable

For example Dim strName As String


Dim intX As Integer
Dim intX , intYAs Integer
• Syntax to declare a constant

Const name_of_variable AS type_of_variable = constant value

For example Const conAge As Integer = 34

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Data Types of Variables and Constants

Data type Range


Byte 0 to 255.
Integer – 32,768 to 32,767.
Long – 2,147,483,648 to 2,147,483,647.
Single – 3.402823E38 to – 1.401298E – 45 (negative values).
1.401298E – 45 to 3.402823E38 (positive values).
Double – 1.7200369313486231E308 to
– 4.94065645841247E – 324 (negative values).
4.94065645841247E – 324 to 1.7200369313486231E308
(positive values).
Currency – 922,337,203,685,477.5808
to 922,337,203,685,477.5807.
Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Data Types of Variables and Constants

Data type Range


String Zero to approximately two billion characters.
Variant Date values: January 1, 100 to December 31, 9999.
Numeric values: same range as Double.
String values: same range as String.
Can also contain Error or Null values.
Boolean True or False.
Date January 1, 100 to December 31, 9999.
Object Any object reference.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using the Option Explicit Statement

• Use Option Explicit to enforce explicit declaration of variables.


• It must appear in a module before any procedure.
• If not used, undeclared variables will be of Variant type.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Message box and Input box

• Msgbox function
Displays a message in a dialog box, waits for the user to click a
button, and returns an Integer indicating which button the user
clicked.
• InputBox Function
Displays a prompt in a dialog box, waits for the user to input
text or click a button, and returns a stringcontaining the
contents of the text box.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Selecting and Activating Cells

• When you work with Microsoft Excel, you usually select a cell
or cells and then perform an action, such as formatting the cells
or entering values in them.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Selecting and Activating rows and columns

• Some times you need to select specific rows and columns and
then perform actions.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Working with Sheets

• Many a times you need to select a specific sheet, or


• Insert new sheet
• Rename a sheet, etc…

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Working with WorkBook

• Some times you need to work with different workbooks.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Working with Application

• Some times to ignore different excel messages you need to


work with application object.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 15

• Create a macro which should accept Name and City of a


person and store it in excel worksheet in cell A1 and B1.
• If user type Mumbai as city then font color must be red.
• Use InputBox function to take input from the user.
• Use MsgBox function to display results.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 16
• Create a macro name it as Data_Entry
• Accept employee code, name, date of joining and salary of a
person
• Insert the values in “Database” worksheet
• Every new record must be stored after the last record.

Last
Record

New
Record

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using Loops (repeating action)

• Looping allows you to run a group of statements repeatedly.


Some loops repeat statements until a condition is False; others
repeat statements until a condition is True. There are also
loops that repeat statements a specific number of times or for
each object in a collection.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using Do...Loop Statements

• You can use Do...Loop statements to run a block of statements


an indefinite number of times.
• The statements are repeated either while a condition is True or
until a condition becomes True.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Repeating Statements While a Condition is True

• In a Do...Loop statement there are two ways to use the While


keyword to check a condition

 You can check the condition before you enter the loop , or
 You can check it after the loop has run at least once.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 17

• Write a code to accept and validate username.


• Blank name should not be allowed.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using For…Next Statements

• You can use For...Next statements to repeat a block of


statements a specific number of times.

• For loop use a counter variable whose value is increased or


decreased with each repetition of the loop internally.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 18

• Create a macro named fill_series to display numbers from 1 to


10(starting with cell A1)

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using For Each…Next Statements

• For Each...Next statements repeat a block of statements for


each objects in a collection or each element in an array.
• Visual Basic automatically sets a variable each time the loop
runs.
• Any number of Exit For statements may be placed anywhere
in the loop as an alternative way to exit.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 19

• Create a macro name it as UPPER_CASE to convert data into


capital letters
• Use Ucase () function to convert the case into capital letters

Before After

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 20

• Create a macro name it as lower_case to convert data into


small letters
• Use lcase () function to convert the case into small letters

Before After

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 21

• Create a macro name it as Proper_case to convert data into


Title case letters
• Use WorksheetFunction object to use any function from excel
in VBA.

After
Before

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 22
• Open Scenario – 22 and modify
• After storing record macro should ask to the user to be
continued or not, and run as per user response.
• If user click OK then it should continue the data entry
• If user click Cancel then display Thanks and end the macro.

On OK

On Cancel
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 23
Create a macro which will calculate the following for each employee
• HRA (75% of salary),
• DA (60% of salary) and
• TOTAL (salary +hra +da)

Before

After

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 24
• Create a macro to display list of names of worksheets in current
workbook.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Auto-Executed Macros

To use
Run a macro as soon as workbook Sub auto_open()
gets opened
End Sub

Run a macro as soon as workbook is Sub auto_close()


closed
End Sub

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Practice - 3

• Write a function(“Search_sheet”) to check existence of any


sheet.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Practice - 4

• Write a macro to increase the salary by 2000 for each


employee.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 25

• Create a macro to generate regionwise departmentwise sum of


salary and count of employees using pivot table
• Modify code such a way that everytime pivot should be
generated on current data

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 26

• Write a code to remove duplicate records from “daily”


worksheet if they exists in “master” worksheet.
(Use nested loop)

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 27

• Create a macro named as Merging_Sheets which will copy


data from all worksheets to one worksheet
• Your macro should generate a pivot for total of quantity sold
for regionwise and then emp code wise after consolidation.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
What are Arrays

• A set of sequentially indexed elements having the same


intrinsic data type.
• Each element of an array has a unique identifying index
number.
• Changes made to one element of an array don't affect the
other elements.
• An array whose size is specified is a fixed-size array.
• An array whose size can be changed while a program is
running is a dynamic array.
• Single dimension array: Only with rows
• Multiple Dimension array: With rows and columns

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Declaring the Arrays

• Arrays are declared the same way as other variables,


Syntax :
Dim name_Of_array(Size) As Data_Type

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Using Arrays

• For example, to store daily expenses for each day of the


month, you can declare one array variable with 31 elements,
rather than declaring 31 variables.
• Each element in an array contains one value.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Array Indexing

• All array indexes begin at zero.


• Whether an array is indexed from 0 or 1 depends on the setting
of the Option Base statement.
• If Option Base 1 is not specified, all array indexes begin at
zero.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Declaring a Dynamic array

• By declaring a dynamic array, you can size the array while the
code is running.
• Use a Dim statement to declare an array, leaving the
parentheses empty
Syntax
Dim Name_Of_Array() As Data_Type

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Resizing a Dynamic Array

• Use the ReDim statement to declare an array implicitly within


a procedure.
• Be careful not to misspell the name of the array when you use
the ReDim statement.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Errors
An error is generated if a statement fails. There are two types of
errors

Logical When macro does not give the expected result.


These errors can be handled by change in logic and hit and
trial method

Technical When run time failure of any statement. Use On Error


statement to handle these errors.

Syntax These include incorrectly spelled keywords, mismatched


parentheses, and a wide variety of other errors. Excel flags
your syntax errors and you can't execute your code until they
are correct

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Error Handling

• There are three ways to handle errors

 Whenever error encounters direct the control to the specific


label or line of code.
On Error GoTo line / label
On Error

 Continue with the statement immediately following the


statement that caused the run-time error
On Error Resume Next

 Disable any enabled error handler in the current procedure.


On Error GoTo 0

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 28

• Open the Scenario 22.


• It will generate an error if Database worksheet does not exists.
• Modify the code to handle this error, i.e., your program should
add a new worksheet if database worksheet does not exist.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Error Number

• Each runtime error has a number. If you know the number you
can trap the error by its number.
For example
Error Number Description

61 Disk Full

4 Application defined or
Object defined error
7 Out of memory

9 Subscript out of range

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 29

• Open Scenario -28


• If you leave inputbox empty, your macro will generate an error.
• Modify the code as follows (use On error resume next)

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Debugging the macro
• Debugging is the process of finding and correcting run time
errors and logical errors.
• Press or F8 to execute code one at a time.

Debug Toolbar
Immediate Window
Reset
Step Into Step Out Quick Watch
Run Macro

Break Step Over

Toggle Breakpoint Local Window


Design Mode
Watch Window

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
User Forms
• User Forms are used to create customized Dialogue Box as
follows.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Create User Forms

1 2

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Adding other controls
1 3

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Handling events for the control

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario - 30
• Create a UserForm which will accept Participant’s information
to get enrolled for the training.
• Form should have “Insert” and “Cancel” command button .
• When Insert button is clicked the information entered in the
form must go into the excel.
• When Cancel button is clicked the Form should be closed.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution
1. Insert a UserForm .
2. Change the name and caption from the property window
Name of the Form USR_enrol
Caption Training Enrolment Form
3. Design the form as follows

Continued...
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Control Name Property Value
Label LBL_header Caption Pragati Software Pvt. Ltd.
Label LBL_name Caption Name
Label LBL_address Caption Address
Label LBL_contactno Caption Contact No.
Label LBL_email Caption Email-id
Label LBL_Subject Caption Subject
TextBox TXT_name
TextBox TXT_address
TextBox TXT_contactno
TextBox TXT_email
TextBox TXT_companyname Text Enter your company name
Frame FRM_details Caption Other Details
Combo Box CBO_subject Caption
Option Button OPT_company Caption Company
Option Button OPT_Personal Caption Personal
Command Button CMD_insert Caption Insert
Command Button CMD_cancel Caption Cancel

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code to give initial values to the control

• Select View code form Project explorer


• Select the UserForm object
• Select Initialize event

Select Object Select event

Write your code here

Continued...
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code for option buttons

Double click here

Write your code here

Continued...
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code for Insert Button

Double click here

Write your code here


Continued….
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code to show User Form
To run the UserForm from excel , insert a module and write a macro

Sub Enrol_form()
USR_enrol.Show
End Sub

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Add- Ins
• Add- Ins are separate utilities.

• They provide some extra functionality to the software.

• Extension name of an Add Ins is .XLAM

• In Excel we have readymade Add Ins like Solver , Analysis


Toolpack , Conditional Sum Wizard, etc…

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Scenario 31
• Create an Add- Ins to convert the case into upper / lower /
proper, according to the option selected by the user.

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Solution
• Design a form for Add-Ins

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Object Name Property Value
Reference Edit Refselect
Option Button Optupper Caption UPPERCASE
Option Button Optlower Caption lowercase
Option Button Optproper Caption Proper Case
Command Button Cmdexit Caption EXIT

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code for the Change Case form

Double click here

Write your
code here

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code for the Change Case form

Double click here

Write your
code here

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Code for the Change Case form

Double click here

Write your code here

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Creating menu through the code
Sub auto_open()
‘This code will create a new menu in the existing menubar , which will have one
‘menuitem i.e., Changecase Add-Ins
Dim newmenu As CommandBarPopup
Dim menuitem As CommandBarButton
Set newmenu = CommandBars(1).Controls.Add(Type:=msoControlPopup,
before:=CommandBars(1).Controls("help").Index)
newmenu.Caption = "E&xtras“
‘When Changecase menuitem is selected it should show changecase form
Set menuitem = newmenu.Controls.Add(Type:=msoControlButton)
menuitem.Caption = "&Change Case"
menuitem.OnAction = "show"
End Sub
Sub auto_close()
‘This will remove menu when add ins is removed from the excel
CommandBars(1).Controls("extras").Delete
End Sub
Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Protect your Add-Ins with the password

Type your password

Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Continued…
Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
How to use Add-Ins

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Contd…

Pragati Software Pvt. Ltd., 207, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

You might also like