Excel3 macrosVB

You might also like

You are on page 1of 42

www.wisc.

edu/sts

Excel 3: Macros & VBA


Classroom Course Manual

Updated: 4-18-2012

Software Training for Students (STS)


University of Wisconsin-Madison

Excel 3: Macros & VBA

Introduction.......................................................................4
About this Class......................................................................... 4 Topics.......................................................................................... 4 Required Skills........................................................................... 5 Other requirements.................................................................. 5

Table of Contents

About Macros.....................................................................6
Using a keyboard shortcut....................................................... 6 Using a form.............................................................................. 8

VBA and the Visual Basic Editor........................................10


Opening the Visual Basic Editor.............................................. 10 The Visual Basic Editor Interface............................................. 12 Examining Macros.................................................................... 13

Recording Macros..............................................................16
Identifying Cells......................................................................... 16

Programming Basics.........................................................19
Examining and Cleaning Up Recorded Code......................... 19 The While Loop and Boolean Expressions.............................. 22 The If Statement........................................................................ 25 The For Loop.............................................................................. 26 The If-Else Statement................................................................ 28 The Select-Case Statement...................................................... 30 Finishing the Macro.................................................................. 32 Completed Macro Code............................................................ 35

Saving Macros & Add-ins..................................................36


Saving a Macro in a Workbook............................................... 36 Saving a Macro as an Add-in................................................... 37

VBA Quick Reference.........................................................42

University of Wisconsin Board of Regents, Software Training for Students

Excel 3: Macros & VBA

Introduction
Welcome to Excel 3: Macros & VBA! This course will build upon the skills you have learned in your previous experiences with Excel. After Excel 3, you will have learned the building blocks necessary to create macros which automate lengthy and tedious tasks in Excel.

About this Class


Excel 3 is the most advanced Excel course offered by STS. It is extensively focused on the programming environment that provides the user with control over all of Excels functions and commands.

Topics
About Macros VBA and the Visual Basic Editor Recording Macros Programming in VBA Saving Macros and Add-ins

Page 4

Software Training for Students (STS)

Excel 3: Macros & VBA

Required Skills
You should have a basic knowledge of the Windows environment and have firm understanding of all the basics of Excel. This understanding can be achieved through the completion of Excel 1 and our three Excel 2 courses or equivalent personal experience. Key background points include: Terminology: rows, columns, cells, cell names Proficiency in keyboarding skills Switching between multiple applications In addition, having some previous programming experience will help with the understanding of the programming concepts presented here but is not required.

Other requirements
In addition to this manual, you will also need the class files for the course and access to a computer with Microsoft Office 2010. The class files can be downloaded at our website www.wisc.edu/sts or can be provided by your instructor. If you are working on a different version of Office, you are welcome to try the exercises but some features may be located in a different location or not be available in your version. In that case, setting up a one-onone Ask a Trainer appointment with one of our trainers would be a good option to work through your specific questions. Microsoft Office is available in all the infolabs on campus and more information on the specific labs and software can be found at www.doit.wisc.edu/computerlabs.

Software Training for Students (STS)

Page 5

Excel 3: Macros & VBA

About Macros
Anyone who has used a computer program regularly has most likely learned keyboard shortcuts for their favorite commands. These help us save time on fairly basic operations such as copy (Control+C), paste (Control+V), and save (Control+S). Excel (and most other Microsoft Office products) lets us create our own shortcuts if we wish. These custom shortcuts are called Macros. A macro is a recorded set of steps that allows use to automate lengthy, menial , or common tasks. They can even be assigned to a keyboard shortcut.

Using a keyboard shortcut


In this example, we will see how macros can save us time and improve consistency once they have been created.

1.

Open the Macro-VBA Examples workbook from the class files

2. A security warning may appear saying that macros have been disabled. Click Enable Content to ensure that this workbook will function properly.
REMOVE WArNING IF
YO U W O U L D N OT

LiKE TO SEE THiS WA R N i N G A N Y M O R E , YO U C A N C H A N G E

The purpose of this warning is to let you know that there is a macro coded within this T H E D E FA U LT file. Macros are actually computer code that runs in the background of Excel and, if used S E C U R i T Y S E T T i N G S incorrectly, could cause problems. This warning is to make sure you expected there to iN THE TRUST be a macro in this file. If you expected a macro in this file, go ahead and click enable CENTER. THiS content. If you received this file from someone else and did not expect a macro to be in C A N B E A C C E S S E D iN THE EXCEL the file, you may not want to enable the content yet and instead check with the person OPTiONS FOUND you got the file from to figure out if the macro is necessary and safe to run.
ON THE

This workbook has four tabs known as worksheets. For this example, we be working with the Report worksheets.

F i L E TA B (ALSO KNOWN AS B A C K S TA G E V i E W ). ADD MORE TEXT

3. Examine the worksheets Report 1, Report 2, and Report 3 and notice the similarities and differences
In this example, you receive reports daily at your job with a summary of yesterdays employee hours. They come in a poorly formatted sheet as the person who sends them doesnt know Excel very well. It is your job to format these reports so they are presentable financial documents and to determine the total labor costs for that day.

Page 6

Software Training for Students (STS)

Excel 3: Macros & VBA

4.

Switch back to the Report 1 worksheet

5. Take a few minutes to format the report and calculate the total payment in a method you choose
Doing this one time does not seem like a big deal but having to do it everyday you work would get quite tedious and be a waste of time. Instead, a macro was recorded in this workbook to save you the busy work of updating the summary everyday. It was then set to the keyboard shortcut Control+Y.

