Você está na página 1de 37

MsExcel VBA

MsExcel VBA (Macro) Programming


Study Material

Developed by
Sanjay Jamalpur

Microsoft Excel VBA (Macro) Programming

1
MsExcel VBA

Table of Contents
Macro _________________________________________________________________________ 4
Record a macro _________________________________________________________________ 4
Running a Recorded Macro ________________________________________________________ 5
Deleting a Macro ________________________________________________________________ 5
Editing the recorded macro ________________________________________________________ 6
Introduction to VBA ______________________________________________________________ 7
Object Models __________________________________________________________________ 7
Understanding the Visual Basic Editor _______________________________________________ 8
Working with Project Explorer _____________________________________________________ 9
Understanding Sub Procedure and Function Procedure ________________________________ 11
Understanding Data Types, Variables and Constants __________________________________ 13
Variable ______________________________________________________________________ 14
Constants _____________________________________________________________________ 15
Operators _____________________________________________________________________ 15
Arithmetic Operators ___________________________________________________________ 15
Comparison (Relational) Operators ________________________________________________ 16
Logical Operators ______________________________________________________________ 17
Understanding the Document Object Model (DOM) of Excel ____________________________ 18
Using With-End With construct____________________________________________________ 20
Decision making using IF-Then constructs ___________________________________________ 21
Select Case construct ____________________________________________________________ 22
Looping ______________________________________________________________________ 23
InputBox ______________________________________________________________________ 26
MsgBox Function _______________________________________________________________ 27
String Functions ________________________________________________________________ 28
Date Functions _________________________________________________________________ 29
Creating Custom Menu / Toolbar (Excel 2003) _______________________________________ 30
Adding Icons on Quick Access Toolbar (Excel 2007/2010/2013) __________________________ 32
Creating own custom Tab on the Ribbon (Excel 2010 / 2013) __________________________ 33
Excel (DOM) Objects and Properties ________________________________________________ 34
Chart Objects and Properties _____________________________________________________ 34
PageSetup Objects and Properties _________________________________________________ 34
Font Objects and Properties ______________________________________________________ 35
Characters Object ______________________________________________________________ 35
2
MsExcel VBA

PivotTable Object and Properties __________________________________________________ 35


Shape / Picture Object and Properties ______________________________________________ 36
DIR function ___________________________________________________________________ 36
Cells, Worksheet, Workbook, Selection, Copy, Paste, Windows Objects and Properties _______ 37

3
MsExcel VBA

Macro
A macro is a set of instructions, which can be called number of times to ease a repetitive task.
The instructions called statements are written on a macro sheet in the Visual Basic language.

View tab Macros Panel (Group) Macro

Record a macro

1. On the View tab, point to Macro, and then click Record New Macro.
2. In the Macro name box, enter a name for the macro.
Note: The first character of the macro name must be a letter. Other characters can be letters,
numbers, or underscore characters. Spaces are not allowed in a macro name; an underscore
character works well as a word separator.

3. To run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box.
You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters),
where letter is any letter key on the keyboard. The shortcut key letter you use cannot be a

4
MsExcel VBA

number or special character such as @ or #. The shortcut key will override any default
Microsoft Excel shortcut keys while the workbook that contains the macro is open.

4. In the Store macro in box, click the location where you want to store the macro.

If you want a macro to be available whenever you use Excel, store the macro in the Personal
Macro Workbook in the Excel Startup folder.
To include a description of the macro, type the description in the Description box.

5. Click OK.
If you select cells while running a macro, the macro will select the same cells regardless of
which cell is first selected because it records absolute cell references. If you want a macro
to select cells regardless of the position of the active cell when you run the macro, set the
macro recorder to record relative cell references. On the Stop Recording toolbar, click
Relative Reference. Excel will continue to record macros with relative references until you
quit excel or until you click Relative Reference again.
6. Carry out the actions you want to record.
7. On the Macro button, click Stop Recording

Running a Recorded Macro


