You are on page 1of 28

Intro to VBA

Session-1&2b

Recording a macro
Writing simple VBA procedures
Creating event procedures
Assigning macros to Form Control objects in Excel

Recording Macros
Macros
• technically defined as units of VBA code
• can
– be thought of as a way to automate a series of actions in
a spreadsheet application
– either be created directly with VBA code in the VBE, or
recorded in Excel

To record a macro,
• firstly, know exactly the actions to perform, then
• use the Developer > Code > Record Macro
command on the Ribbon

2 2
1 of 28
1.1: Record a macro that copies and pastes data
A dealer wants to place the data highlighted in yellow
in a newspaper advertisement

3 3

Prepare: Review/ practice the steps that one


should take when recording the macro
Select
• the first three columns (Make, Model, and Year) of the Used
Cars table.
• while pressing the CTRL key, select the last column (Price)
Either right-click and choose Copy from the shortcut
menu, or
• use the shortcut key CTRL-C to copy the selected data
Place the cursor in the first cell of the Newspaper
Information table (cell C19)
Paste the data either by right-clicking and choosing
Paste from the shortcut menu, or
• by using the shortcut key CTRL-V
4 4
2 of 28
Recording the macro
Click on:
• Developer > Code >
Record Macro command
on the Ribbon

In the Record Macro


dialog box,
• Enter a name for the macro
– CarCopyPaste
• Define its location
– This Workbook
• Determine a shortcut keys
to associate with the macro

5 5

Stop and Play


Once recording begins, notice that the Record Macro
button transforms to a Stop Recording button
After finishing the steps needed to copy and paste the
information, stop recording
• Click on: Developer > Code > Stop Recording command

Once recorded, play the


macro to ensure it works
correctly
• Click on:
– Developer > Code > Macros
command.
• Select the macro from the list
and click Run
6 6
3 of 28
Result

7 7

Studying the VBA Code generated


during recording a macro
Helps us learn how to create a similar macro
directly from VBA by copying the code
generated

8 8
4 of 28
1.2
Sub Macro1()

End Sub

1.2 (revised)
Sub Macro1a()

9 End Sub

1.3
Sub Macro2()

End Sub
10
5 of 28
1.3 (revised)
Sub Macro2a()

End Sub

11

1.4
Sub Macro3()

End Sub

1.4 (revised)
Sub Macro3a()

End Sub
12
6 of 28
First Program.xlsx

13

First Program

14
7 of 28
First Program

15

First Program (Revised Version…)

16
8 of 28
A First Program (Revised Version…)

17

A First Program (Revised Version…)

18
9 of 28
Budget.xlsx

19

Format Currency by Using a Built-In Tool


Select cells D3:F4 on the Budget worksheet
• On the Home tab of the Ribbon, click the Number Format
arrow, and click Currency
Excel has two different types of formats that look like
currency (Currency Vs. Accounting Number Format button)
• The Currency format puts the currency symbol immediately
in front of the number.
– Unless doing specific accounting applications, the Currency format
is usually easier to read
• The Accounting format puts the currency symbol to the far
left of the cell.
– To use the Accounting Number Format button to apply an
Accounting format, click the arrow and choose one of the specific
currency types

In Excel 2007, even though the name on the Ribbon


button is Accounting Number Format, the default
format it applies is Currency.
20
10 of 28
Record a Macro to Format Currency
Budget.xlsx
On the Budget worksheet, select cells D7:F8
On the status bar, click the Record Macro button
Replace the default macro name with FormatCurrency, and
then click OK
Right-click in the selected range, and click Format Cells. If
necessary, click the Number tab in the Format Cells dialog box.
Select Currency from the Category list
Replace the value in the Decimal Places box with 0
Select Custom from the Category list, and look in the Type box
Click OK to format the selected cells as currency without
decimal places
On the status bar, click the Stop Recording button

21

Record a Macro to Merge Cells Vertically


