VBA-Chapter 1 - Lecture Note

You might also like

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

City U Computer Programming for Construction

Chapter One

1.0 Introduction
1.1 What is a Macro?

A macro is a sequence of instructions that can be automatically executed in


order to automate frequent or complicated tasks. Macros are written in a
programming language called Visual Basic and can be created by recording a
task or by writing the Visual Basic program or by a combination of the two.

Macros can be added to menus, assigned to keys or buttons or made to run


automatically.

1.2 Recording a Macro

A macro can be easily created by instructing Excel to record a series of routine


actions. This is very useful for repetitive tasks.

To record a macro:

1. Choose Tools from the menu bar, then Macro, Record New Macro.

Page 1
City U Computer Programming for Construction

2. In the Macro name text box, type a name for the macro.

3. The macro name can contain letters, numbers and underscores; it must
begin with a letter. The name cannot contain spaces or punctuation marks.

4. Type a brief description of the macro in the Description box, Excel creates
its own default description.

5. To run the macro with a shortcut key type a letter in the Shortcut key box.
The shortcut will be assigned to [CTRL]+[letter]. Hold [SHIFT] while typing
the letter in the Shortcut key box to assign the shortcut to
[CTRL]+[SHIFT]+[letter].

6. Choose the OK button to start recording the macro.

7. The Stop Recording toolbar appears on the screen, and the


word Recording appears in the status bar.

8. Perform the actions that are to be recorded.

9. Click the Stop Recording button from the Stop Recording toolbar or
choose Tools, Macro, Stop Recording, when the macro is finished.

Page 2
City U Computer Programming for Construction

1.3 Running a Macro

To run a macro:

1. If a shortcut key was assigned to the macro, then press the shortcut key.
Or
1. Choose Tools, Macro, Macros or press [ALT]+[F8].

2. Type the macro name or select it from the list.

3. Choose the Run button.

Page 3
City U Computer Programming for Construction

To set the reference type:

When recording a macro, click the Relative References button on the Stop
Recording toolbar. By default, Excel records in absolute mode. Recording
can be switched from absolute to relative, and vice versa, during the same
recording process. This will be fully demonstrated in the following section.

1.4 Demonstration for Recording Macro

Let's say you have 400 rows of address data like that shown in the figure. The
name field is in column A, the street address in column B, and the city in
column C.
Your goal is to convert the data to a single column like that shown in the
second figure.
This simple problem will be used to illustrate how to record and then run a
simple macro.

Although there are 400 records in this worksheet, it is only need to record a
tiny bit of the macro that takes care of just the first address.

Procedure in Excel Operation and Record a Macro


The macro will assume that the cellpointer is on the first name. It will insert
three blank rows. It will copy the cell to the right of the original cell to the cell
underneath the original cell. It will copy the city cell to the cell 2 rows under
the original cell. It should then move the cell pointer down so it is on the next
name.
The key is to think this process out before you record it. Don't make a lot of
mistakes when recording the macro.

Page 4
City U Computer Programming for Construction

So, put your cell pointer in cell A1. Go to the menu and select Tools > Macro >
Record new Macro. The Record Macro dialog suggests a name of Macro1.
Change it to Exercise1. Use Relative References by clicking the right button.

Choose the relative cell

Step 1: Hit the down arrow once to move to cell B1.

Step 2: Hold down the shift key and hit the down arrow twice to select rows 2,
3, and 4.

Step3: From the menu, select Insert, then select Rows to insert three blank
rows.

Page 5
City U Computer Programming for Construction

Step 4: Hit the up arrow and then the right arrow to move to cell B2.

Step 5: Hit Ctrl X to cut cell B2. Hit the down arrow, the left arrow, then Ctrl V
to paste into cell A2.

Step 6: Hit up arrow, right arrow, right arrow, Ctrl X, left arrow, left arrow,
down arrow, down arrow, Ctrl V to move C1 to A3.

Page 6
City U Computer Programming for Construction

Step 7: Hit the down arrow twice so that the cell pointer is now on the next
name in Row A5.

Step 8: Click the "Stop Recording" icon on the toolbar to stop recording the
macro.

Now put the cell pointer in cell A5. Choose Tools > Macro > Macros >
Exercise1 > Run. The macro runs and your second address is formatted.

Page 7
City U Computer Programming for Construction

Record another macro with relative reference un-clicked and do the same
process. You will see the difference between results in running two different
macros.

1.5 Assigning Macros to Objects

A macro can be assigned to a menu item, a button or another graphic object


providing a simple and convenient way of running the macro.

1.5.1 Assigning a Macro to a Button on a Sheet