Select the View tab click on the Macro button View Macro this will pop-up the dialog box
as shown below select the macro to run click on button Run
Or
Press the shortcut key you assigned while recording the Macro.

Deleting a Macro
Select the View tab click on the Macro button choose View Macro this will pop up the
above dialog box select the macro you want to delete and click on Delete button.

5
MsExcel VBA

Editing the recorded macro


Excel generates code of the macro recorded at the back of excel i.e. in the Visual Basic editor; we
have to go to the VBE (Visual Basic Editor) to edit the macro. The code generated will be by default
in the form of Sub Procedure placed in a Module. Below diagram shows a Sub Procedure code

Press ALT +F11 to navigate to Visual Basic editor

6
MsExcel VBA

Introduction to VBA
Visual basic for application (VBA) is a powerful programming language that you can use to add
automation, new features, or even customized functions to your excel workbooks.

Following is the summary of VBA


You perform actions is VBA by executing VBA code.
You write (or record) the VBA code, which is stored in a VBA module. The VBA modules are
stored in as Excel workbook, but you view or edit a module using the Visual Basic Editor
(VBE)
The module is stored as .bas file which can be imported or exported
The code is stored in the form of Procedure in the module and there are two types of
procedures in VBA Sub procedure (Public or Private) and Function procedure
You write the code by referring the standard library of object models

Object Models
The secret of using VBA with other application lies in understanding the object model for each
application. Excels object model for example exposes several very powerful data analysis objects,
such as worksheets, charts, pivot tables and scenarios as well as mathematical, financial,
engineering and general functions. With VBA, you can work with these objects and develop
automated procedures. Object classes are arranged in a hierarchy the arrangement of these objects
is referred to as Excels Object Model. As explained below with an example.

Application. Workbooks (Book1). Worksheets (Sheet1). Range (A1). Select

The above statement means as follows Application refers to the main object i.e. MS Excel which
contains another object as WorkBooks and Book1 is the name of the workbook, which in turn
consists of Worksheet object and Sheet1 is the name of the sheet, which in turn consist of cells which
is defined by Range object and Select is a method or action to be done. In short to describe the
above object hierarchy selects cell A1 in worksheet by name Sheet1 present in workbook (file) by
name Book1

7
MsExcel VBA

Understanding the Visual Basic Editor


The VBE is a separate application that works seamlessly with Excel. By seamlessly we mean that
excel takes care of the details of opening the VBE when you need it. You cant run VBE separately
excel must be running in order for the VBE to run.
Activating the VBE
When youre working in excel you can use any of these techniques to switch to VBE
Press Alt + F11

The above fig. shows the VBE chances are that your VBE window may not look exactly as above
because this is highly customizable, you can hide windows, change their sizes, dock them,
rearrange them and so on.

The VBE has lots of parts lets briefly understand some key components

Menu bar
The VBE menu bar works like any other menu bar youve in windows based programmes. It contains
commands that you use to work with the various components in the VBE.

Toolbar
The standard toolbar is directly under the menu bar by default. VBE toolbars work just like those in
Excel. For displaying the toolbars click on menu View Toolbars Select the required toolbar

8
MsExcel VBA

Project Explorer window


The Project Explorer window displays a tree diagram that consists of every workbook that is
currently open in excel (including add-ins and hidden workbooks). If the project explorer window is
not visible, then press Ctrl + R or click on menu View Project Explorer

Code window
A code window (sometimes known as a module window) contains VBA code. Every item in a project
has an associated code window. To view a code window for an object, double-click the object in the
Project Explorer window on the required object / module

Immediate window
The immediate window is most useful for executing VBA statements directly, testing statements,
and debugging the code. This window may or may not be visible. If the immediate window is not
visible, then press CTRL + G

Working with Project Explorer

When youre working in the VBE, each excel workbook and add-in thats currently open is
considered a project. You can think of a project as a collection of objects arranged as an outline. You
can expand a project by clicking the plus sign (+) at the left of the projects name in the Project
Explorer window. You can contract a project by clicking the minus sign (-) to the left of a projects
name, above fig. shows the Project Explorer.

