Академический Документы
Профессиональный Документы
Культура Документы
Keyboard shortcuts
The following keyboard shortcuts may be of use whilst using these notes: <Alt><F11> <F1> To open the Visual Basic Editor (VBE) or switch between the VBE and your workbook. Use within the VBE window to obtain help on VB functions, objects and properties. Click within the word you require help with (do not select the word) and press <F1>. Toggle breakpoints position your cursor on a macro statement within the Visual Basic editor and press <F9> to set a breakpoint. When the macro is run, processing is suspended at the breakpoint(s) to allow you to inspect variable values and see what is going on. To clear all breakpoints. Use within the VBE window to display the Object Browser window.
<F9>
<Ctrl><Shift><F9> <F2>
Related documentation
The following local documents are available from the Web: Further Excel 2000 (document exl00-t3) VB Excel 97/2000: Creating custom dialog boxes (document exlvba-t2) Other books are available: Writing Excel Macros, Steven Roman, (Excel 97 and 2000) O'Reilly http://www.oreilly.com/ Excel 97 Programming for Windows for Dummies, John Walkenbach Excel 2000 Programming for Dummies, John Walkenbach Excel 2002 Power Programming with VBA, John Walkenbach (Wiley and sons) Visual Basic for Excel 97/2000 (03.04) http://www.bristol.ac.uk/is/selfhelp/documentation/ exlvba-t1/exlvba-t1.doc If you have any comments or queries about this document mail iser-docs@bristol.ac.uk. This document may be used wholly or in part by the academic community, providing suitable acknowledgment is made. It may not be used for any commercial or profit-making purpose without permission. 2004 University of Bristol. All rights reserved.
Contents
Format conventions Keyboard shortcuts Related documentation Task 1 Virus protection ................................................................................ 1 Task 2 Recording a macro............................................................................ 2 Task 3 Relative reference macros ................................................................ 3 Task 4 Editing a recorded macro................................................................. 5 Task 5 Simple loop structures ...................................................................... 6 Task 6 Debugging a macro ........................................................................... 7 Task 7 Using a Range variable..................................................................... 8 Task 8 Creating a function ........................................................................... 9 Task 9 Rearrange macro ............................................................................ 10 Task 10 Yes/No inputs................................................................................... 12 Task 11 Error trapping and GoTo .............................................................. 13 Task 12 MsgBox: Text & numerical values ................................................ 14 Task 13 Applying formats using macros..................................................... 15 Task 14 Text functions.................................................................................. 17 Task 15 Worksheet functions in VB ............................................................ 19 Task 16 InputBox .......................................................................................... 20 Appendix A Appendix B Appendix C Visual Basic objects....................................................................... A-1 Declaration of variables................................................................ B-1 Programming structures .............................................................. C-1
Introduction
Excel is the University's recommended spreadsheet product for Windows on PCs. This document is intended for the more experienced user of Excel who wishes to make use of Visual Basic for Applications (VBA). This document does not intend to teach VBA or even the concepts of object-oriented programming. Instead the examples in this document have been devised to show various aspects of Visual Basic for Excel. John Walkenbach's book in the "...for Dummies" series (see Related Information) gives a good explanation of these. When attending courses in the training rooms in the Computer Centre the working files and solutions referred to in this document are located in the directory C:\User\Excel\. If you are working on your own system, you need to download the file: http://www.bristol.ac.uk/is/selfhelp/documentation/exlvba-t1/exlvba-t1.exe, copy it to a folder on your hard disk and run it before starting these notes. In many cases there is continuation from one example to the next. If you wish to skip a particular exercise you will need to load the solution file to the previous example. When working through the examples you may also like to try modifying them in order to make them applicable to your own uses of Excel.
Prerequisites
It is essential that you have grasped the concepts of names and conditional functions, covered in Further Excel 2000 (document exl00-t3). Some experience of structured programming will be an advantage.
Acronyms
VB VBA VBE Visual Basic Visual Basic for Applications Visual Basic Editor
If the Stop Recording toolbar is not available, you could display it using the View/Toolbars/Stop Recording. However, this would then be inserted into your macro and the toolbar displayed every time the macro is run. Use the alternative method instead: From the Tools menu, select Macro and Stop Recording. If you fail to stop recording the macro at this stage, you will create an infinite loop of record and playback.
Select Sheet2 and cell A1. If you do not have a Sheet2; from the Insert menu, select Worksheet. From the Tools menu, select Macro and Macros. Select Company_name, click on Run and watch the result.
2.8
Select Sheet3 and click in cell A1. Run the macro again, this time by pressing <Ctrl><n>.
2.9
Insert a new Worksheet and click in a cell other than cell A1. Run the macro again and observe where the title heading and formatting are inserted.
2.10
If you want to make any changes to the macro (as in the next task) you will first need to unhide personal.xls. From the Window menu, select Unhide and with Personal.xls highlighted, click on OK. When you quit Excel you will be asked if you wish to save the changes made to the personal macro workbook. If you click on Yes, the file personal.xls is opened as a hidden workbook. Personal.xls is stored in the folder (for a default installation of Windows NT):
c:\winnt\profiles\username\Application Data\Microsoft\Excel\XLStart
The personal.xls workbook is opened next time you start Excel and is not available to other users.
4.1
4.4
You may also like to look at the Company_name macro created in task 2 to see how the relative references make a difference. Using the left-hand pane, navigate to VBA Project (Book1)/Modules/Module1 (replacing Book1 with the name of your workbook). Return to the Months module and, if you wish, make a small change (such as the font size). Make sure that you modify the last occurrence of .Size= in the macro. In some cases, such as the simple macros recorded so far, it may be quicker to delete and re-record the macro than edit the code. From the File menu, select Close and Return to Microsoft Excel. If you made any changes to the code, run your macro again. Close any open workbooks, discarding changes. Later examples explain the program structures and language used. Appendix 1 introduces the concepts of Visual Basic objects. Lines that are just text comments and not Visual Basic commands are preceded with a single quotation mark. If you forget to assign a shortcut key (such as <Ctrl><m>) to a macro at the time of recording, you can assign one later by returning to the workbook and, from the Tools menu, selecting Macro/Macros and the Options button.
4.5
6.1 6.2
Position the mouse cursor over a variable, for example Number. Note that the current value for the variable is displayed. Position the cursor over the misspelt variable, Roww. The text Roww = Empty is displayed. Correct the mistake (remove the extra w). From the Visual Basic Run menu, select either: Continue to resume processing the macro, OR: Reset and then switch to the worksheet before re-running the macro.
Note
When editing a Visual Basic macro you can position the cursor on a macro statement and set (or unset) breakpoints (from the Debug menu, select Toggle Breakpoint or press <F9>). When the macro is next run, execution will stop before the statement and enter into the debug mode. You can then inspect variables and see what is going on. To restart the macro, from the Run menu, select Continue. To clear all breakpoints, from the Debug menu, select Clear All breakpoints (or press <Ctrl><Shift><F9>).
This task will rotate those results (figure 4) in order to make use of other features within Excel such as Subtotals and PivotTables. 9.2 Highlight the range A1:G13 and define a range name, area.
Figure 4 - sample of rotated data
Click in cell I1 and define a name, areaoutstart. 9.3 Switch to the VBE and insert a new module. Insert a new procedure (subroutine) named rearrange.
10
9.4 Note
Enter the following code (in bold): The following text is available in the working folder as task9_4.txt to copy and paste if you prefer not to type it. Take a few moments reading through the code to get an idea of the structure and what might be happening. Public Sub rearrange() Set ar = Range("area") Set arout = Range("areaoutstart") ncols = ar.Columns.Count nrows = ar.Rows.Count aroutr = 2 countblankcells = 0 arout.Cells(1, 1) = "Name" arout.Cells(1, 2) = "Subject" arout.Cells(1, 3) = "Mark" For r = 2 To nrows For c = 2 To ncols If Not IsEmpty(ar.Cells(r, c)) Then arout.Cells(aroutr, 1) = ar.Cells(r, 1) arout.Cells(aroutr, 2) = ar.Cells(1, c) arout.Cells(aroutr, 3) = ar.Cells(r, c) aroutr = aroutr + 1 Else countblankcells = countblankcells + 1 End If Next c Next r End Sub
Note
The variable countblankcells is used to calculate the number of blank cells encountered when running the macro. The total number will be displayed at the end of the macro (see task 12). The variables ar and arout are ranges and must be initialised using the Set command. By qualifying Cells with a range variable, for example, ar.cells(1,1) we now reference cells within that range rather than the cells within the whole worksheet. The solution example, vbexam_a.xls, contains comments to explain the use of these variables and functions.
Switch back to the worksheet (click on the icon in the Status bar or use <Alt><F11>). Save your workbook. From the Tools menu, select Macro/Macros and with the rearrange macro selected, click on Run.
11
10.1 10.2
Reply = MsgBox(Msg & vbCr & _ "Do you want to continue?", vbYesNo, macroname) If Reply <> vbYes Then MsgBox "Macro abandoned", vbOKOnly, macroname Exit Sub ' quit the macro End If aroutr = 2 Note As you type functions, for example MsgBox, you will notice that the editor displays the parameters required by that function. Appropriate drop down boxes also provide shortcuts as you type your procedures. The ampersand character & is used to string together text strings and text variables whilst the underscore character _ allows you to continue a single line command on the following line for display purposes. Blank spaces are ignored. Indentation in an application is used to make the program easier to read and debug. The standard constant vbCr is used to insert a carriage return into your dialog box. The standard constant vbYes is returned if the Yes button is clicked in reply to the message. The operator <> is used to denote not equal to. 10.4 10.5 Switch back to the worksheet and save your workbook. Highlight and delete the results of the previous task and from the Tools menu, select Macro/Macros and with the rearrange macro selected, click on Run. Test your macro using both No and Yes inputs to your dialog box. 10.6 Take a few moments to read the comments (preceded by a single apostrophe) in the solution file vbexam_b.xls.
12
11.1
14
Method Comments
13.1
13.4 13.5
Test your VBA (vbformat.xls contains a working solution with some sample values to test it on). The second IfEnd If statement in the above code could be extended to deal with Percentage formats with different numbers of decimal places (see the commented out section of vbformat.xls). Close any open workbooks.
13.6
16
14.1 14.2
Copy the formulae in the range B2:E2 into rows 3 to 5. Select columns B:D and from the Format menu, select Column/Hide. See vbreverse_a.xls for a working solution. This function could be extended to include the actions performed by columns B to E. The next task demonstrates this.
18
15.1
19
Task 16 InputBox
Objectives Method Comments
16.1 16.2 16.3 16.4 To obtain and use input from the user. You will use the InputBox function in Visual Basic. You must first have successfully completed task 15. With the worksheet created in task 15 open, switch to the VBE. From the Insert menu, select Procedure. Type the name Surname and click on OK. Complete the procedure as shown in bold: Public Sub Surname() myString = InputBox("What is the full name?") Msg = "The surname is " MsgBox Msg & getSurname(myString), vbOKOnly End Sub 16.5 16.6 Note Run the procedure (press <F5> or from the Visual Basic Run menu, select Run Sub/UserForm). When prompted enter the name Dr P A Brown and click on OK. See vbreverse_b.xls for a working solution together with additional code for allowing the user to select the Cancel button (or press the <Esc> key). The solution also deals with blank and numeric values entered into the dialog box.
20
Appendix A
Comments
Some of the items referred to in the examples are more complicated than simple numeric constants and values. Such variables are called objects. For instance the variables that refer to Excel ranges, worksheets, charts, and workbooks are objects. This appendix gives a very rough explanation of how to find out what objects there are and how they interact.
Libraries
Objects are grouped in classes (for example, Excel, Office) and their definitions stored in specific libraries. Visual Basic for Excel starts with a default set of libraries. Libraries can easily be added to the set (from the VBE Tools menu, select References). A reference to an object that is not in the current set of object definitions will cause an error.
Example Range(A1).Clear will clear the contents and formatting of cell A1.
Methods cause acts to be done to the object, while Properties return simple values and objects that are associated with the object As can be seen from these examples, each property and method has its own set of rules defining what arguments are necessary to construct a valid reference to it. If present the arguments are enclosed in parenthesis and separated by commas. Any text constant argument must be enclosed in double quotes. There is an alternative form of specifying arguments using keywords that is useful when there are many arguments.
In general the collection objects will share many methods and properties, for example, Count, Add, Item, Close.
Visual Basic for Excel 97/2000 (exlvba-t1) A-1
A separate help window will be created (if it does not already exist) containing information about the chosen item. Quite often there will be Properties and Methods buttons that can be clicked to get information about all the properties and methods for the chosen object. Because it is sometimes difficult to guess whether a particular item is a property or a method, it is often necessary to look in both lists to find its definition. When it is available on the help window, the Example button can be clicked to give useful information and the displayed example text pasted into your program to be edited for your own use.
ActiveWorkbook and ActiveSheet are such global objects. They refer to the currently active workbook and worksheet respectively. If a Range object is used, which is not specifically associated with a particular sheet or book, then it is assumed to refer to the ActiveWorkbook.ActiveSheet object. If only one Excel workbook is open, then this will be defined to be the ActiveWorkbook. The sheet selected when the macro is run will be the ActiveSheet. If all the objects you want to access are in this sheet then there is no need to associate them with a parent object. If you want to access objects in other sheets or workbooks, then objects such as Sheets and Workbooks need to be used.
Example Workbook(exone.xls).Activate
A particular sheet may be made the active sheet via:
Example Sheets(Sheet2).Activate Warning Before the ActiveCell object can be used or a particular range selected using the
Select method, then an ActiveSheet object must have been defined.
A-4
Appendix B
Comments
Declaration of variables
The examples in these notes introduce variables as they are needed within the subroutines. However it is good practice to declare your variables before you use them in a procedure (subroutine or function). By assigning the data type to each variable the program will run faster and use memory more efficiently. If a variable is not explicitly declared, it is of type variant. In general, Visual Basic is very tolerant of the kind of information that can be stored as type variant. A variable can be declared in 3 places:
Single procedure only If a variable is to be used within a single procedure only, declare it with a Dim or Static statement in the procedure that uses that variable. A static variable is one that retains its value even when the procedure ends.
Module only If a variable is to be used throughout the procedures within a module, use a Dim statement before the first Sub or Function statement in that module.
B-1
In the examples within this document, only a few procedures are used. However, as a large program is developed using multiple procedures across several modules, it becomes essential to declare all variables used. Efficiency aside, spelling mistakes can occur within variable names leading to incorrect calculations. Use the statement Option Explicit as the first line within a module to force the declaration of variables. The program will stop if a variable name has not been declared. Note The VBE can be configured to automatically insert the Option Explicit line in new modules. From the Tools menu, select Options. Within the Editor tab, select Require Variable Declaration. The declaration Dim i, j As Integer will declare j as an integer and i as a variant. See the online help for more information on declaring variables and variable types.
B-2
Appendix C
Programming structures
Comments This appendix includes examples of some of the programming structures available to
you when writing VBA code. For further information on their use, please see the online help system. Where square brackets [] are used, this indicates that this part of the structure is optional. For Next For expression (item=) {do these commands} Next item
If then If condition Then {do this single command} [Else] Alternatively, using the block syntax: If condition Then {do these commands} Else {do these alternative commands} End If
For Each Next For Each Cht in Sheets(Sheet1).ChartObjects (or Cell in Selection) Cht.Chart.ChartType = xlLine Next Cht
Select Case End Select Select Case Quantity Case 0 To 24: Discount = 0.1 Case 25 To 49: Discount = 0.15 Case 50 To 74: Discount = 0.2 Case Is >= 75: Discount = 0.25 End Select
C-1