A button can be created on a worksheet and a macro assigned to it. The


macro will be available whenever the workbook is open.

To create a button on a sheet:

1. Choose Tools from the menu bar, then View, Toolbars and tick Forms.

1. Access the Forms toolbar

Choose the button tool

2. Choose the Button tool on the Forms toolbar. The mouse pointer is
replaced by a cross-hair.

Page 8
City U Computer Programming for Construction

3. Move the cross-hair to where the corner of the button should be.

4. Drag until the button is the correct size and shape and release the mouse
button. The Assign Macro dialog box appears:

5. Type the macro name or select it from the Macro Name list.

6. Choose the OK button.

To assign a new macro to the button:

1. Choose the Record button and follow the steps for recording a new macro.

To run the macro:

1. Click the button to which the macro is assigned.

To alter the text or appearance of a button:

1. Select the button by holding down [CTRL] and clicking the left mouse
button.

2. Alter the button text by typing new text.

3. Change the font or alignment of the button text by choosing Format


Control from the shortcut menu.

Page 9
City U Computer Programming for Construction

1.5.2 Assigning a Macro to a Drawn Object on a Sheet

Macros can be assigned to any worksheet object by choosing Assign Macro


from the object’s shortcut menu.

1.5.3 Assigning a Macro to a Button on a Toolbar

If a macro is assigned to a button on a toolbar, the macro is available at any


time and for every sheet in the workbook, provided the toolbar is displayed.

A macro is usually assigned to an unused custom button, but can be assigned


to a built in button overriding the button’s normal function.

Customising a Toolbar

Change, or customise, a toolbar so it contains buttons for most often used


commands or macros.

To add a button to the toolbar:

1. Choose the Commands tab of the Tools Customize dialog

2. From the Categories list box, select Macros.

Page 10
City U Computer Programming for Construction

3. Drag the Custom Button from the Commands list box over the toolbar
and then release the mouse.

4. To select a different button image for the new button, right-click the new
button and choose Change Button Image. Select a button image.

5. Choose the Close button.

Page 11
City U Computer Programming for Construction

Creating a Toolbar

Buttons can only be added to existing toolbars. It may be necessary to create


a new toolbar before adding a button to it.

To create a new toolbar:

1. Choose the Toolbars tab of Tools, Customize.

2. Click the New button and enter a name for the new toolbar.

3. Choose the OK button.

Button Image Editor

Excel is supplied with a small selection of “spare” button images. New button
images can be created by editing the existing images or by drawing new images.

To edit a button image:

1. Choose Tools, Customize.

2. Right-click the button image to be edited and choose Edit Button Image.

Page 12
City U Computer Programming for Construction

3. To edit the existing image, select a colour and fill the pixels of the image

4. To draw a new button image, choose the Clear button and then follow step
3.

Images can also be copied and pasted from other buttons or graphics
applications.

Page 13
City U Computer Programming for Construction

1.6 Introduction to Visual Basic Editor – Working Environment

1.6.1 Visual Basic Editor (VBE)

Excel 2003 is supplied with the Visual Basic Editor for modifying and creating
macros and for creating user defined forms.

Activate the VBE

Choose Tools, Macro, Visual Basic Editor or you may display the toolbar for
visual basic by choosing View, Visual Basic.

or

Choose the VBE

Page 14
City U Computer Programming for Construction

The Visual Basic Editor is common to all the Microsoft Office 2003
applications. To start with, the Visual Basic Editor contains two important
windows: the Project Explorer and the Code window.

Object List Box Procedure List Box


Lists objects associated Lists the procedures associated
with the selected project. with the selected object.

Project Explorer
Displays the list of
the open projects
and corresponding
modules, objects,
and forms, using
nodes to represent
each item type. Code Window
Displays the VBA
source code in the
selected module.
Properties Window
Displays properties
for the currently
selected object.

Project Explorer
The Project Explorer displays a hierarchical list of the projects and all of the
items contained in and referenced by each of the projects.

VBAProject

Excel opens a new VBA project for each workbook that opens in Excel. Each
project has three nodes containing project elements: Microsoft Excel Objects,
Forms and Modulus.

Microsoft Excel Objects

The worksheets and chart sheets contained in the VBAProject. The event
procedures for each sheet and the workbook are stored here.

Forms

This folder node displays only if you create custom forms for the specific
project. The will be explored in later chapter.

Page 15
City U Computer Programming for Construction

Modules

Modules contain general procedures, either functions or subroutines. Excel


creates a new module for a project each time you add a new macro to the
corresponding workbook. You can add other modules within the Visual Basic
Editor, as outlined later in this chapter.