9
MsExcel VBA

Adding a new VBA module


To add a new VBA module to a project, select the projects name in the Project Explorer window,
and choose Insert Module. Or you can right-click the projects name and choose Insert Module
from the shortcut menu.
Note: When you record a macro, excel automatically inserts a VBA module to hold the recorded
code.

Removing a VBA module


If you need to remove a VBA module from a project, select the modules name in the Project
Explorer window and choose File Remove xxx (where xxx is the name of the module). Or you can
right-click the modules name and choose Remove xxx from the shortcut menu. You will be
prompted whether you want to export the module before removing it.

Exporting objects
Every object in a project can be saved to a separate file. Saving an individual object in a project is
known as Exporting. And it stands to reason that you can also Import objects into a project. Exporting
and Importing objects might be useful it you want to use a particular object (such as VBA module or
a UserForm) in a different project. To export an object select it in the Project Explorer window and
choose File Export File (Or press Ctrl + E) you will be prompted for a file name.
Note: If you export that object remains in the project (only a copy of it is exported).

Importing objects
To import a file into a project select the projects name in the Project Explorer window and choose
File Import File you will be prompted with a dialog box asking for file name. You can import only
a file that has been exported using File Export command.

10
MsExcel VBA

Understanding Sub Procedure and Function Procedure


Procedure is a set of instructions given to perform some task in a logical sequence. VBA provides
two different types of procedures

Sub Procedure
Function Procedure

Sub Procedure Sub Procedure is a set of instructions given to perform certain task in logical
sequence, a sub procedure does not return value and it may or may not carry the arguments.

General syntax of Sub Procedure


Sub ProcedureName ()
--------
Executable statements
--------

End Sub

The keyword Sub defines the start of the procedure and End Sub marks the end of procedure and
the open close parentheses () may or may not contain arguments. ProcedureName is the valid
procedure name and the program (code) is written in between the Sub and End Sub.

Function Procedure Function Procedure is a set of instructions given to perform certain task in
logical sequence; a function procedure returns value and carries required number or arguments. It
can return only one value at one time.
General syntax of Function Procedure
Function FunctionName (Arg1 as type, Arg2 as type..) as type
--------
Executable statements
--------

End Function

The keyword Function defines the start of the function and End Function marks the end of function
and the open close parentheses () contain arguments (Arg1 as type, Arg2 as type) the
arguments are defined with their respective data type as type is the return value data type.
FunctionName is the valid function name and the program (code) is written in between the Function
and End Function.

11
MsExcel VBA

Rules for defining Procedure / Function name

Procedure / Function name should start with an alphabet and can contain number and
underscore
Procedure / Function name cannot contain any defined library keyword
Procedure / Function name should be unique
Procedure / Function name can be maximum 255 characters long (including text, number and
underscore)
Procedure / Function name cannot contain any special character like %, $ etc.

Difference between Sub Procedure and Function Procedure


Sub Procedure starts with keyword Sub and ends with keyword End Sub and it does not return
value
Function Procedure starts with keyword Function and ends with keyword End Function and returns
value.

12
MsExcel VBA

Understanding Data Types, Variables and Constants


Defining data types
Data type refers to how data is stored in memory i.e. as Integers, Real numbers, Strings and so on.
Although VBA can take care of data typing automatically, it does so at a cost: slower execution and
less efficient use of memory. So to overcome this problem we need to know very well about
different data types and there uses.

Data types

Type Size in Bytes Storage Range

Integer 2 Whole number -32768 to 32767

Long 4 Whole number -2,147,483,648 to 2,147,483,647

Single 4 Decimal number 3.4 E-38 to 3.4 E+38

Double 8 Decimal number 1.7 E-308 to 1.7 E+308

String 1 Byte per Character Text 0 to 255

Boolean 2 Yes / No True / False

Variant 22 bytes + string Alphanumeric 0 to approximately 2 billion


(Characters) length

Variant 16 bytes Alphanumeric Any numeric value up to the