6.

Press Control+Y to run the macro

The macro will run and the sheet will be updated with better formatting and calculation methods.

7. 8. 9.

Switch to Report 2 Press Control+Y to run the macro Switch to Report 3

10. Press Control+Y to run the macro Page 7

Software Training for Students (STS)

Excel 3: Macros & VBA 11. Compare the different worksheets


Notice how quickly the formatting was updated. This will save you time everyday when you receive this report. Also, the formatting is consistent between worksheets instead of you having to remember how you made the previous days worksheet look.

Using a form
In this example, we will see another shortcut called a User Form. The User Form is a graphical interface that can perform any operation that you code it to perform. Lets examine the use of a user form which calculates the area of a circle based on a radius.

1.

Switch to the VisualBasic worksheet

A userform was created in this workbook to save you the time of inserting an area formula for a circle. It was set to the keyboard shortcut Control+A.

2.

Press Control + A to launch the form

3. 4.

For the Radius field, enter a value of 1 Click the Calculate button

The form displays the value of the area(3.14159) in the area field and also in the designated cell in the worksheet (cell B2).

5.

Change the value for in the Radius field and again click Calculate

Notice how quick and easy it is to find the area for multiple values of the radius.

6.

Exit the form by clicking the Exit Button

Page 8

Software Training for Students (STS)

Excel 3: Macros & VBA


User forms can be very useful and as complex as necessary. In this simple example, it was seen how a form can be utilized to provide quick access to whatever it is programmed to do. This could be a functionality you would like Excel to have but is not easily available by default. Next, we will examine how these two examples actually perform the tasks we want them to by looking at the computer code which performs the operations.

Software Training for Students (STS)

Page 9

Excel 3: Macros & VBA

VBA and the Visual Basic Editor


The Microsoft Office Suite is written using a computer language known as Visual Basic. In most Office programs, there is a built-in program called the Visual Basic Editor which allows you to code your own customizations to Office applications using the Visual Basic for Applications(VBA) VBA I N programming language. OFFICE

Opening the Visual Basic Editor


The Visual Basic Editor allows you to actually view and change macros. There are two main ways to open it. The quickest way is accessing it from the tab where the current worksheet is named.

EXCEL, WORD, POWERPOiNT, P R O J E C T , O U T LO O K , I N F O P AT H , V i S i O , ONENOTE, AND ACCESS ALL SUPPORT VBA i N M i C R O S O F T O F F i C E 2010.

1. 2.

Right-click on the name of one of the worksheets Select View Code from the popup menu

The Visual Basic Editor will open in a separate window.

There is a second way to open the Visual Basic Editor by showing the Developer tab in Excel.

Page 10

Software Training for Students (STS)

Excel 3: Macros & VBA 3. 4. Close the Visual Basic Editor In Excel, click on the File tab to open Backstage View

5.

Click on Options button on the bottom of the menu to open the Excel Options dialog box

6. 7.

Select the Customize Ribbon button from the menu on the left In the box on the right side under Main Tabs, check the box for the Developer tab

Software Training for Students (STS)

Page 11

Excel 3: Macros & VBA 8. Then click OK to close Excel Options


Looking at the Ribbon, you will see that a new tab has been added with the name Developer. This tab provides easy access to the tools needed to customize Excel.

9.

Click on the Visual Basic button on the Developer tab to open the Visual Basic Editor

The Visual Basic Editor will open in a separate window as it did before.

The Visual Basic Editor Interface


The Visual Basic editor provides the basic coding interface necessary to do all customizations. It has plenty of advanced features to make coding and debugging easier. The basic interface features are explained here.

The Project Explorer: All macros and code created for use in Excel must be associated with a project. This area provides a navigational interface to open code for different Excel objects(worksheets or workbooks), forms, and modules. To open a coding window, double-click on the object in the Project Explorer.

The Property Window: All objects in the Project Explorer have certain properties associated with it which can be viewed and changed here. This is also used to view and change the properties associated with UserForm controls.

Page 12

Software Training for Students (STS)

Excel 3: Macros & VBA The Tool and Menu Bars: The tool bar contains quick shortcuts to many commonly used functions and commands. The menu bar contains all the commands that can be performed in the VB editor. These will be examined as needed.

The Workspace: The workspace is the large gray area in the center. This is where we can open code windows to view and edit our macros. The code windows can be minimized , maximized, and closed with the common three buttons in the upper right corner of the code windows.

Examining Macros
Now that the interface is understood, lets examine the two examples we used earlier.

1. In the Project Explorer, click on the plus sign next to the area project,and the Modules folder if they are not already expanded 2. Double-click on Module1 to open its code window

The code window for Module1 will open in the workspace.

3.

Scroll through the code and try to figure out what is going on

This is the entire program that ran when we used the shortcut Control + Y earlier to format the reports. The code runs line by line performing the requested formatting operations on the active worksheet.

Software Training for Students (STS)

Page 13

Excel 3: Macros & VBA


For example, look at lines 8 to 21. These format the heading Yesterdays Summary and merges the second row of cells together.
LINE NUMbErS YOU
C A N T E L L W H AT

L i N E O F CO D E YO U R C U R S O R i S AT B Y L O O K i N G AT T H E L A S T BOX iN THE TOOLBAR.

4. 5.

If not already expanded, click on the plus sign next to the Forms folder in the Project Explorer Double-click on frmFirst to open its UserForm window

