Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations

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:

1 November 30, 2010 Excel VBA: An Introduction

2 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)

3 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:

4 Not the addition table I learned! What went wrong? Let’s look at the formula in cell C2:

5 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:

6 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.

7 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.

8 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?

9 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.

10 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.

11 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.

12 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.

13 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

14 Running the Macro Go to Developer Tab Macros Select Macro, click Run Or use the shortcut key

15 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.

16 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.

17 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.

18 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.

19 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…

20 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.

21 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.

22 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.

23 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.)

24 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

25 “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).

26 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.

27 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

28 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.

29 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.

30 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

31 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.

32 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!

33 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.

34 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.

35 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.

36 Examples Gravity BMR

37 UDF Examples: Too Simple

38 Simple but Useful

39 Something’s Missing? What do these functions lack?

40 More UDFs



43 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

44 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

45 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

46 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?).

47 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.

48 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.

49 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”.

50 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”.

51 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.

52 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.

53 Example Here I have put a CommandButton on a spreadsheet. Here’s the code:

54 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”.

55 Properties! Note that in VBA, many controls (buttons, labels) have a “Caption” property instead of “Text”.

56 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.

57 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.

58 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:

59 The Name Manager

60 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.

61 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.

62 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

63 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.

64 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

Download ppt "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."

Similar presentations

Ads by Google