(Numbers) range of double data type

Currency 8 Number -922,337,203,685,477.5808 to


922,337,203,685,477.5807

Date 8 Date / Time Number starting from 1st Jan


1900 to December 31, 9999

Range -- Alphanumeric Range Selection


data

13
MsExcel VBA

Variable
A variable is simply a named storage location in computers memory. Variables can accommodate a
wide variety of data types from simple Boolean values (True or False) to large double precision
values. You can assign values to the variable by using the equal sign operator. And the value assigned
to the variable can change in the course of program.

Rules for defining variable name


Variable name should start with an alphabet and can contain number and underscore
Variable name cannot contain space or special characters like ($, # etc.)
Variable name can be maximum 255 characters long.

Declaring Variable
Variable is declared by using keyword Dim and Public along with data type. Below examples show
declaring of variable

Dim Area as Single / Public Area as Single


(In the above statement Dim and Public are the keyword, Area is the variable name and Single is the
data type)

Variable declared by using Dim keyword is a Local variable which is accessible within the procedure
it is declared

Variable declared by using Public keyword is a Global variable which is accessible across all the
procedures, forms and modules.

Dim Area as Single, Peri as Single, Volume as Single


(Above statement shows declaring of multiple variables of same data type separated with comma
(,) operator)

Below statements show declaring multiple variables of different data types and assigning values to
them
Dim Length as Single
Dim Name as String
Dim Breadth as Integer

Length = 2.4
Name = MsExcel
Breadth = 6

Note: If you dont declare variable name with specific data type VB considers that to be of Variant
data type

14
MsExcel VBA

Constants
A variables value may and often does, change while a sub procedure or function is executing (thats
why its called a variable). Sometimes you need to refer to a named value or string that never
changes.

Declaring constants
You declare constants using the Const statement. As shown below in examples
Const PI as Single = 3.142
Const Name as String = MsExcel

Note: If you attempt to change the value of a constant in VBA, you get an error, which is what you
would expect. A constant is a constant not a variable.

Operators
The operators used in VBA are classified as follows
Arithmetic
Comparison (Relational)
Logical

Arithmetic Operators: To perform basic mathematical operations such as addition, subtraction, or


multiplication; combine numbers; and produce numeric results, use the following arithmetic
operators.

Arithmetic
operator Meaning Example
+ (plus sign) Addition 3+3
(minus sign) Subtraction 31
Negation
* (asterisk) Multiplication 3*3
/ (forward slash) Division 3/3
MOD Returns the remainder 5 MOD 2 returns 1
^ (caret) Exponentiation 3^2 (the same as 3*3)

15
MsExcel VBA

Comparison (Relational) Operators: You can compare two values with the following operators.
When two values are compared by using these operators, the result is a logical value, either TRUE
or FALSE.

Comparison
operator Meaning Example
= (equal sign) Equal to A=B
> (greater than sign) Greater than A>B
< (less than sign) Less than A<B
>= (greater than or equal to sign) Greater than or equal to A>=B
<= (less than or equal to sign) Less than or equal to A<=B
<> (not equal to sign) Not equal to A<>B

Text concatenation operator Use the ampersand (&) to join, or concatenate, one or more text
strings to produce a single piece of text.

Text
operator Meaning Example
& (Ampersand) Connects, or concatenates, two values to "North" & "wind" produce
produce one continuous text value "Northwind"

Reference operators Combine ranges of cells for calculations with the following operators.

Reference
operator Meaning Example
: (Colon) Range operator, which produces one reference B5:B15
to all the cells between two references,
including the two references
, (Comma) Union operator, which combines multiple Dim Area, Peri, Volume as
references into one reference Single

16
MsExcel VBA

Logical Operators used for logical calculations.

Logical
operator Meaning
AND Used for testing if two or more than
conditions are satisfied
OR Used for testing if either one of the
condition is satisfied
NOT Used for testing if the condition is not
satisfied.

17
MsExcel VBA

Understanding the Document Object Model (DOM) of Excel


The Document Object Model (DOM) describes defined standard library Objects / Properties /
Methods which we can use while writing our custom code.

For accessing this objects / properties / methods


Click on menu Help Microsoft Visual Basic Help this will pop-up the dialog box as shown
below
Select Excel Object Model Reference in the Microsoft Visual Basic Help pane. As shown in
the figure below
You can scroll and look for the required object or type in the search box and click on the Start
searching button

18
MsExcel VBA

Clicking on the option Microsoft Excel Object Model Reference this will pop-up the Microsoft Excel
Object Model dialog box as shown below

For accessing any of the object with its properties click on that object for e.g. for accessing the Font
object click on the Font link and this will the font object properties dialog box as shown below

19
MsExcel VBA

Using With-End With construct


The With-End With instruction construct enables you to perform multiple operations on a single
object.

General syntax of With-End With construct


With Object / Method / Property
-----
Executable Statements
-----
End With

To start understanding how the With-End With construct works lets examine the following
procedure, which modifies the properties of selected data.

Sub Format_Data ()

Selection.Font.Name=Arial
Selection.Font.Size=12
Selection.Font.Color=vbBlue
Selection.Font.Bold=True

End Sub

This procedure can be rewritten using the With-End With construct. The following procedure
performs exactly same operations like the preceding one.

Sub Format_Data ()
With Selection.Font
.Name=Arial
.Size=12
.Color=vbBlue
.Bold=True
End With
End Sub
The procedure that uses With-End With statement for changing the properties of the selected data
works significantly faster than the equivalent procedure that explicitly references the object in each
statement.

20
MsExcel VBA

Decision making using IF-Then constructs


Perhaps the most commonly used instruction grouping in VBA is the If-Then construct. Good
decision making is the key to writing successful programs. A successful excel application essentially
boils down to making decisions and acting on them.

The different forms of If-Then constructs are as follows

Single line IF Statement without End IF


If condition then Executable Statements

Single condition If statement


If condition Then
-------
Executable Statements
-------
End If

If-Then construct with Else

If condition Then
-------
Executable Statements
-------
Else
-------
Executable Statements
-------
End If

If-AND construct

If condition1 AND condition2 then


-------
Executable Statements
-------
Else
-------
Executable Statements
-------
End If

21
MsExcel VBA

If-OR construct

If condition1 OR condition2 then


-------
Executable Statements
-------
Else
-------
Executable Statements
-------
End If

Multiple If-Then Else construct (If-ElseIf Ladder)

If condition Then
Executable Statements
ElseIf condition Then
Executable Statements
ElseIf condition OR condition Then
Executable Statements
ElseIf condition AND condition Then
Executable Statements
Else
Executable Statements
End If

Select Case construct


Select Case construct is used for testing multiple conditions and is an alternative for If-Then ElseIf
ladder.

General syntax of Select Case constructs

Select Case Test expression


Case expression
Executable Statements
Case expression
Executable Statements
Case expression
Executable Statements
Case Else
Executable Statements
End Select

22
MsExcel VBA

Looping
Looping is the process of repeating a block of instructions. You may know the number of times to
loop, or it may be determined by the values of variables in your program.

The different types of loops supported by VBA are as follows


For Next Loop
For Each Next Loop
Do-While Loops

For Loop is used to repeat set of instructions with specified start and end point
General syntax of for loop

For Initial Condition to End Condition


------
Executable Statements
------
Next

Example of for loop


Sub ForDemo ()
Dim i As Integer
For i = 1 To 10
ActiveCell.Offset(0, i) = i
Next i
End Sub

The above program is going to print numbers from 1 to 10 columns wise incrementing every time
by one.
Sub ForDemo ()
Dim i As Integer
For i = 1 To 10 Step 2
ActiveCell.Offset(0, i) = i
Next i
End Sub

The above program is going to print numbers between 1 to 10 column wise incrementing every time
by 2

23
MsExcel VBA

For Each Next loop repeats a block of statements for each object in collection. VBA
automatically sets the variable each time the loop runs.
General syntax of for each next loop

For Each Object/Property/Method in Method / Object / Property


------
Executable Statements
------
Next Method / Object / Property

Example of For each . Next loop

Sub ChangeCase()
For Each Cell In Selection
If Application.WorksheetFunction.CountBlank(Cell) = 0 Then
Cell.Value = UCase(Cell.Value)
End If
Next
End Sub

In the above example the CountBlank () function checks each cell in selection whether it is empty or
not if not then it converts the case of the text to upper case and the task is repeated for each cell in
selection.

Do-While Loops
A Do-While loop is another type of looping structure available in VBA. Unlike a For-Next loop, a Do-
While loop executes while a specified condition is met.
There are two forms of Do-While loop they are as follows

1)
Do While Condition
-------
Executable Statements
-------
Loop