This is the visual interface for creating forms. A toolbox will also appear in a separate window when the UserForm window is selected. The toolbox has all the controls necessary to create a user form. It is relatively intuitive to select these objects, add them to the form, and manipulate them. This process will not be covered.

Page 14

Software Training for Students (STS)

Excel 3: Macros & VBA 6. Right-click on the Calculate button and choose View Code

This is the code the runs when the Calculate button is activated. You should be able to recognize the formula for area (3.14*r2). The radius.Text and area.Text commands are referencing the numbers in the Radius and Area text boxes.

7. After you are done examining them and asking any questions, close the VB editor and exit from the Marco-VBA Examples file by clicking the smaller x in the upper right corner of Excel.

That brief tour of the Visual Basic Interface and example code has provided you with a working knowledge necessary to navigate all basic macro scenarios.

Software Training for Students (STS)

Page 15

Excel 3: Macros & VBA

Recording Macros
After seeing the hundreds of lines of code and seemingly complex syntax associated with the report macro example, you may be feeling overwhelmed and think you will never be able to make something that complicated. Dont fret, it is easier than it seems thanks to the Record Macro function. This allows you to record any clicks and changes you make to a spreadsheet and transposes it into VBA for you.

Project Description
1. Open the Gradebook.xlsm workbook from the class files
For the remainder of the course, imagine you are the instructor for a course that has just finished. At the beginning of the course, you promised the students that:
E N A bl E CONTENT A L LO W E XC E L
TO

If a student got a score greater than a 95% on a homework, you would upgrade their final grade to the next highest letter grade.

ENABLE CONTENT iF PROMPTED AGAiN.

If they got a 100% on the final, they would automatically receive an A in the course.

You have entered all of the students grades into an Excel worksheet and calculated their grades based upon a formula assigning a certain portion of weight to the homework average and each exam. You now need to go through the gradebook and check if they met either of the criteria for a grade adjustment.

Identifying Cells
First, you want to identify students who received a 100% on the final by applying some special formatting to the final exam grade. Lets record a macro the first time we format a cell so we can be consistent for all the other cells we apply formatting to.

1.

Locate and select the first cell that has a 100% on the final. This is cell L6

A lT . L O C AT I O N

2.

Go to the Developer tab and click the Record Macro button

T H E R E C O R D MACRO BUT TON


i S A L S O AvA i L A B L E ON THE

ViEW
DROP TA B i S

TA B U N D E R T H E

M A C R O S

DOWN MENU iF THE

D E v E L O P E R N O T vi S i B L E .

Page 16

Software Training for Students (STS)

Excel 3: Macros & VBA 3. Type in the following information:


SHOrTCUT KEYS WHEN
SELECTiNG A SHOR TCUT KEY, BE SURE NOT TO R E P L AC E O N E YO U C O M M O N LY U S E .

C T R L +E,J,M, O R Q D O N O T H Av E
D E FA U LT S A N D A R E O P E N F O R YO U R U S E .

4.

Click OK and do NOT click anything else.

Excel has now begun recording every action you take on your spreadsheet. Because of this, make sure you have a plan of what you want to do before you click anything or you could add unnecessary steps to your macro (which takes up extra memory). If you screw up while recording a macro, you can always stop, delete the macro, and try again. You can see Excel is recording by looking in the bottom left corner of the Excel window. There is a blue box that represents a stop button (like on a remote control). By hovering over this, the following text will appear: A macro is currently recording. Click to stop recording. We will click this once we have done everything we want to have our macro do.

While recording:

Normally:
A lT . L O C AT I O N T H E R E C O R D MACRO BUT TON ON T H E D E v E L O P E R
TA B H A S A L S O CHANGED TO A

5.

Go to the Home tab

Remember we already have cell L6 selected, so any changes we make will affect that cell.

6.

Click the Bold button on the Font palette

7. Click the Paint Bucket drop down arrow on the Font palette and select green

S T O P R E C O R D i N G
BUT TON AND CAN BE USED iNSTEAD OF THE STOP BUT TON ON SCREEN.

Software Training for Students (STS)

Page 17

Excel 3: Macros & VBA 8. Click the Stop button in the lower left corner to stop recording the macro
REMOVE MACrO TO
DELETE A MACRO,

Congratulations, you have just recorded your first macro! Lets test it out.

9.

Click on the next cell that has a 100% on the final, cell L22

10. Press Control+G


The macro will run and cell L22 will be formatted as green and bold.

S i M P LY C L i C K O N

M A C R O S O N T H E D E v E L O P E R TA B ,
HiGHLiGHT THE MAC R O YO U N O L O N G E R WA N T , A N D CLiCK THE DELETE BUT TON iN THE MACRO WiNDOW.

11. Select cell L26 12. Press Control+G


Cell L26 will be formatted as green and bold.

The macro worked and made the selected cells green and bold. This was a simple example demonstrates the power of being able to record macros. You dont have to know anything about VBA to make simple macros. Just simply use the Record Macro function.

Reset Formatting
Lets reset our worksheet for the next exercise where we will continue this example. A macro has already been recorded in this class file to erase any formatting and grade updates. It has been assigned to Ctrl+R.

1.

Press Control+R

It is as simple as that and we will be using it through the course. Watch the right margin in the manual for reminders on when to reset the worksheet by using this shortcut.

RESET F O r M AT REMEMBER TO USE T H E C T R L +R


MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

Page 18

Software Training for Students (STS)

