computer science 127 - lab exercise 3 - okanagan college

16
Computer Science 127 - Lab Exercise 3 Excel Macros During this lab you will learn how to create and edit macros in Excel. Background What are macros? A macro is a series of commands/actions/tasks, which you specify, that an application (e.g. Excel) carries out automatically. Conceptually a macro is like a recording of actions you performed at the computer. The actions can then be played to repeat those actions that you recorded. How are macros created and where are they stored? Like UDFs, a macro can be created by typing the Visual Basic code for performing the actions of the macro into a Visual Basic Module. Visual Basic (VB) is the same programming language used to code UDFs. A VB Module is accessible through the VB Editor and stores the macro as text that you can modify as you did with UDFs. As we saw previously, the VB Editor has some built-in syntax checking features that will inform you of any syntax mistakes you make. Writing Visual Basic code can be tedious, especially if you are not a Visual Basic programmer. Excel has a feature, called a Macro Recorder, that allows you to create a macro by recording the actions that you want the macro to perform. Excel will write the Visual Basic code for you while the macro recorder is on. Most actions that you perform while the recorder is on will be captured and coded. Pre-Exercise Activity: Ensuring macros are enabled. Before we get started we need to make sure the Developer ribbon is visible and that macros are enabled on your system. The following actions will take care of this on your computer, for this session: Select the Edit Options buttong from the File menu: In the Excel Options dialog box, select Customize Ribbon from the left pane area and make sure the Developer checkbox is selected from the Main Tabs areaas shown below, and click OK. CoSc 127 Lab 3 1 of 16

Upload: others

Post on 13-Apr-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computer Science 127 - Lab Exercise 3 - Okanagan College

Computer Science 127 - Lab Exercise 3

Excel Macros

During this lab you will learn how to create and edit macros in Excel.

Background

What are macros?

A macro is a series of commands/actions/tasks, which you specify, that an application (e.g. Excel) carries out automatically. Conceptually a

macro is like a recording of actions you performed at the computer. The actions can then be played to repeat those actions that you recorded.

How are macros created and where are they stored?

Like UDFs, a macro can be created by typing the Visual Basic code for performing the actions of the macro into a Visual Basic Module. Visual

Basic (VB) is the same programming language used to code UDFs. A VB Module is accessible through the VB Editor and stores the macro as text

that you can modify as you did with UDFs. As we saw previously, the VB Editor has some built-in syntax checking features that will inform you

of any syntax mistakes you make.

Writing Visual Basic code can be tedious, especially if you are not a Visual Basic programmer. Excel has a feature, called a Macro Recorder,

that allows you to create a macro by recording the actions that you want the macro to perform. Excel will write the Visual Basic code for you

while the macro recorder is on. Most actions that you perform while the recorder is on will be captured and coded.

Pre-Exercise Activity: Ensuring macros are enabled.

Before we get started we need to make sure the Developer ribbon is visible and that macros are enabled on your system. The following actions

will take care of this on your computer, for this session:

Select the Edit Options buttong from the File menu:

In the Excel Options dialog box, select Customize Ribbon from the left pane area and make sure the Developer checkbox is selected from

the Main Tabs areaas shown below, and click OK.

CoSc 127 Lab 3 1 of 16

Page 2: Computer Science 127 - Lab Exercise 3 - Okanagan College

Next we will make sure macros are enabled as we have in previous weeks. Select Trust Center, then Trust Center Settings to open the

Trust Center dialog box. Then select Macro Settings and then enable all macros and check Trust access to the VBA project object

model. Click OK to close the Trust Center dialog box and then click OK again to close the Excel Options dialog box.Select Macro

Security from the Developer ribbon.

As macros present a security risk (since some viruses are written as macros in Visual Basic), we must tell Excel whether we want to allow

them to be executed. Generally, it is a good idea to keep macros disabled and get notification by Excel when it determines that a

spreadsheet contains a macro. That way, macros will not run automatically, and we can decide when to run them on a case-by-case basis.

Most of the time the macros in Excel files do something useful and are an important part of the spreadsheet.

