Macro Development Using: Excel
Macro Development Using: Excel
Macro Development
using
VBA
Marisa Dass
Computing Services
20 November, 2003
Acknowledgement
These notes are based upon course notes originally written by Fariborz
Kiannejad, Computing Services, Queen Mary, University of London
Table of Contents
INTRODUCTION ................................................................................................................................................ 1
WHAT IS A MACRO ............................................................................................................................................. 1
WHAT IS VBA.................................................................................................................................................... 1
VBA-RELATED TERMINOLOGY .......................................................................................................................... 1
CREATING A MACRO ...................................................................................................................................... 4
RECORDING A MACRO ........................................................................................................................................ 4
SPECIFYING WHERE TO STORE A MACRO ........................................................................................................... 4
RUNNING A MACRO ........................................................................................................................................ 5
APPENDIX A ..................................................................................................................................................... 27
SAMPLE CODE FOR EXERCISE 16...................................................................................................................... 27
SAMPLE CODE FOR EXERCISE 19 – WHILE…WEND ......................................................................................... 27
SAMPLE CODE FOR EXERCISE 19 – DO…WHILE .............................................................................................. 27
SAMPLE CODE FOR EXERCISE 20...................................................................................................................... 28
Introduction
What is a Macro
Excel is a powerful spreadsheet package containing many built-in functions as well as graphical data
presentation facilities. The built-in functions in Excel are generally sufficient in most cases. However,
Excel can also be used to automate tasks. In Excel, a macro is a module containing commands or
functions, that is a series of actions used to automate a task. This has the following advantages:
a) saving time in performing repeated actions;
b) reducing the possibility of introducing errors into the spreadsheet;
c) enabling users to perform complex operations in a single step.
For example, to calculate a monthly balance sheet for a company, or perform data analysis on
multiple sets of experimental results, one of the following methods can be adopted:
1. apply the functions, formulas etc. for each set of data independently,
2. record all the required actions (functions, formulas) in an independent module (a macro) and
apply this macro to any similar data set.
What is VBA
VBA corresponds to Visual Basic for Applications, and is a programming language developed by
Microsoft. Many Microsoft applications already use VBA, such as Access, Excel, Project, Word.
It is worth noting that:
! VBA is not the same as VB (Visual Basic). VB is a programming language that creates stand-
alone applications like Excel itself. VBA is embedded in another product, such as Excel.
Hence, VBA provides the basic functionality of VB for programming facilities within
Microsoft applications. Although VBA and VB have a lot in common, it is important to know
that they are different.
! VBA is a programming language (like Fortran, Basic C), but it also serves as a macro
language. Excel documentation refers to a program written in VBA and executed in Excel as a
macro.
! Prior to the introduction of VBA, Excel (versions 2.0, 3.0 and 4.0) used another development
language called XLM (Excel Macro Language). Later versions of Excel support both XLM
and VBA.
VBA-Related Terminology
Functions
A function is a procedure that performs one or more actions in a specific order and returns a single
value or an array of values.
For example, the following function (named “AddUp”) takes two arguments, adds them up and
returns a single value (the sum of the arguments):
Function AddUp(num1, num2)
AddUp = num1 + num2
End
Argument
An argument is a value that is passed to a function or a subroutine procedure. The procedure then uses
this value to perform its task. For instance, an argument can be a number, text, cell, references,
constants or even other functions. In the above example, the arguments are num 1 and num 2.
Subroutine
A subroutine is a procedure that performs a number of actions, including functions, on or with objects.
A subroutine, unlike a function, does not return values, but performs some action. VBA modules
consist of subroutine procedures.
Collection
Objects of the same type form a collection. For example, the worksheets collection consists of all the
worksheets in a workbook and the toolbar collection consists of all the objects in a toolbar.
Collections are themselves objects.
Reference to an object is made by specifying its position in the hierarchy, separated by dots. For
example, reference to a cell, A1, in Sheet1 of a given workbook, Book1, in an application would be as
follows:
Application.Workbooks(“Book1”).Worksheets(“Sheet1”).Range(“A1”)
! Active objects can be left out of the list. For example if Application and Workbook (Book1) are
active the list can be reduced to:
Worksheets(“Sheet1”).Range(“A1”)
Properties
A property is a setting for an object. For example, a range object can have such properties as value or
name. A chart object has such properties as type, has legend, etc.
A property of an object is referred to by combining the object’s name with the property’s name,
separated by a dot.
For example, Worksheets(“Sheet1”).Range(“A1”).Value, refers to the value property of Cell A1.
Exercise 1
Objective: To enter data and manually perform actions on the data in a worksheet.
1. Open Excel.
2. Enter the following data into Sheet 1:
10. Select Sheet 2, select cell B1 and paste the copied data
Edit ! Paste.
Recording a Macro
Before recording a macro, plan the actions which are to be recorded. Remember that recording a
macro will register every individual keystroke and mouse-click.
Exercise 2
Objectives: To record a macro which will:
i) copy the item and Euro value columns into a different sheet;
ii) format the relevant cells as currency , two decimal places with the sterling (£) or Euro
(€) symbol.
1. Clear the entire contents of sheet 2 – select the entire sheet then Edit ! Clear ! All.
2. Select cell A1 on sheet 2.
3. Select sheet 1.
4. Choose Tools ! Macro ! Record New Macro.
5. In the Record macro window, enter the macro name – CopyCurrency. Then click OK.
Running a Macro
To run an existing macro in Excel, select Tools ! Macro ! Macros, select the desired macro and
click Run.
Exercise 3
Objective: To run the CopyCurrency macro.
The macro begins with a Sub statement, followed by the macro name “CopyCurrency”; next are the
recorded actions, and the macro ends with an End Sub statement.
! Comments in a programming language are completely ignored by the program, and serve as an
explanation of the code.
Comment lines begin with an apostrophe ‘.
! By default, Excel adds the information typed in the Record – New – Macro sheet at the beginning
of the macro as comments.
Examine the code of the macro. Each line of code refers to one operation. The code can be edited by
typing directly in the Visual Basic window.
Exercise 4
Objectives: To edit the VBA code so that:
i) the macro always starts at cell A1;
ii) a message box appears asking for confirmation prior to running the macro.
1. Look at the existing code and add an appropriate line of code so that the macro starts in cell A1.
2. Type in the following code before the first line of code:
Answer = MsgBox(“Copy currency values to sheet 2?”, vbYesNo)
If Answer <>vbYes Then Exit Sub
3. Save the VBA code – File ! Save.
4. Close the Microsoft Visual basic window.
5. Clear sheet 2 and run the macro “CopyCurrency”.
Exercise 5
Objective: To write a macro to calculate the number of holidays left for each member of staff and the
cost if replaced by hourly staff.
3. Note that the Excel has created a new workbook to store the macro.
4. Starting at cell A3, enter the following data:
Staff 2 30 8
Staff 3 30 21
Staff 4 28 12
Staff 5 28 14
Sub Holidays()
'
' Holidays Macro
' Macro recorded 15/08/2003
'
'
ActiveCell.FormulaR1C1 = "=RC[-2]-RC[-1]"
Range("E2").Select
ActiveCell.FormulaR1C1 = "=RC[-2]*8*8.26"
Range("E2").Select
Selection.Style = "Currency"
End Sub
9. This code can be edited so that the cost is calculated for the appropriate staff member:
i) Replace the first occurrence of Range("E2").Select with ActiveCell.Next.Select
! This selects the cell immediately to the right of the active cell and is equivalent to using
the TAB key.
! Note: ActiveCell.FormulaR1C1 will return or set the value or formula of the currently selected
cell.
R[x]C[y] will select a cell x rows downward (or –x rows upward) and y columns to the
right (or –y columns to the left) of the currently selected cell.
Exercise 6
Objective: To assign a macro to a button on a toolbar.
3. Under Commands, click and drag the Custom Button icon, and position
the icon at the end of the Formatting toolbar.
4. Right-click the Custom Button icon which was positioned on the toolbar.
5. Type in the macro name Holidays leaving the & symbol in place.
6. Click on Assign Macro and select the macro to be assigned to this button – in this case, Holidays
– then click OK.
7. If desired, a different picture can be selected for the icon by clicking on Change Button Image.
8. Click the Close button in the Customize window.
9. Use this button to run the macro for the remaining staff members.
Exercise 7
Objective: To re-do Exercise 5 using the Offset property.
Sub HolidaysCost()
ActiveCell.FormulaR1C1 = "=RC[-2]-RC[-1]"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=RC[-2]*8*8.26"
ActiveCell.Select
Selection.Style = "Currency"
End Sub
Exercise 8
Objective: To step through the HolidaysCost macro.
This VBA module sheet is identical to the one that is opened by the macro recorder. A single VBA
module sheet can contain any number of subroutines, functions and declarations.
• This sheet behaves in almost the same was as a word-processing sheet.
• Text can be cut, copied and pasted.
• The layout of the text can be formatted using tabs.
A single VBA line can be as long as desired. However, it is better practise to make lines shorter and
joined with continuation marks “_“.
! This is another example of VBA code that cannot be recorded and can only be entered manually.
Exercise 9
Objective: To ask the user to input their name and then display the name in a message box.
2. On the third line of code “Enter Name” is the title of the input box and will be displayed at the top
of the input box. This is optional and if omitted, the default title is “Input”.
3. Save the macro with the name Ask Name in the ‘My Documents’ folder.
4. Run the macro: Run ! Run Sub/User Form F5.
5. If nothing is entered in the input box and the user clicks Cancel, a zero-length string ("") is
returned.
2. Open a Visual Basic Module window and type in the following code:
' This macro counts the number of occurrences of the word Liverpool from cells B2:B15
Sub CountData()
Range("A1").Select
ActiveCell.FormulaR1C1 = "=countif(R[1]C[1]:R[14]C[1], " & """" & "Liverpool" & """" & ")"
End Sub
Using Help
When using the Visual Basic Editor, help can be accessed at any time by pressing F1 or via the
menu: Help ! Microsoft Visual Basic Help. Help can be gained on the various commands and the
correct syntax.