2)
Do
--------
Executable Statements
--------
Loop While Condition

Note: In the first form of Do-While loop the condition is checked first and then the statements are
executed this is also called as Entry Control loop.

24
MsExcel VBA

Note: In the second form of Do-While loop once the statements are executed and then the condition
is checked this is also called as Exit Control loop.

The following example uses a Do-While loop with the first syntax

Sub DoWhileLoop ()

Do While IsEmpty(ActiveCell)
ActiveCell.Value = 0
ActiveCell.Offset(1, 0).Select
Loop

End Sub

The above procedure uses the active cell as the starting point and then travels down the column,
inserting a zero into the active cell. Each time the loop repeats, the next cell in the column becomes
the active cell. The loop continues until VBAs IsEmpty function determines that the active cell is not
empty.

25
MsExcel VBA

Built in functions in VBA

VBA provides many build in functions like String, Date/Time, Math, Input, Output etc. Few of them
which are used very frequently in day to day work are listed below.

InputBox Displays a dialog box for user input. Returns the information entered in the dialog box.
Use InputBox to display a simple dialog box so that you can enter information to be used in a macro.
The dialog box has an OK button and a Cancel button. If you choose the OK button, InputBox returns
the value entered in the dialog box. If you click the Cancel button, InputBox returns False.