Excel 3: Macros & VBA

Programming Basics
The VBA programming language is very similar to many other programming languages. VBA uses variables to store information, expressions to compare different things, and loops to repeat operations. As with all programming, syntax is very important so make sure you are entering things in the proper order. Also, VBA ignores white space in coding so we will be using tabs, blank lines, and comments to keep our code organized. In this section, we will construct an entire macro to automatically check and update the gradebook we used in the previous example. We will build upon the portion of the code we already recorded.

Examining and Cleaning Up Recorded Code


Using the record macro function is very convenient for basic operations. It is also useful for finding out what the proper syntax is for a command you dont know, such as formatting a cell a certain way.

1.

Open the VBA editor by opening the Developer tab and clicking Visual Basic

The VBA Editor will open. Close any windows that may be open in the workspace to make it easier for you to work.

2.

In the Project Explorer under Modules, double-click Module1

Software Training for Students (STS)

Page 19

Excel 3: Macros & VBA


The code window for our recorded macro will appear. Yours may look slightly different depending on the order of your clicks, that is ok.

The first line (Sub GradeCheck()) initializes the macro and last line(End Sub) ends the macro. All the relevant code of the macro comes between these two lines are indented for organization. This is an example how many lines in VBA come in pairs and act as containers to hold other code. Both lines are necessary for any macro and are rarely changed. The different colored text in the window serves no functional purpose other than to help you identify different parts of the code. VBA keywords are blue, comments are green, errors are red, and all other code is black. The text is colored automatically and consistently for you. As stated, the green lines of code are comments. A comment is something that VBA completely ignores when it runs the code. It is only there for the programmers reference. It is good programming practice to comment your code as much as possible. This includes a header which explains what the code does in general and individual comments for sections or lines of code. Any text on the same line that follows the apostrophe character () will be made a comment. The remaining code is the changes Excel believed we made to our selection while we were recording a macro. Remember, the purpose of this macro was to turn the selected cell green and bold. This should only require two lines of actual code.
COMMENT YOUrSElF COMMENTS
ARE

v E R Y i M P O R TA N T B U T H Av E B E E N E X C L U D E D F O R T H E M O S T PA R T FROM SCREENSHOTS i N T H i S MA N UA L .

THiS

i S T O S Av E

S PA C E A N D M A K E THE CODE EASiER F O R YO U TO R E A D .

3.

Examine the code and try to identify the two relevant lines of code

The line that bolds the selection is: Selection.Font.Bold = True

COMMENTED iN

COPY OF THE CODE i S AvA i L A B L E THE CLASS FiLE

The line that fills the selection green is: .Color = 5287936

G R A D E B O O K ( C O M P L E T E ). X L S M .

Now we can erase some of the extra lines to make our macro more simple. The line of code to bold the selection looks like a complete statement and will be able to run on its own. Yet, the line of code to color the selection is preceded by a period, known as the dot operator. The dot operator is used to refer to a preceding

Page 20

Software Training for Students (STS)

Excel 3: Macros & VBA


object. For example, in making the text bold, Bold is a property of the Font of the Selection. So, we can not allow the .Color line to be on its own or we will receive an error. The color code is embedded inside a With statement, identified by the line being tabbed in further. The With statement allows a number of dot operator statements to be performed on a single object; here the object is Selection.Interior. Knowing this, lets delete some lines of unnecessary code.

4.

Delete the unnecessary code from the macro

The code should end up looking like the following:

Lets test the code to make sure it still works.

5.

Go back to Excel and select a cell with 100%


RESET F O r M AT REMEMBER TO USE T H E C T R L +R
MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

6. Press Control+G
The macro still worked just the same so we know we didnt erase any important code. Lets optimize this code in one more way by using the With statement.

7.

Combine the Bold and Color commands into the same With statement

Software Training for Students (STS)

Page 21

Excel 3: Macros & VBA 8. Go back to Excel and test to see if the macro still works
RESET F O r M AT

The macro still works in its simplified version. This shows how recording simple macros can be a useful to find out the syntax for commands that you want to use for more R E M E M B E R T O U S E T H E C T R L +R complicated macros you will be coding.
F O R M AT T i N G F O R

MACRO TO RESE T THE FUTURE TESTiNG.

The While Loop and Boolean Expressions


1. 2. Switch back to the code window for Module1

If we want our macro to do the formatting for us, we will need it to do the selecting of the cell. First, we will make it go through every student to apply the green/bold formatting and give the student an A. We will add the logic later to have it only apply the changes for those that got a 100% on the final exam.

Type the following lines of code into the macro to create the iCurrentRow variable: Dim iCurrentRow As Integer TrY IT iCurrentRow = 4 YOUrSElF
WHENEvER
CODE iS PRESENTED iN THiS MA N UA L , YO U A R E F i R S T G iv E N T H E S Y N TA X F O R T H E LiNES AND THEN A SCREENSHOT OF WHERE THEY GO iN THE MACRO.

TRY

F i G U R i N G O U T i F YO U CAN PLACE THEM C O R R E C T LY B E F O R E L O O K i N G AT T H E SCREENSHOT.

These lines of code declare and initialize a variable. The first line is a declaration and sets an area in memory for the variable. The second line is an initialization which sets the original value of the variable. A variable is an object which stores some sort of information while the program is running. This information can be changed and updated throughout the run of the program. Here, we are keeping track of what row the program is looking at and will use this variable to reference the row. It will be incremented as the program moves to the next row. It will only be a whole number so it is declared as an integer. We have set it at a value of four as this is the first row in the spreadsheet with student information in it.