Budget.xlsx
Rearrange your windows as necessary so that you can see
both the Module1 window and the Excel window
Select the range A15:A20, and then click the Record Macro
button
In the Record Macro dialog box, replace the default macro
name with SideBarHeading, replace the default description with
Merge and Rotate cells Vertically, and press Shift+S to set
Ctrl+Shift+S as the shortcut key
Click OK. In the module window, you can see that the recorder
immediately inserts the comment lines, the keyboard shortcut,
and the Sub and End Sub lines into the macro
Right-click the selection, and then click Format Cells
In the Format Cells dialog box on the Alignment tab, select the
Merge Cells check box, set the orientation to 90 degrees, and
click OK. The recorder inserts several lines into the macro all at
once
22 Click the Stop Recording button, and save the workbook
11 of 28
Budget.xlsx

23

Eliminate Unnecessary Lines from the Macro


Budget.xlsx

Sub SideBarHeading()
'
' SideBarHeading Macro
' Merge and Rotate cells Vertically
'
' Keyboard Shortcut: Ctrl+Shift+S
'
With Selection
.Orientation = 90
.MergeCells = True
End With
End Sub

24
12 of 28
Inventory.xlsx

25

Recording
a Macro

26
13 of 28
Saving
a Macro-
Enabled
Workbook

Running
a Macro

27

Editing
a Macro
in the VBE

28
14 of 28
Using Sort and Filter functions in VBA
By first recording a macro and then using the
generated VBA code to create similar macros

29 29

2: Miami Airport data, listing Flight Destinations,


Number of Stops, Class and Price
Filter this information
to do the following:
• View flights to Beijing
• View flights to Hong
Kong
• View all flights

Also sort the data by:


• Number of Stops
• Price

30 30
15 of 28
Filtering
Begin by recording three macros to filter the data for
specific flight destinations
To prepare for recording this macro, review the steps
that should be performed:
• Highlight the entire table (cells B3:E15)
• Select Data > Sort & Filter > Filter command on the Ribbon.
• Click on the filter drop-down button of the “Destination”
column.
• Select Beijing, Hong Kong, or All respectively from the filter
drop-down list:
– 1st Macro: “ViewBeijingFlights.”
– 2nd Macro: “ViewHongKongFlights”
– 3rd Macro: “ViewAllFlights”

31 31

Excel to VBE => VBA Code


Check the recorded macro to ensure it works
• View the code generated, in VBE

32 32
16 of 28
VBA Code
The first line of code for all three macros, Range(“B3:E15”)
• Select is an example of the Select Method for the Range Object

The second line of code, Selection.AutoFilter, uses the


Selection as the object and AutoFilter as the method.
• view a list of methods and properties associated with the
Selection object by typing Selection and a period

The third line of code, Selection.AutoFilter Field:=1,


Criteria1:=…, is an example of an argument of a method
• The Field is the column of data in the selected range that we
want to filter from
• The Criteria is the value of the filter drop-down arrow next to this
field

The last line of code selects a cell to de-highlight the data


33

3: Modifying coding redundancies


Delete the first Selection.AutoFilter statement
from each sub procedure

34
17 of 28
Record a macro to sort the data by
number of stops/ price
To prepare for recording a macro to sort the data
table, review the steps to be performed
• Highlight all data (B3:E15)
• Click on: Data > Sort & Filter > Sort command
• Specify the sorting criteria and order in the Sort dialog box
• SortByStops Macro:
– Select “Stops” from the “Sort by” list, select “Values” from the “Sort
on” list, and select “Largest to Smallest” from the “Order” list, then
press OK to close the Sort dialog box
• SortByPrice Macro:
– Select “Price” from the “Sort by” list, select “Values” from the “Sort
on” list, and select “Largest to Smallest” from the “Order” list, then
press OK to close the Sort dialog box
35 35

4: Test macros and view the code

36
18 of 28
VBA Code
The first line of code
• selects the range we are interested in sorting

The second line of code


• clears all the SortFields objects in the active worksheet

The third line of code


• creates a new sort field and returns a SortFields object

The forth line of code