Note:

The first time you record a macro, Excel creates a new module. Each time you
record an additional macro, Excel adds the new macro to the end of the same
module. When you close and reopen the workbook, the macro recorder stars
putting macros in a new module. There is no way for you to control where the
recorder puts a new macro.

Code Window

Use the Code window to write, display and edit Visual Basic code. Open as
many Code windows as there are modules; view the code in different forms or
modules and copy and paste between them.

Open a Code window from the Project window, by double-clicking a form or


module.

Drag selected text to:

• A different location in the current Code window.


• Another Code window.

Object Box

It displays the name of the selected object. Click the arrow to the right of the
list box to display a list of all objects associated with the form.

Procedures/Events Box

Lists all the events recognised by Visual Basic for a form or control displayed
in the Object box. When an event is selected, the event procedure associated
with that event name is displayed in the Code window.

Split Bar

Choose Window, Split. A split bar appears. Drag the Split bar down, splits the
Code window into two horizontal panes, each of which scrolls separately.
View different parts of code at the same time. The information that appears in
the Object box and Procedures/Events box applies to the code in the pane
that has the focus.

Page 16
City U Computer Programming for Construction

Margin Indicator Bar

There is a grey area on the left side of the Code window, where margin
indicators are displayed. Margin indicators provide visual cues during code
editing.

1.6.2 Set Properties for a Project

Excel considers each open workbook a project when you access the Visual
Basic Editor. By default, the Visual Basic Editor gives each project the name
of VBA Project (WorkbookName), but you can customize the name of the
project, if desired, within the Visual Basic Editor

If you plan to distribute your workbook to other users, you may want to
consider password protecting your projects. If a project is password protected,
the user must specify the password in order to view or modify any portion of
the project.

Page 17
City U Computer Programming for Construction

1.6.3 Add a New Module

You can create new code module directly within the Visual Basic Editor. VBA
uses modules to store variable declarations and all procedures, including
functions and subroutines.

After creating a module, you can create a subroutine within the module and
add the desired code so that the Macro dialog box lists your macro within
Excel.

Procedures

A procedure is a series of statements of Visual Basic code stored in a module


of a Visual Basic project. When a macro is recorded, Excel writes a
procedure. The code can be modified and special Visual Basic commands
can be included to allow user interaction, conditional testing, looping and other
options.

Each procedure is identified by a name that is written at the top of the


procedure.

There are two types of procedures, Sub procedures and Function procedures.

Page 18
City U Computer Programming for Construction

Sub Procedures

Sub procedures perform actions. A macro is a recorded Sub procedure. A


Sub procedure is enclosed by Sub and End Sub statements, the Sub
statement contains the macro name:

Sub Macro1 ()
Commands
End Sub

The macro name is followed by brackets. The brackets may contain variable
data called arguments.

Add New Macro in Module

Add a new module and type the following code in the module. This creates a
new macro with name “Display” in the wordbook.

Access the macro by choosing Tools, Macro, Run Macro. The new macro
“Display” will appear in the list.

Run the macro

Edit content of
macro

Page 19
City U Computer Programming for Construction

You may run the macro by choosing Run. You may edit the content of the
macro by choosing Edit.

Inserting Comments

It is very important to put explanatory comments into a macro as it will make


the macro easier to read and debug. Comment text can be placed in a line on
its own or following a macro statement.

Comment text is prefixed by an apostrophe. The apostrophe tells Visual


Basic to ignore the text that follows it and to continue execution with the
statement on the next line. Comment text normally appears in a green font,
but this style can be altered.

Printing a Visual Basic Module

To print the contents of a Visual Basic module:

1. Display the Visual Basic module that is to be printed.

2. Choose File Print.

3. Set the required print options.

Page 20
City U Computer Programming for Construction

1.7 The Range Object

Introduction

A range object can consist of:

1. A cell.

2. One or more selections of cells.

3. A row or column.

Working with range objects is fundamental to most Excel macros. There are
several important methods and properties for controlling a range object.

Page 21
City U Computer Programming for Construction

1.7.1 Cells Method

The Cells method returns a single cell. All cells are numbered on a worksheet
from left to right, top to bottom. A cell can be specified by its row and column
index. Cells(1) can also be referred to as Cells(1,1) and Cells(4194304) can
be referred to as Cells(16384,256).

1.7.2 Range Method

The range method returns a rectangular range or cells. The range can be
specified by a text string that is a cell address or a defined range name or it
can be specified with the Cells method.

Selecting Range Objects

Range objects are selected using the Select method:

Range(“A1:B2”).Select
Range(Cells(1,1),Cells(2,2)).Select