3. Type the following code into the macro to give the student an A and select the cell to format: Cells(iCurrentRow, O) = A Cells(iCurrentRow, L).Select Page 22 Software Training for Students (STS)

Excel 3: Macros & VBA


VBA REF SHEET THE
F i N A L PA G E

O F T H i S MA N UA L

VBA QUiCK REFERENCE


C O N TA i N S A S H E E T W i T H vA R i A B L E i N F O R M AT i O N AND THE COMMON S Y N TA X F O R A L L THE COMMANDS WE WiLL BE GOiNG THROUGH.

USE

THiS

AS A GUiDE WHiLE PROGRAMMiNG.

These two lines of code include one of the most common statements you will use while interfacing with Excel: the Cells statement. This code allows you to select or manipulate a specific cell in Excel by specifying the row and column indexes. In the first statement, we are inserting the letter A into Cell O4 (4 because that is the current value of iCurrentRow). The second line activates cell L4 so the formatting in the With statement can be applied. The problem with the code now is that if the macro is run, the formatting will only be applied the first student and then the macro is stopped. We need to utilize a programming structure called a loop to repeat the inputting and formatting operations.

4. Type the following code into the macro to create the While loop. While (Cells(iCurrentRow, B) <> ) iCurrentRow = iCurrentRow + 1 Wend

Software Training for Students (STS)

Page 23

Excel 3: Macros & VBA


The While loop repeats any code between While and Wend until the expression which immediately follows While (in parentheses) evaluates to false. This expression is called a Boolean expression which is a statement that evaluates to true or false. Boolean expressions use basic math operators to compare things. The operators commonly used in Boolean expressions are as follows:

> >= < <= <> OR

Greater than Greater than or equal to Less than Less than or equal to Does not equal Combine multiple expressions of which only one must be true

AND Combine multiple expressions that must be true

NOT() Reverses logic of statement inside the parentheses, i.e. True becomes False and False becomes True The Boolean expression used here (Cells(iCurrentRow, B) <> ) looks at every student ID number and evaluate to false when the cell is blank. Because every student has a student ID number, this means that the program will stop once it detects there are no more students listed. The other line is a basic mathematical statement that adds one to the value of iCurrentRow. This is called incrementing and is used to move the program on to the next row once it is done with the current row. This statement is very important as it presents infinite loops (see side note).
INFINITE LOOPS A
COMMON

PROGRAMMiNG F L AW T H AT S H O U L D B E Av O i D E D i S FORGE T TiNG TO iNCREMENT THE vA R i A B L E T H AT i S CO N T R O L L i N G YO U R LO O P .

5. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. 6. Switch back to Excel and test the macro by pressing Control+G

THiS

C R E AT E S

A N i N F i N i T E LO O P i N WHiCH THE PROGRAM WiLL NE vER STOP ON i T S O W N , P O S S i B LY LEADiNG TO A PROGRAM OR SYSTEM CRASH.

RESET F O r M AT

The program runs and highlights all the final exam grades in green and puts an A in the grade reported column. This is a completed step of our program and now we need to make it smart enough to only do this operation if a certain condition is true.

REMEMBER TO USE T H E C T R L +R
MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

Page 24

Software Training for Students (STS)

Excel 3: Macros & VBA

The If Statement
As seen with the While statement, Boolean expressions can be powerful tools in programming. They allow the computer to make a decision about whether something is true or false. We are going to build upon that using the If statement. The If statement allows us to run a section of code a single time only if a boolean expression is true. If the expression is false, the program will skip the section of code and continue after the End If line. We will use the If statement to check if the student got a 100% on the final and only apply the formatting and grade change if this is true.

1. 2.

Switch back to the code window for Module1 Type the following lines of code into the macro to create the If statement: If (Cells(iCurrentRow, L) = 100) Then End If

The If statement has three parts: the Boolean expression, the code that will run, and the End If. The Boolean expression evaluates as explained previously. Here it checks to see if the Cell in column L, the final grade, is equal to 100. Then, if that expression evaluates to true, the code between the If and End If will run. In this case, the code that runs gives the student an A and formats their final exam grade.

3. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. Software Training for Students (STS) Page 25

Excel 3: Macros & VBA 4. Switch back to Excel and test the macro by pressing Control+G

The program runs and highlights only the final exam grades that equal 100% and puts an A in the grade reported column. We have now completed the first portion of our macro to check our first grade criteria (if they get a 100% on the final, they get an A). This was accomplished by first recording an macro to get the code necessary for formatting. Next, we added a While statement which looped through every student. And finally, we added the logic to check if the student got a 100% by using the If statement. These few basic steps combined to make a macro that could make it much easier to check final exam grades if there are hundreds of students in a class.

RESET F O r M AT REMEMBER TO USE T H E C T R L +R


MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

The For Loop


Now we need to find out if the other students deserve to get their final grade bumped up one letter. For this part, we will look at each of the students homework grades to check and see if they got higher than a 95% on a homework assignment.

1. Switch back to the code window for Module1 2. Type the following lines of code into the macro to create the For loop and necessary variables: Page 26 Software Training for Students (STS)

Excel 3: Macros & VBA Dim iCounter As Integer Dim bGreaterThan95 As Boolean bGreaterThan95 = False For iCounter = 4 To 9 If (Cells(iCurrentRow, iCounter) > 95) Then bGreaterThan95 = True Exit For End If Next iCounter

