November 30, 2010 Excel VBA: An Introduction. For more info on Excel VBA My favorite Excel VBA book is on reserve, and is available as an electronic resource.
Published byModified over 3 years ago
Presentation on theme: "November 30, 2010 Excel VBA: An Introduction. For more info on Excel VBA My favorite Excel VBA book is on reserve, and is available as an electronic resource."— Presentation transcript:
For more info on Excel VBA My favorite Excel VBA book is on reserve, and is available as an electronic resource through Mirlyn: – Walkenbach, John. Excel 2007 power programming with VBA / by John Walkenbach. [Chichester : John Wiley, distributor], c2007. – Location: Art Architecture & Engineering Course Reserve - 2nd Floor HF 5548.4.M523 W34486 2007 (Full Mirlyn Record)(Full Mirlyn Record)
Absolute vs. Relative References Let’s make an addition table in Excel: I have created row and column headers of the numbers from 1 to 9 and added the formula “=A2+B1” into cell B2. Watch what happens when I copy and paste this formula to the rest of the cells:
Not the addition table I learned! What went wrong? Let’s look at the formula in cell C2:
B2+C1! For the addition table, it should be A2+C1. When I copied the formula from B2 (=A2+B1) and pasted it into C2, Excel used a relative reference, changing A2 to B2 to match the changed column (B to C). This is usually what we want when we copy and paste formulas, as shown in the following example:
Why relative references are the default In the example below, I copied the formula from cell D2 into cells D3 and D4. Excel changed the row number 2 from the original formula into 3 and 4 in the pasted version. In this case, it works: subtotal equals Price * Quantity in all rows. This is usually what we want, which is why this type of copy- paste is the default for Excel. These are called relative references, because the formula is adjusted relative to where it is pasted.
Absolute References In the addition table, however, we always want to add the number in the first row to the number in the first column. To do this, we use absolute references. In Excel, absolute references are created using the dollar sign ($). As we paste a formula into a new column, we still want the first number to come from column A. And when we paste a formula into a new row, we still want the second number added to come from row 1.
By changing the formula for cell B2 from “=A2+B1” to “=$A2+B$1”, we are saying… Don’t change the column (A) for the first number when you copy/paste this formula, and Don’t change the row (1) for the second number. Does this work?
It works! Note that the formula for J10 is now “=$A10+J$1” The column for the first number added is still A, and the row for the second number is still J.
A simpler absolute reference example I want to be able to apply a discount to the subtotals in column D. The discount goes in cell H1. From the formula in the middle, I don’t get any discount when I copy the formula, because the default relative references point to empty cells. Making the discount absolute to cell H1 (with “$” in front of both the row and column, makes the formula copy and paste properly.
Relative vs. Absolute Reference Summary By default, Excel creates relative references for formulas when you copy and paste them. You can override this behavior by putting a dollar sign in front of the row and/or column that you don’t want to change during copy/paste operations. Absolute reference formulas work just like relative reference formulas; The only difference comes when they are copied and pasted. If the row or column reference is absolute, it will not change no matter where it is copied and pasted to.
Macros Most Excel users’ first exposure to VBA comes when they try to record a macro. To a beginner, a macro is simply a set of recorded commands used to simplify repetitive commands. Technically, a macro is a subroutine that doesn’t take any parameters. Most macros start with the macro recorder; a tool in Excel which records your actions in performing a task. For simple, repetitive tasks, the macros created by the macro recorder may be enough. Power users, however, need to know how to edit and expand upon recorded macros to create truly powerful Excel applications.
Recording a Macro Developer Tab Record Macro Enter Name, Shortcut Key, and Description (if needed) Perform Excel tasks When done, go to Developer Tab, Stop Recording
Running the Macro Go to Developer Tab Macros Select Macro, click Run Or use the shortcut key
Editing Macros Macros are recorded in VBA code To find the code for a macro, go to Developer tab, Macros, select the macro, and click Edit. Or hit Alt+F11 to bring up the VB window, and search for the macro in the code. Recorded macros are limited in what they can do. Real power comes from using non-recordable VBA features like loops, if-thens, and select-cases.
Start by Recording, Then Edit Recording a macro gives you a big head start. You won’t know what Excel calls everything; the macro recorder does. The recorded macro gives you the names of all the objects and constants you may want to use.
Saving Workbooks with Macros If a workbook contains macros, it is saved with a different extension than if it isn’t. For Excel 2007, regular workbooks are saved with an “.xlsx” extension. Workbooks with macros use a “.xlsm” extension. If you try to save a workbook with macros, Excel will prompt you to save it in the “.xlsm” (macro-enabled) format.
VBA vs. VB.NET Excel and the other Office applications use Visual Basic for Applications (VBA). VBA is basically the same as Visual Basic 6, a version of Visual Basic introduced in 1998. VB.NET is what we have been using for this class. It was originally introduced in 2003, and has been updated a few times. We are using VB.NET 2008. There are numerous differences between the two languages internally; we’ll look mainly at the programming differences.
VBA is less picky VBA does not require that variables be declared or have specified data types. For example, you can just write a line of code that says x = 4 VBA will assume that x is a variable, and that it is an Integer because you have put one in it. If instead I had written x = “Four” VBA would assume that x is a String. VBA does automatic data type conversions without needing Cint, ToString, or other conversions. You might think that this would make it easier to write code in VBA, but there is a downside, which is…
VBA is less helpful Since VBA allows you to type so many different variations on code, it rarely knows when you are making a mistake. Therefore, there is almost no Intellisense in VBA; the code editor will not help you write the code. Because of this, it is very easy (too easy) to write bad code. When you write bad code in VB.NET, the compiler usually catches it before you try to run it, and will underline the offending code. In VBA, the bad code will run, causing runtime errors, or worse, logical errors (code that “works” but doesn’t do what you want it to). These are much harder to debug, especially since… The debugging tools in VBA are much less powerful. However, you can still use breakpoints, stepping through code, and watches.
VBA is less powerful Compare the toolbox in VBA to that in VB.NET: There are far more tools in the.NET toolbox, and they’re better tools, too!.NET contains hundreds of other Classes that are not available in VBA, such as the Generic.List.
Writing Functions in VBA In VB.NET, functions can return values in one of two ways: 1.Use the Return statement, or 2.Assign a value to the function’s name. In VBA, only the second method works— there is no Return statement. You must assign a value to a function’s name for it to return a value.
Parameters in VBA Subs and functions offer two ways to pass parameters: 1.In order. This is the only way to pass parameters in VB.NET. The order of the parameters passed must match the order declared in the sub or function header. For example, here’s a sub header: Sub DoSomething(x As Integer, y As Integer) And here’s the sub being called: DoSomething 4, 7 In the sub’s code, x will have the value of 4, and y will have the value of 7. – Note that the parameters for a subroutine call are NOT in parentheses in VBA. (For functions, you put the parameters in parentheses just like in VB.NET.)
Parameters in VBA You can also pass parameters specifically by name, ignoring order. For example, given the previous sub… Sub DoSomething(x As Integer, y As Integer) We can call it this way: DoSomething y := 4, x := 7 In this case, y will be 4 and x will be 7, ignoring the order of x and y in the sub’s declaration. Since VBA doesn’t offer much intellisense to help you remember the order of parameters, this “:=“ method can make your code more readable: DrawRectangle Width := 6, Height := 4
“Setting” object references VBA doesn’t generally allow shortcuts to object creation. In VB.NET, you can do this: Dim FSO As New System.IO.FileInfo(Filename) In VBA, you need to do this: Dim FSO As FileSystemObject Set FSO = New FileSystemObject Not only can you not combine the variable declaration with “New”, you must use the word “Set” whenever you are assigning a value to an object variable (any variable that isn’t of one of the simple built-in types like Integer, String, or Boolean).
So why use VBA? VBA is built in to Microsoft Office applications, and many other programs as well, such as AutoCAD and Corel Draw. Therefore, anyone who has one of these programs can write VBA code without having to purchase Visual Studio. In addition, it is tightly integrated with these programs, meaning that you can write macros and other code that can extend the functionality of the applications. In fact, the introduction of VBA in Excel is the main reason that Excel became the dominant spreadsheet program. In the early 1990’s, Excel’s competitors Lotus 1-2-3 and Borland Quattro Pro did not offer such powerful macro languages for their spreadsheets.
In many ways, they’re the same VBA code looks very much like VB.NET code. Most of the common code patterns that you have used in VB.NET work in VBA: – If Then – Select Case – Loops – Subs – Functions – Classes – Properties
Object Models VBA works with applications like Excel through something called an Object Model. Excel’s Object Model contains lots of Classes which encapsulate most of the features that you see in Excel: Workbooks, Worksheets, Cells, Ranges, Charts, Pivot Tables, and much more. The simplest way to determine the names of the objects in the Object Model is to record macros; that is, if you want to learn how to write VBA code that modifies charts, record a macro that modifies a chart, and examine its code.
VBA Resources There are many books available on using Excel VBA, and Excel in general. I strongly recommend the books written by John Walkenbach, several of which are available as online resources through Mirlyn. For VBA, search for Walkenbach’s “Excel 2007 Power Programming.” Don’t worry—you won’t need to read that book to do assignment 6. But if you find that you need to know more about Excel or VBA for a course or a job, Walkenbach’s books are excellent resources. There are other resources available in Ctools/Resources/Excel VBA Resources.
Demonstration Watch this demonstration: – I’ll display the Excel window on part of the screen, and the VB editor on the other part. – Now watch what happens when I record the macro: Module is added if there isn’t already one Sub is created in the module, with comments identifying it as a macro Every step I take recording the macro is added to the code Lots of extra code is generated
Notes on Macros Macros are subroutines (subs) They take no parameters; however, they can call subs or functions that do take parameters Even if you end up changing every line of code, it is usually easiest to start writing a macro by using the recorder.
Debugging a Macro Adding a breakpoint—click in the left margin; a red circle appears. When you run the macro, code execution will stop at the breakpoint. Hit the F8 key to step through the code line by line. This is fun to do if you arrange the Excel window and the VBA window side-by-side on the monitor!
The object browser When in the VBA window, hitting F2 will open up the object browser. Example: – Open the object browser. Where it says “ ”, change it to “Excel”. – Under Classes, scroll down to “Worksheet” – Check out the members of Worksheet: Cells, Columns, Rows, Name, etc.
Macros can do Anything! In Excel, at least All of Excel’s powerful features—charts, pivot tables, solver, and more—can be manipulated by macros. You can even use Excel VBA to write programs that have basically nothing to do with Excel (I’ll show you one on Thursday). Unfortunately, we don’t have time to learn about most of Excel VBA’s power in this class.
User-Defined Functions User-Defined Functions (UDF’s) are an easy and excellent use of VBA in Excel. Have you ever tried to enter a complicated formula into a cell in Excel? You combine typing with clicking on cells, and end up with a practically unreadable string of cell references and operators (+, *, etc.). UDF’s provide a much neater and simpler solution for those who know even a little bit of VB. I’ll refer to “Function Examples.xlsm” for this part of the lecture.
Spreadsheet Applications According to John Walkenbach*, a spreadsheet application is: – a spreadsheet file (or group of related files) that is designed so that someone other than the developer can perform useful work without extensive training. * Walkenbach, John. Excel 2007 power programming with VBA / by John Walkenbach. [Chichester : John Wiley, distributor], c2007. Page 98
Good Apps Also according to Walkenbach*, a good spreadsheet app has the following characteristics: – Enables the end user to perform a task that he/she wouldn’t be able to do otherwise. – Provides the appropriate solution to the problem. (In some cases, an Access database or a full-fledged VB program might be better than Excel VBA.) – It does what it is supposed to. – It produces accurate results without bugs. – It uses appropriate and efficient methods and algorithms. – It traps errors before the user is forced to deal with them. * Walkenbach, John. Excel 2007 power programming with VBA / by John Walkenbach. [Chichester : John Wiley, distributor], c2007. Page 98
Basic Spreadsheet Types* Quick-and-Dirty: Solve a simple problem in a few minutes. For Your Eyes Only: A more permanent spreadsheet, but used only by its creator: tax records, music collection, etc. Single-user application: Still used only by the developer, but uses many of Excel’s and VBA’s most powerful tools. Spaghetti app: A multi-user spreadsheet that has grown over time to the point where nobody really knows how it works. (Not recommended!) * Walkenbach, John. Excel 2007 power programming with VBA / by John Walkenbach. [Chichester : John Wiley, distributor], c2007. Pages 103-107
Spreadsheet Types (cont.) Utility Apps: Tools designed to extend Excel’s capabilities that can be widely used. Add-ins that contain functions: Excel’s answer to VB’s shared function classes (like the Math class). Putting all of a business’s frequently-used formulas into a single spreadsheet can simplify using them with any other spreadsheet. Single-block budgets: Maybe the most common type of spreadsheet—a single block of cells that performs budgetary or similar calculations (gradebooks?).
Spreadsheet Types (cont.) What-if models: Excel provides the means to quickly determine the “bottom line” when any number of inputs are being manipulated; it also offers (through Solver) the ability to find optimum inputs for a desired output. Data storage: Excel is certainly one of the most widely-used database management systems for small database. Not the best, but very popular and frequently useful. Database front ends: Excel sheets can be linked directly to tables and queries in databases from most common DBMS’s. Turnkey applications: While I prefer VB.NET for creating truly powerful Windows programs, Excel has the tools, including VBA, to create powerful, user-friendly applications for just about any purpose on a Windows- based computer.
Controls and User Forms Aside from Macros and User-Defined Functions, VBA can be used very much like VB.NET. You can create user forms and add controls to them, just like in VB.NET. This is part 3 of assignment 6.
Create a User Form From the Developer tab, open up Visual Basic.. From the menu, choose Insert UserForm. Very much like VBA, a blank form will appear, along with a Toolbox. Many of the standard controls that you are familiar with are in the Toolbox: Labels, Textboxes, Comboboxes, Listboxes, Checkboxes, Radiobuttons, and more. To add a control to the form, drag it from the Toolbox. Note that the Properties window works basically the same as it does in VB.NET. A few properties have different names from what you are used to: Forms and Labels have a “Caption” property instead of “Text”.
User Forms and Excel User forms can be used to control Excel. The simplest way to get started with this is to record a macro, and then paste its code into a CommandButton click event. Note that in VBA, event handlers are matched with controls by their names, not by using “Handles”.
Putting Controls on Spreadsheets You can add buttons and other controls directly to worksheets (without a user form) Go to the Developer tab; Click the down arrow under Insert. Select the control. Double-click on the control to write code for it.
Design Mode When you add controls to a worksheet, Excel switches to Design Mode. You will see this on the Developer tab—the Design Mode icon will be highlighted. In design mode, you can move and resize controls, but you can’t use them. To test your code, click the design mode icon to turn it off; then click the button.
Example Here I have put a CommandButton on a spreadsheet. Here’s the code:
Editing Properties To edit the properties of a control on a worksheet, make sure that you are in design mode, then right-click on it and select “Properties”.
Properties! Note that in VBA, many controls (buttons, labels) have a “Caption” property instead of “Text”.
Tables You are familiar with tables from database design. Excel uses tables as well, although it is not as picky as Access. In Excel, a table is a rectangle of cells, generally with column headers. The data in the rows is related. Excel 2007 allows you to “Format as Table”, which provides several cool features: – Cool color schemes. – Columns can be automatically sorted or filtered. – Typing a formula in a cell adjacent to the table causes the formula to automatically be copied to all rows.
Using Names Rows, columns, cells, tables and other ranges in a spreadsheet can be assigned names. This can make your formulas easier to read and some development tasks simpler.
Using Names Rows, columns, cells, tables and other ranges in a spreadsheet can be assigned names. This can make your formulas easier to read and some development tasks simpler. The Name Manager is found on the Formula tab in Excel:
Pivot Tables Pivot Tables are a popular Excel feature. They allow you to quickly organize summary data according to the categories that you want. Creating a useful pivot table is part 4 of assignment 6. I will demonstrate using the Elements table.
The Key to a Useful Pivot Table Pivot tables are best at organizing subtotals according to categories. Categories are usually either enumerated values (Freshman, Sophomore…; North, East, South, West) or time periods (years, quarters, months). The subtotals are aggregate values (sums, averages, minimums, maximums, etc.) that you want to analyze based on various combinations of categories. If your Excel data table doesn’t include AT LEAST three category columns and AT LEAST one numerical value that can be aggregated (summed, averaged, etc.), the pivot table will likely be useless and dull.
Examples of Useful Pivot Tables In a table of students – Categories: Year in School Major Gender Resident Status – Values to be aggregated: Grades (in grade points) Credits Financial Aid
Examples of Useful Pivot Tables In a table of baseball players: – Categories Team Position Nationality Years Played – Values to be aggregated: Batting Average Home Runs Salary Etc.
In a table of Universities Categories – Public/Private – State – Size Category – Values to be aggregated: – Graduation Rate – Rate of Job Placement – Rate of Admission to Grad School