Professional Documents
Culture Documents
Excel3 macrosVB
Excel3 macrosVB
Excel3 macrosVB
edu/sts
Updated: 4-18-2012
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
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
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.
Topics
About Macros VBA and the Visual Basic Editor Recording Macros Programming in VBA Saving Macros and Add-ins
Page 4
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.
Page 5
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.
1.
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
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.
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
4.
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.
The macro will run and the sheet will be updated with better formatting and calculation methods.
7. 8. 9.
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.
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.
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.
Page 8
Page 9
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
There is a second way to open the Visual Basic Editor by showing the Developer tab in Excel.
Page 10
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
Page 11
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 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
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
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.
Page 13
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
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.
Page 15
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.
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.
ViEW
DROP TA B i S
TA B U N D E R T H E
M A C R O S
D E v E L O P E R N O T vi S i B L E .
Page 16
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.
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.
Remember we already have cell L6 selected, so any changes we make will affect that cell.
6.
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.
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
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.
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.
Page 18
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.
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.
Page 19
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
3.
Examine the code and try to identify the two relevant lines of code
COMMENTED iN
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
4.
5.
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
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
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
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)
O F T H i S MA N UA L
USE
THiS
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
Page 23
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
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
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
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.
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
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
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.
Page 27
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.
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
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
Page 29
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.
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
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
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
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
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
Page 33
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
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/
Page 35
1.
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
. 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.
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.
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
CUT COPY,
Page 38
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.
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
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
IT
Page 40
22. Select OK
24. Open the Gradebook2.xlsx class file 25. Click on the Add-Ins tab
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.
Page 41
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)
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
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
If( <Boolean expression> ) Then <any type of code> Else <any type of code> End If
Page 42