Project 9 Using Visual Basic for Applications (VBA) to Customize and Automate Excel Jason C. H. Chen, Ph.D. Professor of Management Information Systems School of Business Administration Gonzaga University Spokane, WA 99258, USA Chen@gonzaga.edu
Excel Skills Add code to a VBA macro procedure Assign a macro to a custom button Create a VBA procedure to import text data Modify a macro in the Visual Basic window Record a macro Run a macro assigned to a button View a macro using the Visual Basic Editor
Key Terms custom button Event event-driven A control you create from a tool on the forms toolbar that is used to run code procedures. Event An action by the user or the system, such as a mouse click, or the change of the system clock. event-driven A programming environment where specific procedures and routines are executed in response to a specific user, system, or error event.
Key Terms macro recorder Method Object The Excel tool you use to record a series of steps and commands that are stored in a Visual Basic procedure. Method A Visual Basic term that refers to an action performed on an object. Object An image, chart, or other data added to an Excel worksheet.
Key Terms Property sub procedure Visual Basic Editor Specification for a workbook file, such as the author and title of the workbook. Individual controls in Excel such as text boxes, images, and command buttons also have properties that can be set or changed. sub procedure A series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but does not return a value. Visual Basic Editor "A window in Excel that you can use to write and edit macros attached to Excel workbooks."
Key Terms Visual Basic for Applications (VBA) Visual Basic window The shared Visual Basic development environment that provides you the means to accomplish a wide range of programmatic results within any Office application Visual Basic window The window that appears on top of the Worksheet window and displays the Visual Basic code comprising a macro.
Objectives Record a macro View the contents of a macro using the Visual Basic Editor Modify a macro using the Visual Basic Editor Use VBA to automate a complex task Assign a Visual Basic macro to a button control Run a macro from a button control
What is Visual Basic for Application (VBA)? VBA is the shared development environment that provides you the means to accomplish a wide range of programmatic results within any Office application. You can use the tools you use to develop solutions in Excel to automate tasks in other applications (e.g., Word and Access). VBA is a subset of Visual Basic, a full-fledge programming environment for creating applications and solutions. Therefore, VBA uses the same conventions as other powerful programming environment.
VBA can be considered as the glue that provides functionality within Office. Visual Basic and VBA are event-driven environments.
Traditional, structured programming environments: In an event-driven application: The program does not follow a predetermined path, but rather executes different code sections in response to an event. Events include user actions and the sequence of the events determines the sequence in which the code executes, thus the path through the application’s code differs each time the program runs. The program controls how the code executes. The program runs beginning with the first line of code and follows a predefined path through the application, calling procedures as needed.
Task 1: To Record a Simple Macro (cont.) Open the Retirement Calculator.xls workbook. 2. Click View, Toolbars, and select the option to display the Visual Basic toolbar. The Visual Basic toolbar will appear. 3. Click the Record Macro button. The Record Macro dialog box will appear.
Task 1: To Record a Simple Macro (cont.) 4. Type FormatWorksheet as the name for the macro you will create. 5. Change the format of the range A1:A3 to Bold. 6. Change the alignment of the range A5:A11 to Align Right. 7. Add the outside Borders format to cells A11:B11. Type 21 in cell B5 as the current age of the employee. 9. Type 250 as the initial investment in cell B7, and 125 as the monthly contribution in cell B8. Format both entries as currency. 10. Type 7.5% in cell B9 as the average annual interest rate.
Task 1: To Record a Simple Macro (cont.) 11. Click cell A1, and then click the Stop Recording button. 12. Save the workbook. FV(rate, periods, payment) it returns the future value of an investment based on periodic, constant payments, and a constant interest rate
Task 2: To View a Macro in the Visual Basic Editor (VBE) Click Tools, Macro, and Select Macros from the cascading menu. The Macros dialog box appears and displays the macros in all open workbooks. Because there is only one macro in the workbook, it is highlighted by default. 2. Click Step Into.
Excel displays the code for this macro. Task 2: To View a Macro in the Visual Basic Editor (cont.) Excel displays the code for this macro.
Task 2: To View a Macro in the Visual Basic Editor (cont.) TIP. You may also view code for one or more macros by clicking the VBE button. On the VB toolbar. TIP. When you name the macro, you were defining the name for the subprocedure. 3. Press [F8] to move to the next statement in the procedure. The Editor highlights the line displayed in the Figure. In this statement, the specified range object is selected, using the Selection method.
Objects, Properties, and Methods As a subset of the Visual Basic programming environment, VBA exposes objects that have properties and methods. An object represents an element of an application, such as a worksheet, a cell, a chart, a form, or a report. A property is a named attribute of an object. It defines object characteristics such as size, color, and screen location, or the state of an object such as enabled or disabled. Properties are displayed in blue text. A method is an action performed on an object. In VBA code, you must identify an object before you can apply one of the object’s method or change the value of one of its properties.
Task 3: To Edit a Macro using the VB Window 1. Press [F8] twice, and press [Enter]. Place the insertion point to the blank space you just created. 2. Press [Tab] to indent the line. 3. Type Selection.Font.ColorIndex=55 on this line. This statement will set the font color property for the selection to dark blue. 4. Scroll to the bottom of the Visual Basic window. 5. Change the text entries in cells B5, B7, and B8 to 25, 350, and 200 respectively. 6. Close the VB window. When the Dialog box shown, click OK.
Task 3: To Edit a Macro using the VB Window (cont.) 6 (cont.). Close the VB window. When the Dialog box shown, click OK. 7. Save the workbook 8. Click the Run Macro button on the VB toolbar.
Task 3: To Edit a Macro using the VB Window (cont.) 9. Click Run when the FormatWorksheet macro is highlighted. The workbook appears with the new changed. 10. Close/or Save the workbook.
Task 4: To Create a VBA Procedure to Import Text Data Launch Excel, if it is not currently running. Display the VB toolbar, if it is not currently visible (click View, Toolbar then Visual Basic) Click the VB Editor button on the VB toolbar. 4. Click File, Import File
Task 4: To Create a VBA Procedure to Import Text Data (cont.) 5. Locate your floppy disk in the Import File dialog box and change the file setting to all files. 6. Select the Import Text Code.txt file and click the Open button. (Make sure that you have all three text files on the floppy A) 7. Click the small Expand button in the Project window next to the Modules Folder.
Task 4: To Create a VBA Procedure to Import Text Data (cont.) 8. Double-click the Module 1 icon. 8 (cont.). The Visual Basic procedure appears in the VB window. 9. Close the VB window. 10. Click the Run Macro button.
Task 4: To Create a VBA Procedure to Import Text Data (cont.) 10 (cont.). The ImportTextData macro is highlighted because it is the only macro in the workbook. 11. Click Run in the Macro dialog box. The VBA statements execute. After a time you will see the worksheet shown. TROUBLESHOOTING: If the Orders.txt file is not on the A: floppy diskette, you will receive an error message, and the data will not be imported into Excel.
Task 4: To Create a VBA Procedure to Import Text Data (cont.)
Task 4: To Create a VBA Procedure to Import Text Data (cont.) Check Point: Look at the Excel Title bar. Has this document been saved? You do not need to save this workbook because the macro includes VBA statements to save the file to the A: floppy diskette. 11. Close the Sales Data.xls workbook. The default workbook, Book1.xls, is now displayed.
Task 4: To Create a VBA Procedure to Import Text Data (cont.) OLD NEW
Task 4: To Create a VBA Procedure to Import Text Data (cont.)
Task 4: To Create a VBA Procedure to Import Text Data (cont.)
Task 5: To Add Code to the Macro 0. Files needed: Import Text Code.txt Orders.txt Add Formulas.txt Spreadsheets created: Sales Data.xls Import Text Data.xls Launch Excel, if it is not currently running and click the VB Editor button on the VB toolbar. Scroll to the last code statement defining the array, near the bottom of the code listing.
Task 5: To Add Code to the Macro (cont.) 4. Click Insert, File. 5. Select the Add Formulas.txt file and click Open.
Task 5: To Add Code to the Macro (cont.) 6. Scroll down in the code listing so the comments introducing the additional lines of code are visible.
Task 5: To Add Code to the Macro (cont.) 7. Click the Save button in the VB Editor. Type Import Text Data as the name for the workbook, and select floppy drive A as the file location in the Save As dialog box. 8. Click Save. 9. Close the VB Editor.
Task 6: To Assign a Macro to a Button Control 0. Open the Import Text Data.xls file Click View, Toolbars, and display the Forms toolbar. Click Custom Button on the Forms toolbar.
Task 6: To Assign a Macro to a Button Control (cont.) 3. Drag a rectangle near cell A1. When you release the left mouse button, a command will appear, as well as the Assign Macro dialog box shown.
Task 6: To Assign a Macro to a Button Control (cont.) 4. Highlight the ImportTextData macro in the list and click OK. 5. Right-click over the Command button (i.e., Button 1) and choose Edit text
Task 6: To Assign a Macro to a Button Control (cont.) 6. Type Import Sales Data as the caption for the button. 7. Click outside the button to deselect it. 8. Save your changes to the workbook.
Task 7: To Run the Import Text Data Macro using a Button Control Click the Import Sales Data button. Excel will import the text data, add formulas to column I of the imported worksheet, and apply formatting to specified cells and columns. When the message shown in the Figure appears, click Yes..
Task 7: To Run the Import Text Data Macro using a Button Control (cont 3. Use the horizontal scroll bar to display column O. The worksheet appears as shown (right side). 4. Close the Sales Data.xls workbook. 5. Close the Import Data.xls workbook.
Running Case Mr. Traylor is interested in how Microsoft Office’s Visual Basic for Applications programming features in Excel may assist the e-commerce department in automating redundant tasks. He wants you to develop a specific VBA solution.
Project Challenge Mr. Traylor wants you to create a custom method for importing ASCII text transaction data into Excel automatically, regardless of the number of sales transactions stored in the file.
Solution – Macros and the Visual Basic Editor
Project 9 Using Visual Basic for Applications (VBA) to Customize and Automate Excel