43
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 [email protected]

Project 9 Using Visual Basic for Applications (VBA) to Customize and Automate Excel Jason C. H. Chen, Ph.D. Professor of Management Information Systems

Embed Size (px)

Citation preview

Project 9Using 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 UniversitySpokane, WA 99258, USA

[email protected]

2

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

3

Key Terms custom button

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.

4

Key Terms macro recorder

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.

5

Key Terms Property

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

6

Key Terms Visual Basic for Applications (VBA)

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.

7

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

8

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.

9

VBA can be considered as the glue that provides functionality within Office.

Visual Basic and VBA are event-driven environments. VBA can be considered as the glue that provides

functionality within Office. Visual Basic and VBA are event-driven environments.

10

Traditional, structured

programming environments:

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.

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.

11

Task 1: To Record a Simple Macro (cont.)

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

12

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

13

11. Click cell A1, and then click the Stop Recording button.12. Save the workbook.

Task 1: To Record a Simple Macro (cont.)

FV(rate, periods, payment) it returns the future value of an investment based on periodic, constant payments, and a constant interest rate

14

Task 2: To View a Macro in the Visual Basic Editor (VBE)

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

15

Task 2: To View a Macro in the Visual Basic Editor (cont.)

Excel displays the code for this macro.

16

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.

17

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.

18

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.

19

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.

20

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.

21

Task 4: To Create a VBA Procedure to Import Text Data

1. Launch Excel, if it is not currently running.

2. Display the VB toolbar, if it is not currently visible (click View, Toolbar then Visual Basic)

3. Click the VB Editor button on the VB toolbar.

4. Click File, Import File

22

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.

23

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.

24

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.

25

Task 4: To Create a VBA Procedure to Import Text Data (cont.)

26

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.

27

Task 4: To Create a VBA Procedure to Import Text Data (cont.)

OLD NEW

28

Task 4: To Create a VBA Procedure to Import Text Data (cont.)

29

Task 4: To Create a VBA Procedure to Import Text Data (cont.)

30

Task 5: To Add Code to the Macro

0. Files needed:Import Text

Code.txtOrders.txtAdd Formulas.txtSpreadsheets

created:Sales Data.xlsImport 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.

31

Task 5: To Add Code to the Macro (cont.)

5. Select the Add Formulas.txt file and click Open.

4. Click Insert, File.

32

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.

33

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.

34

Task 6: To Assign a Macro to a Button Control

0. Open the Import Text Data.xls file

1. Click View, Toolbars, and display the Forms toolbar.

2. Click Custom Button on the Forms toolbar.

35

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.

36

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

37

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.

38

Task 7: To Run the Import Text Data Macro using a Button Control

1. Click the Import Sales Data button.2. 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..

39

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.

40

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.

41

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.

42

Solution – Macros and the Visual Basic Editor

Project 9

Using Visual Basic for Applications (VBA) to Customize and Automate

Excel