You may need to close and re-open Excel to apply the settings changes.

We will have to redo the above steps next week, as these setting will return to their original settings when the computer is rebooted.

Exercise: Creating a macro to enter formated text into cell C4.

This exercise will demonstrate how we can automate a small set of actions into a macro. This exercise will show us the steps for:

Recording a macro.

Viewing code associated with the macro.

Running a macro.

Editing a macro.

The actions that we will record into a macro in this exercise are the following:

Make cell C3 the active cell.A.

Type “Parameter Summary”, and press enter.B.

Make C3 the active cell again (i.e. click cell C3, or cursor to it).C.

Choose 16 for the font size from the formatting toolbar (on the Home ribbon).D.

Click the Bold button.E.

On the Home ribbon click the Format menu and choose AutoFit Column Width.F.

Normally, the first thing that you do before recording a macro is, practice the actions that you want to perform. We will skip this step as the

actions we are performing are relatively simple.

Open an Excel workbook and save the file as a Macro-Enabled Workbook using Name-Lab3Ex1 as the filename. Use your first name and

last initial in place of Name. For example, I would save this file as AlanK-Lab3Ex1. Excel will automatically add the "xlsm" file extension.

1.

CoSc 127 Lab 3 2 of 16

Page 3: Computer Science 127 - Lab Exercise 3 - Okanagan College

Select Record Macro from the Developer ribbon.

The Record Macro dialog box opens. This allows you to indicate what name you would like to assign to your macro. Type a name for the

macro as I have, but use your own name. Note that you cannot include punctuation or spaces in the name of the macro.

2.

Click the OK button. The Record Macro dialog box will disappear and you will be left looking at your current worksheet. You should see

