Visual Basic for Applications (VBA) Goals: ² Familiarity & experience with solving problems algorithmically. ² Familiarity with Visual Basic for Applications (VBA). VBA/Excel dialect. ² Empower you to build useful applications and to learn more on your own. ² Get you comfortable in a programming environment. Note: But you have to do a lot of work on your own! Lectures are to provide you a map. You must make the trip yourself. (cf., VBATutor.xls) File: misnotes-vba-slides-s1999.tex. 1
File: misnotes-vba-slides.tex. Created: February 13, 1998. Modi ed version of vb1-19970228.ppt. Modi ed: 19980329, 19980326, 19980214. See also: VBATutor.xls. File: misnotes-vba-slides-s1999.tex, modi ed February 8, 1999. 1-1
Goals for lecture 1. Assuming: ² Famliarity with the basic concepts of macros in Excel (which are written in VBA). ² Know how to record and run a macro, and examine and edit its code in the Visual Basic Editor. Then: 1. Use the Visual Basic Editor to create a simple VBA program (Sub) and call it for execution from a button on a worksheet. 2. Use the Visual Basic Editor to create a simple VBA program (Function) and call it for execution from a cell in a worksheet. 3. Introduce the core structure of VBA programs. 4. Introduce program variables (cf., Worksheets("Lecture1") code module Lecture1) 2
See VBATutor.xls, Worksheets("Lecture1") and code module Lecture1. 2-1
Macros ² Programs in VBA. R^ole of VB and VBA for Microsoft. ² What is VBAnExcel good for? { Assembling, \gluing together," applications in MS O±ce. (Larger issue: \component-based applications.") { Utility (small job) programming, e.g., for data preparation and manipulation, for programming the interface,... { For learning how to program. { For prototype programming. { For learning about modern software concepts (e.g., OOP) and development environments (now a good one in Excel for VBA). 3
More on macros ² Recording macros { Tools ) Macro ) RecordNew Macro... { Stop, relative addressing { Running the macro: Tools ) Macro ) Macros... { Viewing the macro: Tools ) Macro ) Visual Basic Editor Alt+F11 3-1
Recorded macro, called Bob Sub Bob() ' ' Bob Macro ' Macro recorded 2/13/98 by Steven O. Kimbrough ' ' Range("B3:C4").Select Selection.Copy Range("A1").Select ActiveSheet.Paste Application.CutCopyMode = False Range("A1").Select End Sub 4
1. This is VBA code written by the macro recorder. You can edit it just as you would code you had written. 2. Later we'll see details of VBA syntax, etc. For now note that, e.g., Range("B3:C4") is an object which has the method Select. Range("B3:C4").Select means \Select the object Range("B3:C4"). But note how readable the code is. 3. Application is also an object (here, Excel itself) but CutCopyMode is not a method. Rather, it is a property, which as it happens can be true or false. Here we are setting this property ofappication to False. 4. In general, think in terms of: Objects which have methods (which do things) and properties (which can have di erent values). Related to object-oriented programming: close but not quite. Still, a pervasive and very useful metaphor in Microsoft O±ce products. 5. Note comment signs. 4-1
Basics of Visual Basic for Applications ² VB, VBA, VBAnExcel, VBAnWord,... ² Macro modules ² Subs ² Functions ² Variables & declaring them ² Structure of a VBAnExcel application 5
A simple Sub 1. Tools ) Macro ) Visual Basic Editor 2. Insert ) Module (Not: Class Module) 3. View ) Properties Window 4. Then write some code: Sub HelloWorld() MsgBox "Hello world!" End Sub ² Use the VB Help menu item to search on MsgBox. (And use it generally and often!) ² Subs do things, but do not return values. Functions do things, and do return values. 6
Note: ² The editor is helpful. Always type lower case and make the editor do the conversion to upper case a good error-prevention strategy. ² Run the macro from the Editor (put the cursor in the code and click the Run button on the menubar) ² Run the macro from Excel (Tools ) Macro ) Macros... ) 6-1
Now, make it run from Excel...... 1. View ) Toolbars ) Control Toolbox 2. Select and draw a button. 3. Right-click with the button selected ) Properties. Set the properties as desired, then close the Property Window. 4. Right-click the button selected ) View Code 5. Add a call tohelloword: Private Sub cmdhellowold_click() HelloWorld End Sub 6. Return to Excel, exit design mode, and click the button. 7
A simple Function 1. Tools ) Macro ) Visual Basic Editor 2. Select a code module, e.g., the one with Sub HelloWord. 3. Add code and save work: Function dblutility(x, Hi, Lo, Risk) As Double dblutility = ((X - Lo) / (Hi - Lo)) ^ Risk End Function 4. Return to Excel and use this function in a cell, just as any built-in Excel function. 8
Try these procedures in a code module: Function dblcubed(x As Double) As Double dblcubed = X ^ 3 End Function Sub CubeMe() Dim dbldanumber As Double dbldanumber = _ InputBox("What number " & _ "would you like to cube?") dbldanumber = dblcubed(dbldanumber) MsgBox "And the answer is " & dbldanumber End Sub ² Dim dbldanumber As Double declares (Dimensions) the program variable dbldanumber as type Double (precision oating point). ² for line continuations. & for string concatenation. 9
VBAnExcel Programs. Are collections of Subs andfunctions (and Declarations). Typically they: 1. Are called (started) from Excel. 2. Read in information. From, e.g., worksheets, dialog boxes, les, databases. 3. Store this information in variables. 4. Computationally manipulate the variables. 5. Write out the information. To., e.g., worksheets, dialog boxes, les, databases. Basic concepts at hand, details now follow. 10
Recall: VBAnExcel Programs. Are collections of Subs andfunctions (and Declarations). Typically they: 1. Are called (started) from Excel. 2. Read in information. From, e.g., worksheets, dialog boxes, les, databases. 3. Store this information in variables. 4. Computationally manipulate the variables. 5. Write out the information. To., e.g., worksheets, dialog boxes, les, databases. 11
Variables Expressions (think of names) in programs that can hold di erent values at di erent times. ² X, Hi, Lo, Risk in thedblutility function. Option Explicit Sub FirstVariableExample() Dim I As Integer Dim MyFirstVariable As Integer 'Note: Dim I, MyFirstVariable as Integer ' leaves I an Integer and MyFirstVariable ' as a Variant. Thanks, Bill! MyFirstVariable = 3 For I = 1 To MyFirstVariable MsgBox "Showing and counting: " & I Next I End Sub 12
Variables have data types ² Types: { Integer, Long { Single, Double { Currency { Date { String { Variant ² Why? ² Look them up in the VBA online help. 13
Programs (in general, I emphasize): ² Declare variables ² Put values into variables ² Make calculations with variables ² Store results of calculations in variables Also (especially in VBA) they: ² Manipulate application objects: call methods, read and alter properties 14
Declaring variables (in VBA) ² Variables should always be declared. { Why? { Variant if not declared. { Use Option Explicit in the declarations section to force declaration of variables. ² Variables have scope. Why? ² Declaring variables { Dim in a procedure. Scope: that procedure. { Private (or Dim) in the declarations section of a module. Scope: that module. { Public in the declarations secion of a module. Scope: entire application. 15
Value(s) of MySecondVariable? Option Explicit Private MySecondVariable As Integer Sub PublicExample1() MsgBox "We're in PublicExample1 " & _ "and MySecondVariable = " & _ MySecondVariable End Sub Sub PublicExample2() MySecondVariable = 23 MsgBox "We're in PublicExample2 " & _ "and MySecondVariable = " & _ MySecondVariable End Sub 16
1. Run PublicExample1 using the Run button in the VBA editor. MySecondVariable = 0. 2. Run PublicExample2 using the Run button in the VBA editor. MySecondVariable = 23. 3. Run PublicExample1 using the Run button in the VBA editor. MySecondVariable = 23. 4. Now Reset and try again (MySecondVariable = 0). Discuss. Emphasize that while VBA has automatically initialized MySecondVariable to 0, it's a bad idea to leave this to VBA. Always initialize variables yourself! 16-1
Reading from, and writing to, a worksheet Sub CosineHardWired() Dim MyNumber As Double MyNumber = _ Worksheets("Lecture2").Cells(9, 2).Value 'Note: Cells(9,2) = row 9, column 2 of the 'worksheet. Worksheets("Lecture2").Cells(11, 2).Value = _ Cos(MyNumber) 'This also works: 'Worksheets("Lecture2").Range("B11").Value = _ 'Cos(MyNumber) 'And suppose MyTestRange is defined B2:D13. 'Then this works, too: 'With Worksheets("Lecture2").Range("MyTestRange") '.Cells(10, 1).Value = Cos(MyNumber) 'End With End Sub Try a nonnumber in B9. Debug. Reset button. Later: the debugger. 17
1. Suppose a single cell has a name, Bob. then Worksheets("Lecture2").Range("Bob").Value = Cos(MyNumber) also works. 17-1
Goals for lecture 2. 1. Say a word or two more on program variables and how to declare them. 2. Discuss and show how in VBAnExcel to read and write information from and to worksheets. 3. Brie y introduce the Object Browser. 4. Do VBA Homework #1 (handed out today) as an in-class exercise with discussion! (cf., Worksheets("Lecture2") code module Lecture2) 18
Generalizing on reading & writing ² Reading & writing the Excel worksheet are special cases of getting and setting object properties. ² So far, the Value property of a particular object, a particular cell. ² Why not, say, the color of a cell? Sub SimpleShowColor() Dim MyTempHolder As Variant MyTempHolder = _ Worksheets(2).Cells(14, 2).Interior.ColorIndex MsgBox "The interior color of B14 is " _ & MyTempHolder & "." End Sub LOTS of objects and properties in Excel. 19
Generalizing on reading & writing (con't.) Sub GetTheWorksheetName() Dim Temp As String Temp = Range("CellBob").Worksheet.Name MsgBox "The name of the worksheet in which " & _ "the range CellBob resides is " & Temp End Sub Sub RenameMeTheWorksheet() Dim Temp As String Temp = _ InputBox("New name for this worksheet?") ActiveSheet.Name = Temp End Sub 20
The object browser, F2 in the VBA Editor ² Displays, and lets you explore, all available objects, methods, and properties. Nifty! member = (method _ property) ² Right-click on a member. Your code. Excel's code. ² Example: Look in Excel, Range class, Cells member (a property). Call for help. 21
The Object Browser (con't.) A word to the wise: Be ever vigilant. No program documentation is ever complete or completely accurate and the VBA on-line Help is no exception. Some of the descriptions are just plain wrong. Some of the code samples don't work. Any many, many \gotchas" are left unexplored. Still, if you take the documentation with a small grain of salt, you'll nd an enourmous amount of important information there. And the easiest way to get to the information is via the Object Browser. from Excel 97 Annoyances, p. 205. 22
Using VBA subs and functions in other workbooks Question: Can you use VBA macros from another workbook (without copying them)? Answer: Yes. Be sure the other workbook is open (running). Preface your macro calls with the name of the other workbook followed by a bang (!). For example, if the other workbook is theotherworkbook.xls and you want to call a function there, named theotherfunction and that function takes one argument, an integer, then you might write =theotherworkbook.xls!theotherfunction(17) in one of the cells in your workbook. 23
And now... Take a look at VBA Homework #1, handed out today. 24