• uses the With construct to set several properties of object
Sort

The last line of code


• selects a cell to de-highlight the data
37 37

5: In the Modified Code, the Key is specified by the


range name of the column that we are sorting by
The Order is specified by “xlAscending” or “xlDescending.”

38 38
19 of 28
6
Suppose that we also want to filter the Business or
Economy Class flights

39

Event Procedures connect events or actions


of an Excel object to a specific macro code
Click, Change, Activate
For each Excel object selected in the Project Explorer,
• there is a list of associated objects in a drop-down menu in
the upper-left hand corner of the Code Window

After selecting an object from this list,


• One can view corresponding events in the drop-down menu
in the upper-right hand corner of the Code Window.

40 40
20 of 28
Eg.: Activate event can be used on the
Workbook object
Once an object and event are selected, a sub
procedure will be initiated

41 41

Event Procedures (cont’d)


• Are just like a sub procedure, except that
– they are associated with a particular action of an Excel
object
• have the name structure object_event, while
– sub procedures can have almost any name
• are necessary when building user interfaces

Suppose we want to have some buttons on the


screen that will perform corresponding macros
when clicked
• first create a button and then use a Click event
procedure

42 42
21 of 28
Form and ActiveX Controls
To create a button in Excel, click on: Developer > Controls >
Insert drop-down list
Several objects can be placed on the spreadsheet:
• command buttons, scroll bars, list boxes, etc.

Choose the Command Button object by clicking on its icon at


the ActiveX Controls dialog box

43 43

Control Properties
Each control has its own set of modifiable properties
• Name
= name of the control, this will be used to identify it in VBA (ex: cmdButton)
• Caption
= text which appears on the control (ex:“Click Here”)

Its font, size, and color can also be changed from the list of
properties
While working with ActiveX Controls,
• the Developer > Controls > Design Mode button is activated

To view the Properties window,


• click on the Developer > Controls > Properties command

The Click event procedure can now be associated with this new
object by titling the sub procedure
• Sub cmdButton_Click()
44 44
22 of 28
Command Button
To add a command button to
perform one of the filtering
macros we previously wrote in
VBA and set the following
properties
For example:
• Name = cmdHongKong_Click()
• Caption = “View Hong Kong Flights”

45 45

Event Procedure for this button


Copy and paste the code for the macro to a new sub
procedure as follows

This title is automatically generated when we select


the command button cmdHongKong from the list of
objects and then select Click from the list of events
46 46
23 of 28
7
Return to Excel & test the functionality of the button
Make sure that we are no longer in Design View
• To activate or deactivate the Design View, click on
Developer > Controls > Design View command.

Click “View Hong Kong Flights” to see that the filtering


works correctly

47 47

8
Create similar Command
Buttons for the other macros
previously recorded
This time, use the Form Controls
listed on the Insert drop-down
dialog box
Click on the Button object, and
then click somewhere on the
spreadsheet
The Assign Macro dialog box
appears

48 48
24 of 28
9
Right-click on the Button to activate the shortcut menu. Use the
Edit Text option to edit the caption of this button
Select the Format Control… option on the shortcut menu to
modify the format of this Button

49

Assign a macro to each new button respectively

50 50
25 of 28
Summary
Macros are technically defined as units of VBA code.
Macros can either be created directly with VBA code in the
Visual Basic Editor, or recorded in Excel.
Steps to Record a Macro:
1. Click on: Developer tab > Code group > Record Macro button.
2. Perform a sequence of actions in Excel.
3. Click on: Developer tab > Code group > Stop Recording button.

Events are actions that can take place in the Excel window that
cause an action to occur in the VBA code
An event procedure is just like a sub procedure, except that it is
associated with a particular action of an Excel object
Creating buttons as a user interface can greatly aid a user
unfamiliar with macros to perform desired functions
51 51

Ex. 1.1

52
26 of 28
Ex. 1.2

53

Ex. 1.3

54
27 of 28
Thanks

55 55

28 of 28

You might also like