Multiple selections using the cell method must also use the union method.

1.7.3 Offset Method

Range object has an Offset property that can be very handy when one wants
to move the active cell around. The following examples demonstrate how the
Offset property can be implemented (assume the current cell before the move
is E5):

Page 22
City U Computer Programming for Construction

ActiveCell.Offset(1,0) = 1 Place a "1" one row under E5 (on E6)

ActiveCell.Offset(0,1) = 1 Place a "1" one column to the right of

E5 (on F5)

ActiveCell.Offset(0,-3) = 1 Place a "1" three columns to the left

of E5 (on B5)

1.7.4 Rows and Columns Methods

This returns a single row or column or a collection of rows and columns.

Rows(3).Delete Deletes the third row.


Columns(3).Delete Deletes the third column
Selection.Row Retures the row number of selected cell
Selection.column Returns the column number of selected
cell
Selection.Columns.Count Returns the number of columns in the
current selection
Selection.Rows.Count Returns the number of rows in the
Current selection

Page 23
City U Computer Programming for Construction

1.8 Variables

A variable is a piece of information that is stored while a procedure is running.


Once the information has been stored the variable can be referred to many
times within the procedure. Each variable in a procedure is referred to by a
unique name.

1.8.1 Declaring Variables

Variables that are to be used in a procedure are usually declared at the start
of that procedure in order to identify them and the type of data that they will
hold.

In Visual Basic it is not necessary to declare variables, but by doing so it is


possible to speed up the procedure, conserve memory and prevent errors
from occurring.

As variables do not have to be declared, Visual Basic assumes any variable


that has not yet been used to be a new variable. This means that a mis-spelt
variable name will not be recognised as such by Visual Basic.

This problem can be avoided by choosing to explicitly declare every variable.


This tells Visual Basic that every variable will be declared in advance and any
others used are therefore wrong. When Visual Basic encounters an
undeclared variable the following message is displayed:

To do this the following statement must be placed at the top of the Visual
Basic module:

Option Explicit

Variables are then declared using the Dim statement:

Dim variablename

The variable exists until the end of the procedure is met.

To save time, the Option Explicit setting can be automatically set in all
modules.

Page 24
City U Computer Programming for Construction

To insert Option Explicit automatically in all new modules:

1. In the Visual Basic Editor, choose Tools ,Options.

2. Select the Editor tab.

3. Select Require Variable Declaration.

4. Choose the OK button.

This command does not add “Option Explicit” to existing modules, only to new
ones.

It is possible to declare variables without using Option Explicit. However,


Visual Basic does not then notify any undeclared variables.

1.8.2 Local, Module-Level and Public Variables

A local variable is declared within a procedure and is only available within that
procedure.

A module-level variable is available to all procedures in the module in which it


is declared, but not to any other modules. Module-level variables are created
by placing their Dim statements at the top of the module before the first
procedure.

A public variable is available to every procedure in every module. Public


variables are created by using the Public statement instead of the Dim
statement and placing the declarations at the top of a module before the first
procedure.

To conserve memory, declare variables at the lowest level possible, e.g. do


not declare a variable as public or module-level if local is sufficient.

Naming Variables

Objects should be named without underscores, hyphens or other unusual