OPTION EXPlICIT THE


FiST LiNE OF

CODE,

O P T i O N E X P L i C i T , H A S THiS

ALSO BEEN ADDED. LiNE iS NOT NECESSARY BUT iS GOOD PRAC TiCE WHEN USiNG vA R i A B L E S .

IT

F O R C E S YO U TO D E C L A R E A vA R i A B L E B E F O R E YO U U S E i T S O YO U D O N T A C C i D E N T LY M A K E A T Y P O A N D C R E AT E vA R i A B L E S Y O U DiDNT MEAN TO.

Two variables are declared to be used in this section. The iCounter variable is needed to keep track of which homework assignment the For loop is looking at and thus is an integer data type. It will be explained more in a moment. The bGreaterThan95 variable is a boolean type which means it can have a value of True or False. This value starts each search as false and is switched to true if we find that a student has a homework grade higher than 95%. The For statement has three parts: the counter expression, the code that will run, and the Next statement.

The first portion is the counter expression which determines how many times the loop will run. It contains the controlling variable, which is iCounter for our example. Here the loop is specified to run five times, from four to eight (4,5,6,7,8). This makes sense because there are five homework assignments.

Software Training for Students (STS)

Page 27

Excel 3: Macros & VBA


The code that will run fills in the next section and will run the number of times specified by the counter expression. This code contains an If statement to check and see if the homework assignment specified is greater than 95%. If this is true, it will change the bGreaterThan95 variable to true and force an early exit from the For loop. The final part is the Next statement. This is the closing line of the For statement and increments the loops controlling variable for the next iteration.

3. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. 4. Switch back to Excel and test the macro by pressing Control+G
The program runs and nothing appears to be different than what it did that last time we ran it. This is fine as we were only collecting information for the program and didnt output anything. We now need to use the information we found to decide what grade to give the students.
RESET F O r M AT REMEMBER TO USE T H E C T R L +R
MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

The If-Else Statement


1. Switch back to the code window for Module1

Now we will use the information obtained from the For loop. We will format the students reported grade (column O) orange if they have earned a grade adjustment. If they did not earn an adjustment, we will assign the same calculated grade (column N) to their final grade reported (column O).

2. Type the following lines of code into the macro to create the If-Else Statement: If (bGreaterThan95) Then Cells(iCurrentRow, O).Select With Selection.Interior .Color = 49407 Orange End With Else Cells(iCurrentRow, O) = Cells(iCurrentRow, N) End If

Page 28

Software Training for Students (STS)

Excel 3: Macros & VBA

The If-Else statement if very similar to the If statement we used earlier. The first part is identical to the If statement. It checks to see if a Boolean expression is true, and, it true, runs the first block of code. If the Boolean expression evaluates to false, it runs the block of code after the Else portion. The structure is completed with the End If line. In this example, we check to see if bGreaterThan95 is true, which means they have had a homework grade higher than 95% and have earned a grade adjustment. If this is true, we select their reported final grade and format it orange. If it is false, we set their final reported grade to be the same as their calculated grade. The If-Else statement is then ended with the End If line of code.

3. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. 4. Switch back to Excel and test the macro by pressing Control+G

Software Training for Students (STS)

Page 29

Excel 3: Macros & VBA

The program runs and some final grades are reported and the others are formatted orange. The cells formatted orange have earned a grade adjustment of a one letter increase. The other students did not earn any special grade adjustments and will receive their calculated final grade. If you look closely, you will notice there are some errors here. For example, if someone was already given an A because they got a 100% on the final exam, their grade still may have been highlighted for an increase adjustment. Also, if they didnt earn the adjustment, their final grade of an A may have been overridden by their calculated grade as in the fourth row from the bottom (Row 26). In addition, the program is only formatting the cell and leaving it blank if they deserved an increase in grade. We will take care of these issues with two more additions to our code.
RESET F O r M AT REMEMBER TO USE T H E C T R L +R
MACRO TO RESE T THE F O R M AT T i N G F O R FUTURE TESTiNG.

The Select-Case Statement


Now we will use a more complicated programming structure called the Select-Case statement. This will allow us to increase a students grade by one letter if they have earned it. It allows us to assign different values for discrete conditions.

1. Page 30

Switch back to the code window for Module1 Software Training for Students (STS)

Excel 3: Macros & VBA 2. Type the following lines of code into the macro to create the If-Else Statement: Select Case Cells(iCurrentRow, N).Value Case F Cells(iCurrentRow, O) = D Case D Cells(iCurrentRow, O) = C Case C Cells(iCurrentRow, O) = BC Case BC Cells(iCurrentRow, O) = B Case B Cells(iCurrentRow, O) = AB Case AB Cells(iCurrentRow, O) = A End Select

The Select Case statement allows us to respond differently depending on what a students current calculated grade is. The first line (Select Case Cells...) selects the specific students calculated grade. The statement then goes through each Case <letter> until it finds a Case where the <letter> equals the students calculated letter grade. It then runs the corresponding line of code which assigns a letter that is one level higher than the students calculated grade. The statement ends with the line End Select. This Select Case statement can be used for as many discrete Case conditions as necessary. We have purposely left out a Case A statement as a student cannot receive a higher grade than an A.

3. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. Software Training for Students (STS) Page 31

Excel 3: Macros & VBA 4. Switch back to Excel and test the macro by pressing Control+G