General syntax of InputBox

VariableName = InputBox (Prompt, Title, Default Value)

Prompt is the message to be displayed to the user

Title Used to specify the title for the Inputbox

Default Value Specifies the value that will be displayed in the text box when the dialog box pops
up.

VariableName After entering the value in the box when you press OK button it is stored in the
variable.

26
MsExcel VBA

MsgBox Function

The MsgBox function is one of VBAs most useful functions. It is often used as a good substitute for
a simple custom dialog box. Its also an excellent debugging tool because you can insert MsgBox
function at any time to pause your code and to display the result of a calculation or assignment.

General syntax of MsgBox function

MsgBox (Prompt, VB-Button, Title)

Prompt Prompt is the message to be displayed to the user

VB-Button A value that specifies which buttons to appear in the message box, use built in
constants for example VBYesNo

Title Used to specify the title for the Msgbox

27
MsExcel VBA

String Functions

String functions are used for editing, manipulating and extracting textual data. Some of the very
frequently required string functions are as follows.

Ucase (String Expression) converts the string to upper case

Lcase (String Expression) converts the string to lower case

Strconv (String Expression, Conversion Factor) converts the string to upper / lower / proper case.

Conversion Factor 1 / 2 / 3

1 converts to upper case

2 converts to lower case

3 converts to proper case

Trim (String Expression) removes the redundant blank space before and after the string.

StrReverse (String Expression) reverses the string expression

Strcomp (String1, String2, Compare) Used for comparing two strings and returns a Integer
indicating the result of comparison.

Compare 0 / 1 (0 makes a binary comparison and 1 makes a textual comparison)

InStr (Start, String1, String2, Compare) returns the position of first occurrence one string within
another.

Left (String Expression, No of Chars) returns specified number of characters from left side of
string

Right (String Expression, No of Chars) returns specified number of characters from right side of
string