a Stop Recording button appear on the Developer ribbon (but don't click it at this time):

3.

The macro recorder is now turned on and will record every action that you perform. Perform steps A, B, C, D, E, and F indicated above.

The final step, clicking AutoFit Column Width, can be accessed on the Home ribbon from here:

4.

CoSc 127 Lab 3 3 of 16

Page 4: Computer Science 127 - Lab Exercise 3 - Okanagan College

After performing these steps, your worksheet will look like this:

Click the Stop Recording button (remember that it is on the Developer ribbon). This stops the macro from recording your actions. The

macro recorder has translated all of your actions into VB code and stored the instructions with your worksheet.

5.

Now let's take a look at the code that was created for the macro. Press alt-F11 to toggle to the VB Editor. Double-click Module1 in the

Project window to display the contents of Module1:

6.

CoSc 127 Lab 3 4 of 16

Page 5: Computer Science 127 - Lab Exercise 3 - Okanagan College

What appears is a set of over 20 lines of VB code. At first glance this code should look strange and very foreign. This code was written by

the macro recorder and represents the actions that you performed. If you examine the code, you will see there are a few things that appear

familiar. For example,"C3", the cell that we selected twice, appears twice; the text "Parameter Summary", which we typed as our second

action appears as the second line of the main block of code; the value 16 appears and is assigned to a variable called size (we changed the

font size to 16 as the fourth step). You can probably detect some meaning in the last few lines as well. Unfortunately, the macro recorder

often includes extra code that is unnecessary for the tasks that we want performed. I suppose that's a small price to pay for us not having to

write the VB code ourselves. Although the extra code that the macro recorder includes is always harmless, it makes reading macros a little

more difficult and it slows down the running of the macro.

A little later, we will learn how to edit this macro to eliminate some of the lines of code that are not necessary. However, as we are not VB

programmers we have to be careful when deleting lines.

Another thing to note in the above code is that the first line of the macro starts off with the VB keyword Sub followed by the name we

decided to assign to the macro. The keyword Sub means that the code enclosed (down to the End Sub line) is a subroutine, a block of

code that performs a task (but doesn't return a value like a UDF does).

Return to your worksheet by pressing alt-F11.7.

Let's try running our macro. In order to run the macro, it would be nice to start off with a clean worksheet - one in which cell C3 contains

no text or formats. So, insert a new sheet or click the Sheet 2 tab:

8.

CoSc 127 Lab 3 5 of 16

Page 6: Computer Science 127 - Lab Exercise 3 - Okanagan College

To run the macro, you will need to select Macro from the Developer ribbon to display the Macro dialog box. Select Macros...:

Note that in the future, you can press Alt+F8 instead of making these menu selections. You will next see the Macro dialog box appear:

9.

The Macro dialog box lists all the macros that are available to you. As there is only one macro created at this point, you do not have any

others from which to choose. Click the Run button to run your macro. After a moment, you will see that the actions that you performed

earlier are repeated, giving you a worksheet that looks identical to your original worksheet:

10.

CoSc 127 Lab 3 6 of 16

Page 7: Computer Science 127 - Lab Exercise 3 - Okanagan College

Return to the VB editor. Next we will try editing the VB code associated with the macro to eliminate as many of the unnecessary

statements as we can. Modify the code as shown below by adding an apostrophe to the beginning of the indicated lines of code.

Putting an apostrophe at the beginning of a line turns the line into a so-called comment line. A comment line is ignored by the VB

interpreter. In this case, it has the same effect as deleting the lines, but it has the benefit of allowing us to put the lines back if we need to

(by deleting the apostrophe). This is especially important because we are making our best guess at what lines can be deleted. After all, we

are not VB programmers, so we are not 100% certain that what we are doing is appropriate.

In the above example, those lines that appeared to not be important are the ones that have been commented out. All of the lines within the

With Selection.Font statement seem to be providing settings related to the appearance of a cell. However, the only line that matches

one of the actions we performed is the .Size = 16 line. As a result, we will leave that line alone (i.e. not comment it out). The other line

that we commented out is the Range("C3").Select line. As this line appeared once for each time that we selected cell C3, we can fairly

confidently assume that this is a VB statement for selecting a cell. If we wanted to select cell B7 we could probably use the statement

Range("B7").Select. Great! We just learned how to do something in VB without really knowing the details of the associated syntax.

Often, as long as you know the effect of a statement, you can use it. You don't need to know why it is structured the way it is. The reason

that we are commenting out the second Range("C3").Select line is because there is no code that suggests that another cell is selected, so

it seems reasonable that the current cell would still be C3, making the second statement redundant.

Although we think that our edits to the code will be appropriate, we should test it out.

11.

Return to your worksheet by pressing alt-F11.12.

CoSc 127 Lab 3 7 of 16

Page 8: Computer Science 127 - Lab Exercise 3 - Okanagan College

Let's try running our macro again now that many of the lines are effectively deleted. Insert a new sheet (shift-F11). You should be looking

at a clean worksheet.

13.

Press alt-F8 to open the Macro dialog box:14.

Click the Run button. Again, after a few moments you will see that this new sheet will look as expected:

Since our macro works, we can proceed to delete the lines we commented out.

15.

Return to the VB editor and delete the lines that we previously commented out:16.

CoSc 127 Lab 3 8 of 16

Page 9: Computer Science 127 - Lab Exercise 3 - Okanagan College

To verify that our deletion didn't change anything, you can try running th macro again.17.

Save your file.18.

Exercise: Using the macro recorder to create VB code that can be added to another macro.

After you create a macro, you may find that there are some other things that you would like your macro to do. In this situation, you have a couple

of options. The first option is to re-record your macro, and then clean it up again. The drawback to this is that the macro may have many tasks in

it which are relatively difficult to reproduce in one recording as mistakes are recorded as well. The second option is to add VB code to your

macro by editing the macro code. The drawback to this is that you don't know how to program in VB. However, even if we can't type out the VB

code for the actions that we want to add, we can get the macro recorder to write the code for us into a temporary macro. Then, we could just cut

and paste the new code into the original macro.

The second option described above is the technique that we will use as it ultimately makes the macro development process easier. In this

exercise, we will modify our macro to include actions for applying a cell border to the cells A3:E3.

Open your Excel workbook from the previous exercise (Name-Lab3Ex1).1.

Select Record Macro from the Developer ribbon. This will open the Record Macro dialog box. Replace the default name for the macro

with Temporary as shown below:

2.

Click OK. The macro recorder starts recording.3.

Select the range of cells A3:E3.4.

Select Thick Bottom Border from the Borders toolbar as shown:5.

CoSc 127 Lab 3 9 of 16

Page 10: Computer Science 127 - Lab Exercise 3 - Okanagan College

Click the Stop Recording button: The macro recorder stops recording your actions.6.

Now let's take a look at the code that was created for the Temporary macro. Press alt-F11 to toggle to the VB Editor and your new

macro. (Note that a new Module may have been created for your new macro. If so, double-click Module2 in the Project window to

display the contents of Module2):

7.

CoSc 127 Lab 3 10 of 16

Page 11: Computer Science 127 - Lab Exercise 3 - Okanagan College

You will see that a lot of code has been created for the two actions (selecting cells A3:E3 and selecting a thick bottom border). Much of

this code is not needed. Before moving to the next step, see if you can guess which lines are not necessary.

The lines of code that are needed are shown below. Edit your macro to eliminate the unnecessary lines.

Although we would not have been able to create these lines of code ourselves (again because we are not VB programmers) we can now cut

and paste these lines of code into other macros and know exactly what will happen - a thick bottom border will be applied to cells A3:E3.

8.

Select the VB code that we want to cut and paste:9.

Press ctrl-c to copy this text to the clipboard (or click the Copy button).10.

Display your first macro. (If you have it in another module, you will first need to double-click that module to select it.)11.

Immediately above the End Sub line of your NamesFirstMacro, insert a couple of blank lines as well as a line with the text " ' Code to

apply a border to cells A3:E3 " as shown below.

12.

CoSc 127 Lab 3 11 of 16

Page 12: Computer Science 127 - Lab Exercise 3 - Okanagan College

Make sure the cursor appears in the location shown above.

Now let's paste the code from the Temporary macro. Press ctrl-v to paste the code (or click the Paste button).13.

Let's try running the edited version of our macro. Again, in order to run the macro, we should start with a clean worksheet. So, insert a new

sheet (Shift-F11):

14.

CoSc 127 Lab 3 12 of 16

Page 13: Computer Science 127 - Lab Exercise 3 - Okanagan College

To run the macro, let's use the shortcut to open the Macro dialog box. Press Alt+F8 instead of making the menu selections. You will see

the Macro dialog box appear as before, but with the addition of the Temporary macro in the list of available macros.

Remember that we are not interested in the Temporary macro, as it was just created to generate the code that we wanted to augment our

main macro (NamesFirstMacro).

15.

Make sure that the NamesFirstMacro is the selected one and click the Run button. After a moment, you will see that the actions that you

performed originally as well as the new actions are performed. Deselect the range A3:E3 by selecting some random cell, so that you can

see that the border was applied.

16.

CoSc 127 Lab 3 13 of 16

Page 14: Computer Science 127 - Lab Exercise 3 - Okanagan College

Save your workbook.17.

You have just finished learning a powerful technique for building macros without having much knowledge of VB!

Practice Exercises

Create a macro that creates and formats a table as shown below. Be sure that the cell B5 is the active cell after you have completed the

macro. Try to eliminate all of the excess VB code from the macro. Have a competition with your neighbour to see who can reduce the size

of the code the most. Save your file as a Macro-Enabled workbook using the file name, NameLab3Exercises1.

1.

Create a macro that generates a formated chart out of data that is in the range B4:C12 as shown below. If you have time, again, try to

remove excess code.

Before running the macro:

2.

CoSc 127 Lab 3 14 of 16

Page 15: Computer Science 127 - Lab Exercise 3 - Okanagan College

After running the macro:

Submitting your Work

When you complete these exercises call your instructor over to check your work. If your instructor asks, submit your work using Blackboard's

email tool.

CoSc 127 Lab 3 15 of 16

Page 16: Computer Science 127 - Lab Exercise 3 - Okanagan College

CoSc 127 Lab 3 16 of 16