The program runs and we can see that we are getting closer to our final result. The RESET program correctly upgraded the students who received a grade higher than 95% on a F O r M AT homework. All we have left to fix is to assign final grades to the students who already have a calculated grade of an A. In addition, we still need to fix the bug in the program R E M E M B E R T O U S E that is overwriting those students grades that we have already assigned an A due to T H E C T R L +R receiving a 100% on the final. MACRO TO RESE T THE
F O R M AT T i N G F O R

Finishing the Macro


1. Switch back to the code window for Module1

FUTURE TESTiNG.

Were almost there. We only need to add a bit more logic to the program to make it function perfectly. To do this, we will add an If-Else statement that will only run the homework check portion if a student has not already received an A in the course.

Page 32

Software Training for Students (STS)

Excel 3: Macros & VBA 2. Type the following lines of code into the macro to finish the macro:
If (Cells(iCurrentRow, N) <> A And Cells(iCurrentRow, O) <> A) Then

Else Cells(iCurrentRow, O) = A End If

TrICkY In the If statement, we first check to see if the student did not earn an A in the LOGIC class in their original calculated grade (column N). We also check to make sure they did not get a grade increase due to receiving a 100% on the final by looking at the grade T H E lO G I C A l reported (column O) to make sure the program did not already assign an A there. If EXPrESSION USED IN both these statements are true, it means the student has not yet earned a grade of an A T H E I F S TAT E M E N T based on the criteria tested so far. This means they are eligible to be checked for a grade C A N b E V E r Y T r I C k Y increase due to a homework grade of greater than a 95%. T O U N D E r S TA N D AT

If the boolean expression in the If statement evaluates to false, this means the student has already earned an A in the course. The program then goes down to the Else statement and runs the code to give the student a final grade of an A.

FIrST.

TAkE

THE

TIME TO MAkE SENSE OF THIS EXPrESSION A N D U N D E r S TA N D w H Y I T w O rk S .

3. Examine the code you entered to make sure it makes sense. Go back over the explanations or ask a question if you are not sure of what is going on. 4. Switch back to Excel and run the macro by pressing Control+G

Software Training for Students (STS)

Page 33

Excel 3: Macros & VBA

The macro runs successfully! Go through each students grade and check to make sure the grade was found correctly. Here is a reviews of what the program does to help you check the solution:

Uses a While loop to go through and evaluate each student individually. This uses the iCurrentRow variable to keep track of what row it is at.

Uses a If statement to see if the student has a 100% on the final. If true, it assigns the student an A and formats the final exam grade green and bold. Uses a For loop to look at each homework score the student received. If they received a score greater than 95%, the variable bGreaterThan95 is changed to true. Uses an If-Else statement to determine if a student already has received an A or not. If the student has not, it runs the homework check code. If the student has, it assigns a final grade of an A Uses an If-Else statement to check the variable bGreaterThan95 to see if the students grade should be upgraded. If not, it assigns a final grade equal to the calculated grade. Uses a Select-Case statement to determine what letter grade a student should be upgraded to based upon their calculated grade.
With the use of some basic programming structures and knowledge of Excels Record Macro function, you were able to code a fairly complex program to check a gradebook. Now that this program is created, it could be used every time this class is offered to save the instructor time and avoid errors in grade calculations.

Page 34

Software Training for Students (STS)

Excel 3: Macros & VBA

Completed Macro Code


This is the complete code for the previous example and is here as a reference. Comments have been excluded to allow it to fit on one page.
TAkE IT WITH YOU AFTER
C L A S S , YO U

A R E W E LCO M E TO TA K E T H E S E F i L E S A LO N G W i T H YO U F O R YO U R E F E R E N C E .

FEEL

FREE TO PUT

THEM ON A FLASH D R iv E O R E M A i L T H E M TO YO U R S E L F .

THEY

ARE ALSO

AvA i L A B L E O N O U R WEBSiTE S T S ) A LO N G W i T H T H i S MA N UA L .