Mid (String Expression, Start, No of Chars) returns specified number of characters from the string
with given start point and length

Len (String Expression) returns length of string including blank space

Asc (Character) returns the ASCII code of the character

Chr (Code) returns the character at specified ASCII code

Val (String Expression) converts string to number

Str (Number) converts number to string

28
MsExcel VBA

InStrRev (Source String, String to search, Start, Compare) returns the position of character in
the string from end of string
Note: Specifying the start as -1 starts the search from end of string

Date Functions

Date functions are used for editing, manipulating and extracting date. Date is internally stored as
number starting from 1st Jan 1900 till 31st Dec 9999. Some of the very frequently required date
functions are as follows.

Date () Returns current system date

Time () Returns current system time

Month (date) Returns the month out of date

For e.g. Month (20-Sep-1978) returns 9

Day (date) Returns the day out of date

For e.g. Day (20-Sep-1978) returns 20

Year (date) Returns the year out of date

For e.g. Year (20-Sep-1978) returns 1978

29
MsExcel VBA

Creating Custom Menu / Toolbar (Excel 2003)

Excel allows us to create custom menu and toolbar and assign the procedures we have written in
VBA to them for easy access.

Following are the steps we should follow to create custom menu bar

1. Click on menu View Toolbars Customize This will pop-up the Customize dialog box as
shown below

2. Click on the Commands tab and under Categories choose New Menu
3. Drag and drop the New Menu option Under Commands: besides any of excels menus
4. Then right click mouse on the new menu and specify an appropriate name for the menu
5. Now for inserting commands in the new menu click on Macros option under Categories
6. This will show the Macro options as whown below in the diagram.
7.

30
MsExcel VBA

8. Drag and drop the Custom Menu Item from Commands: into the new menu created.
9. After dropping it right click mouse on it and rename as per requirement. And assign macro to
the new element by clicking on option Assing Macro
10. After clicking on Assign Macro option the Macro dialog box pops up select the macro name
you would like to assign and close the dialog box.
11. Repeat steps 8 to 9 untill you finish assigning the commands.

31
MsExcel VBA

Adding Icons on Quick Access Toolbar (Excel 2007/2010/2013)

Click on the drop down arrow on Quick Access Toolbar and Select More Commands as
shown below in the image

This will pop-up the Excel Options dialog box as shown below

under Choose commands from drop down choose Macros


Select Macro name and click on Add button to add in the Quick access toolbar and once done
click on Ok button to close the dialog box

32
MsExcel VBA

Creating own custom Tab on the Ribbon (Excel 2010 / 2013)

Click on the drop down arrow on Quick Access Toolbar and Select More Commands

OR

Click on File button and choose Options this will pop-up the Excel Options dialog
box as shown below

Choose Customize Ribbon on the left pane and under Choose commands from choose
Macros
Click on the New Tab button for creating a new tab and rename it by clicking on the
Rename button
Click on New Group button to create a new group and rename it by clicking on Rename
button
Select the Macro to populate in the group and click on the button Add>>
Once done click on OK button

33
MsExcel VBA

Excel (DOM) Objects and Properties

Chart Objects and Properties

Charts.Add Creates a New Chart of selected data

ActiveChart.HasDataTable Adds a Data table to the chart

ActiveChart.ApplyDataLabels Applies actual values on the chart

ActiveChart.ChartType Changes the chart type

ActiveChart.HasTitle Adds a Title for the chart

ActiveChart.ChartTitle.Text Used for specifying the Chart title text

ActiveChart.Axes(xlCategory/xlValue) Adds a Title for X and Y axis


Used for specifying the X and Y axis title
ActiveChart.Axes(xlCategory/xlValue).AxisTitle.Text
text
Charts.Visible=True/False Used for displaying or hiding chart
Used for moving the chart to desired
ActiveChart.Location
sheet
Used for selecting the data labels of a
ActiveChart.SeriesCollection(index).DataLabels.Select
series with specified index
ActiveChart.SeriesCollection(index).AxisGroup = Changes the selected series axis group to
xlSecondary Secondary axis
ActiveChart.SeriesCollection(index).ChartType =
Changes the chart type of selected series
xlLineMarkers