characters such as )(/?\[ ] {+=}. A mixture of different letter case should be
used to show word breaks such as JobNumber. Names that will conflict with
Visual Basic properties or keywords such as “Name”, “Caption” and “Size”
should be avoided.

1.8.3 Data Types

The data type of a variable determines what type of data the variable can hold.
For example a variable could hold an integer, a string or a date.

The data type is specified in the Dim statement:

Page 25
City U Computer Programming for Construction

Dim variable As type

If no type is specified the variable will be given the Variant data type.

Specific Data Types

If a specific data type is assigned to a variable, the variable will only be able to
hold that type of data. This can make a procedure easier to write and decode
as it will always be known what the restrictions are for that variable.

Numeric Data

There are several different data types that can be specified to hold numeric
data: Integer, Long, Single, Double and Currency.

Integer and Long variables hold whole numbers.

Integer variables can hold values between -32,768 and 32,767.

Long variables can hold values between 2,147,483,648 and 2,147,483,647.

Integers store less memory than variants and operations can be performed
faster.

Single, Double and Currency variables can hold whole or part numbers.

Single and Double variables are held as floating point and are used for very
large or very small numbers. They have much larger ranges than currency
but may incur small rounding errors.

Single variables can hold values between -3.402823E38 and -1.401298E-45


for negative values and between 1.401298E-45 and 3.402823E38 for positive
values.

Double variables can hold values between -1.7200369313486232E308


and -4.94065645841247E-324 for negative values and between
4.94065645841247E-324 and 1.7200369313486232E308 for positive values.

Currency variables hold the data as fixed point. This provides complete
accuracy and is particularly useful for additions and subtractions but may not
be so efficient for multiplication and division involving very large or very small
numbers.

Currency variables can have up to 15 figures to the left of the decimal point,
and up to 4 figures to the right.

Currency variables can hold values between -922,337,203,685,477.5808 and


922,337,203,685,477.5808.

Page 26
City U Computer Programming for Construction

Date and Time

Dates and times are held in variables that are of Date type. They are held as
numbers. The number to the left of the decimal point represents the date and
the number to the right of the decimal point represents the time. Midnight is 0,
and midday is 0.5. Any recognisable literal date or time can be assigned to a
date variable, enclosed in # symbols.

For example:

Dim AnyDate As Date


AnyDate = #25/6/94 13:20#
AnyDate = #January 12, 1994 3:15am#
AnyDate = #15 March 1994#
AnyDate = #16:15#
Date variables can hold dates between January 1 0100 and December 31
9999, and times between 0:00:00 and 23:59:59.

Boolean

Boolean variables hold either True or False. This is useful when something
has only two possible values. Instead of testing for the specific values, the
Boolean variable can be set to true or false and it’s value tested at any
necessary point in the procedure.

Page 27
City U Computer Programming for Construction

1.8.4 Getting Values and Sending Values to a Worksheet

Range Contents

Data can be assigned to or returned from Range objects using one of the
properties: Value and Formula. In practice, the Value property can be used
for all assignments.

Value Property

Use the value property to assign or return text or numbers to or from a range.

Assign values to a range in worksheet:

Statement: Description
Range(“A1”).Value = “Ability” Assigns the text Ability to the cell A1.
ActiveCell.Value = “Ability” Assigns the text Ability to the active cell.
Range(“A1”).Value = 25 Assigns the number 25 to the cell A1.
Cells(1,1).Value = 25 Assigns the number 25 to the cell A1
Selection.Value = 10 Assigns the number 10 to each of the cells
in the current selection.
ActiveCell.Value = Range(“A1”).Value Returns the contents of cell A1 and
assigns it to the active cell.

Transfer values from worksheets cells to a procedure (variable):

Statement: Description
AnyVariable = ActiveCell.Value Returns the contents of the active cell to
the variable AnyVariable.
AnyVariable = Cells(1,1).Value Returns the contents of the cell A1 to the
variable AnyVariable.
AnyVariable = Range(“A1”).Value Returns the contents of the cell A1 to the
variable AnyVariable.

Formula Property

Use the Formula property to return a formula from a range. Use either the
Value or Formula property to assign a formula to a range.

Statement: Description
AnyVariable = ActiveCell.Formula Returns the formula in the active cell to the
variable AnyVariable.
Cells(1,3).Formula = “=sum(F1:F10)” Assign the formula sum(F1:F10) to the cell
C1

Note: if a cell contains a formula and it is returned with the value property then
the value of the formula is returned and not the formula itself.

Page 28
City U Computer Programming for Construction

1.9 Demonstration

Develop a VBA to solve the quadratic equation

ax2 + bx + c = 0

Input information:

The input shall be in worksheet with input of a, b and c

Process (Calculation in VBA):

Δ = b2 – 4ac

x1, x2 = (- b ± √Δ)/2a

Output

1.) Value ofΔ

2.) Value of Roots

Open a new workbook and follow the steps as follows:

Step 1: Choose Tools, Macro, Visual Basic Editor

Page 29
City U Computer Programming for Construction

Step 2: Choose insert, module

Step 3: Type “Sub Quad()” and click enter. It will show the following,

Step 4: Declare new variables a, b, c, d, x1 and x2

Page 30
City U Computer Programming for Construction

Step 5: Assign titles in the worksheet.

Step 6: Put “inputBox” to ask user for the values of a, b and c and assign the
values to the variables. Add comments at ends of statement.

Note: To attach a value behind a string, use the symbol “&”

Step 7: Enter the formula for solving the quadratic equations and display the
result of analysis.

Page 31
City U Computer Programming for Construction

Step 8: Assign the Macro “Quad” to a button

Step 9: Click the button to run the macro

Page 32
City U Computer Programming for Construction

Step 10: To make the result have a better look, we would bold the title and the
results. Also, the fonts will change to Arial.

The appearance will become:

Page 33
City U Computer Programming for Construction

The overall VBA program is as follows:

Page 34

You might also like