(WiSC.EDU/

Software Training for Students (STS)

Page 35

Excel 3: Macros & VBA

Saving Macros & Add-ins


Now that you have completed a macro, you need to be able to save it in order to use it again and again. There are multiple methods and formats to save macros and the choice of which one to use depends upon how the macro will be used in the future.

Saving a Macro in a Workbook


One way of saving macros is in a macro-enabled workbook. This is a special type of Excel file which allows you to preserve your code and move it around just like a normal file. The files we have been using throughout this class have actually been macro-enabled workbooks.

1.

In Excel, click on the File tab and then Save As

2.

In the Save As dialog box, drop down the Save as type menu

You will notice that there are many different file types that you can save you work as. Feel free to research about these on the internet if you are interested or ask your trainer.

3. Page 36

Select the Excel Macro-Enabled Workbook as the file type. Software Training for Students (STS)

Excel 3: Macros & VBA 4. Name the file GradebookCompletedExample or any other name you would like to assign 5. Click Save.
By saving a macro in a Macro-Enabled Workbook, you are able to run your macro whenever you have this file open. This is a good option when you are only going to be using the macro on a single file or only for a limited time but the macro will only be accessible from this file.
MArCOE N A bl E D A M A C R O -E N A B L E D WORKBOOK AS THE
FiLE EXTENSiON

. X L S M

C O M PA R E D

THE NORMAL WORKBOOK EXTENSiON OR

Saving a Macro as an Add-in

. X L S .

. X L S X

A more versatile way to save a macro is as an add-in. You can then load an add-in into Excel and run it on any Excel document you open. This is a much better option for something you will use on multiple files or many times in the future (such as on a daily basis). To save a macro as an add-in, the code will need to be self-sufficient. We will need to add some more code for it to work on its own.

1. 2.

Open the VBA editor by clicking on the worksheet name and selecting View Code Open the module titled xAddMenu by double-clicking its name in the Project Explorer

This code creates a drop down menu for our macro. It is fairly advanced and is supplied for you to save time. If you ever need to create a menu on your own, it is advised that you use this code as a guide to create it.

3.

Click in the xAddMenu code window and press Control+A to select all

The code is commented out so that it didnt run when we were previously testing. Lets uncomment the entire block of code.

Software Training for Students (STS)

Page 37

Excel 3: Macros & VBA 4. Right-click in the gray space to the right of the toolbar

5.

From the menu that pops up, click on Edit to add the Edit toolbar

6.

Click on the Uncomment Block button

The first comments on everything will go away. This will let the code run later.

7. 8. 9.

Press Control+X to cut the code Go back the Module1 code window Click after the final line of code (End Sub) and press enter a few times
IF

AUTOOPEN E rr O r ?
Y O U R E C E iv E A N

10. Press Control+V to paste the copied code

ERROR MESSAGE L AT E R W H i L E LOA D i N G T H E A D D iN, MAKE SURE YO U U S E D iNSTEAD OF

CUT COPY,

OTHER WiSE THERE M AY B E T W O C O P i E S T H AT C O N F L i C T .

Page 38

Software Training for Students (STS)

Excel 3: Macros & VBA


After the End Sub line of code for the GradeCheck macro, you will see the following:

11. Go back to Excel and click Save 12. Select the File tab and Save As 13. Select Excel Add-in as the file type 14. Name the file GradebookAddIn and save it to your desktop

You have now created your first Excel Add-in. This will allow us to use our macro from any workbook.

15. Save and close all Excel windows


This unloads all macros we have created. We will now load in our add-in so we can use the macro anytime.

16. Open Excel Software Training for Students (STS) Page 39

Excel 3: Macros & VBA 17. On the File tab, select Options 18. Click on Add-Ins 19. Select Go... on the bottom of the screen where it says Mange Excel Add-ins

20. In the add-ins window, select Browse...

21. Locate your add-in you saved on the desktop and open it
EXCEL

C r E AT E COPY?
M AY P R O M P T

YO U TO CO PY T H E ADD-iN THE TO THE

ADDiNS FOLDER. CLiCK YES TO DO THiS SO EXCEL CAN


FiLE iTSELF.

MANAGE THE SOURCE

IT

iS PUT iNTO THE F O L L O W i N G L O C AT i O N B Y D E FA U LT :

C:\ U S E R S \< U S E R _ N A M E >\A P P D ATA \ ROAMiNG\ M i C R O S O F T \A D D I N S

Page 40

Software Training for Students (STS)

Excel 3: Macros & VBA


The name of your add-in will now appear under the Add-Ins Available. Make sure the box next to it is checked.

22. Select OK

23. Close Excel


This allows the add-in to load. It will load every time you start Excel.

24. Open the Gradebook2.xlsx class file 25. Click on the Add-Ins tab

Notice that this tab was not there before.

26. Drop down the STS Custom Macros menu

27. Click Grade Check


The macro runs just as before. Also notice the Reset Gradebook macro is also available on this menu. Try using the keyboard shortcuts Control+G and Control+R and notice they work as well.

This course has provided you with the building blocks necessary to create macros in Excel. By utilizing the Record Macro function and the VBA Quick Reference sheet at the end of this manual, you should be well equipped to make many basic macros in Excel. When you feel ready to tackle more advanced programming, there are many great resources available online, just search VBA Excel 2010. Our Ask a Trainer appointments are also great resources for future questions in addition to our online video training through Lynda.com. These services and much more can be accessed via our website, wisc.edu/sts. Thanks for attending Excel 3: Macros & VBA . We hope to see you in future classes and Ask a Trainer sessions. All of these services can be accessed at our website, wisc.edu/sts.

Software Training for Students (STS)

Page 41

Excel 3: Macros & VBA

VBA Quick Reference


Variables: name and memory location for information storage
Integer: Long: Double: Boolean: String: Variant:
Dim iCounter As Integer Naming convention is for first letter of variable name to correspond to the variable type.

integer values between -32,768 and 32,767 integer values between -2,147,483,648 and 2,147,483,647 precision values with decimals from 1.8e308 to 4.9e-324 true or false values text values can hold any data type (the above and more)

Boolean Expression: statement that evaluates to true or false


AND, OR, NOT, >, <, >=, <=, <>

While Loop: code within loop runs until the expression evaluates to false
While( <Boolean expression> <any type of code> Wend

If Statement: code within loop runs (once) only if expression evaluates to true
If( <Boolean expression> ) Then <any type of code> End If

For Loop: runs a specified number of times (m n)

If-Else Statement: code within loop runs (once) only if expression evaluates to true, otherwise
the else code runs

Variable iCounter can have any name but the variable must be declared previously For iCounter = <n> To <m> <any type of code> Next iCounter

Select-Case Statement: allows assignment of different values to discrete conditions


Select Case <expression> Case <value> <assignment> Case <value> <assignment> <repeat as many as necessary> End Select

If( <Boolean expression> ) Then <any type of code> Else <any type of code> End If

Page 42

Software Training for Students (STS)

You might also like