PageSetup Objects and Properties

PageSetup.Papersize Allows to set the papersize


Allows to set the orientation
PageSetup.Orientation
(xlLandscape/xlPortrait)
Used for setting the printing of Gridlines i.e.
PageSetup.PrintGridlines
True/False
PageSetup.LeftMargin=Application.inchestoPoints(0.5)

PageSetup.RightMargin=Application.inchestoPoints(0.5)
Used for setting the Left/Right/Top/Bottom
margins
PageSetup.TopMargin=Application.inchestoPoints(0.5)

PageSetup.BottomMargin=Application.inchestoPoints(0.5)

34
MsExcel VBA

For centring the data both vertically and


PageSetup.CenterVertically / CenterHorizontally
horizontally

ActiveSheet.PrintPreview For getting Print Preview


For taking print with the default printer
ActiveSheet.PrintOut
attached

Font Objects and Properties

Font.Name=Arial Changes the font of data

Font.Size=14 Changes the font size

Font.Color=vbRed Change the font color

Font.Bold / Italic=True Makes the font Bold / Italic

Characters Object

Characters (Start, No of Chars) Used for modifying characters in the string with specified Start
point and number of characters

PivotTable Object and Properties

Activeworkbook.PivotCaches.Create(xlDatabase, Allocates required memory in PivotCache


RangeName) with specified range

CreatePivotTable(Table Destination, PivotTable Creates a PivotTable in specified location


Name) and specifies name for the PivotTable

Used to specify the field name for creating


PivotFields(FieldName)
PivotTable

PivotField.Oreintation (xlRowField / xlColumnField Used to specify the field location i.e. in


/ xlDataField) Row/ Column / Value area

Used for changing the function of PivotTable


PivotField.Function=xLCount/xlSum etc.
field

35
MsExcel VBA

Shape / Picture Object and Properties

Shapes.AddPicture File Name, Link to File, Save with Document, Left, Top, Width, Height

DIR function: returns a string representing the name of a File, Directory or Folder that matches
a specified pattern or file attribute

DIR (Path Name, Attribute)

DIR (C:\MyData, \*.*)

36
MsExcel VBA

Cells, Worksheet, Workbook, Selection, Copy, Paste, Windows Objects and Properties

Cells.Select Selects all the cells in the Worksheet

Range(A:A).Select Selects the entire column A

Range(A:B).Select Selects column A and B

Range(A:B, D:E).Select Selects Columns A,B and D,E skipping column C

Range(A1:B20).Select Selects the cells from A1 to B20

Range(A1:B20,D1:E20).Select Selects the cells from A1 to B20 and D1 to E20

Range(D1).Select Selects only one single cell D1

Selection.Copy Copies the selected cell or cells

Sheets.Add Adds a new worksheet in the workbook

Workbooks.Add Creates a new file (Workbook)

ActiveSheet.Name=ABC Used for renaming the worksheet

ActiveSheet.Move After:=Sheets(SheetName) Used for moving the worksheet

Windows(Filename.Extension).Activate Used for moving in the files (Workbooks)

ActiveWorkbook.Close Used for closing the current Workbook

Workbooks.Close Closes all the open workbooks

Sheets(SheetName).Visible=True/False Used for Displaying / Hiding Sheet

ActiveWorkbook.SaveAs FilePath\FileName Saves the current workbook in specified path


Saves the workbook in already predefined
ActiveWorkbook.Save
path
Workbooks.Open FilePath\FileName Opens the workbook from specified path

ActiveSheet.Usedrange.Rows.Count Returns the last used Row in the sheet

ActiveSheet.Usedrange.Columns.Count Returns the last used Column in the sheet

Selection.Columns.AutoFit Adjusts the column width of cells

Selection.Rows.AutoFit Adjusts the Row height of cells

37

Você também pode gostar