Beruflich Dokumente
Kultur Dokumente
Mathew Stoessiger
Outline
Setting up Excel and the Visual Basic Editor Recording Macros in Excel Understanding and Editing Macros Limitations on recording Macros Collections and Objects Properties and Methods
The VBE
Recording Macros
We'll now look at some examples of how to record macros.
Exercises
Modifying the .bdf files
Objects
When you work with VBA, you must understand the concept of Objects and Excel's Object Model. It helps to think of Objects in terms of a hierarchy. At the top of this model is the Application - in this case, Excel itself. When you open Excel you create a Workbook i.e Book1.xlsx Inside the Workbook there are Worksheets i.e Sheet1 Worksheets Contain Cells (Called Ranges in VBA) i.e Cell A1 Thus to refer to a specific range (such as cell A1) on a worksheet named Sheet1 in a workbook named Book1, you can use the following expression:
Application.Workbooks("Book1").Worksheets("Sheet1").Range("A1")
Objects
Thus 4 Objects were used to specify Cell A1 Application.Workbooks("Book1").Worksheets("Sheet1").Range("A1")
Objects
Most of the time, however, you can omit the Application object in your references; it is assumed. If the Book1 object is the active workbook, you can even omit that object reference and use this: Worksheets("Sheet1").Range("A1") And - I think you know where I'm going with this - if Sheet1 is the active worksheet, you can use an even simpler expression: Range("A1")
Collections
Another key concept in VBA programming is collections. A Collection is a group of Objects of the same class, and a collection is itself an Object. For Example: Worksheets is a collection of all Worksheet objects (Sheet1, Sheet2, Sheet3 ect) contained in a particular Workbook (Book1.xls) You can work with an entire collection of objects or with an individual object in a collection for example: Worksheet.Select Selects all the worksheets in the Workbook, while Worksheet(Sheet1).Select Selects only Sheet1
Object Properties
Every Object has Properties. For example, a Range Object has a Property called Value. You can write VBA code to display the Value property or write VBA code to set the Value property to a specific value. Here's a procedure that uses the VBA MsgBox Function to pop up a box that displays the value in cell A1 on Sheet1 of the active workbook:
Object Properties
What if you want to change the Value property? The following procedure changes the value displayed in cell A1 by changing the cell's Value property: Sub ChangeValue() Worksheets("Sheet1").Range("A1").Value = 123.45 End Sub
Object Methods
In addition to properties, objects also have methods. A method is an action that you perform with an object. Here's a simple example that uses the Clear method on a Range object. After you execute this procedure, A1:C3 on Sheet1 is empty and all cell formatting is removed: Sub Clear() Worksheets("Sheet1").Range("A1:C3").Clear End Sub
Object Method
Exercises
Did you know that Excel can talk? Excel has a Text to Speech Engine and is able to speak the text entered into a Cell. Can you make Excel talk to you using the Speak Method on a Range Object? In the VBE your macro will look something like: Sub Speak_to_me() Your code goes here End Sub Also can you use the Orientation Property on a Range Object so the text direction in a cell is vertical? The Help in the VBE might be useful if you are stuck!
Useful Properties
Property ActiveCell Object Returned The active cell.
Properties
Property Object Returned
ActiveSheet
ActiveWorkbook
Properties
Property Selection Object Returned The object selected. (It could be a Range object, Shape, ChartObject, and so on.)
Cells Property
You can also use the Cells property on a Range object. When you do so the Cells property is relative to the upper-left cell of the referenced Range. Thus: Range("B3:B10"). Cells(1,1) = 5 Puts the value of 5 into Cell B3 Range("B3:B10"). Cells(2,1) = 5 Puts the value of 5 into Cell B4
Offset Property
When you record a macro using the relative reference mode, Excel uses the Offset property to reference cells relative to the starting position. The syntax is: object.Offset(rowOffset, columnOffset)
Outline
Introduction to programming in VBA Variables Data Types Loops Error Checking
Introduction to Programming
We now have learnt about objects, properties, and methods but we havent really done anything very useful with them. We will now look at VBA language elements so we can start writing VBA routines.
Comments
A comment is descriptive text embedded within your code and ignored by VBA. It's a good idea to use comments liberally to describe what you're doing because an instruction's purpose is not always obvious. You can use a complete line for your comment, or you can insert a comment after an instruction on the same line. A comment is indicated by an apostrophe. VBA ignores any text that follows an apostrophe
Variables
A variable is simply a named storage location in your computer's memory. Variables can accommodate a wide variety of data types - from simple Boolean values (True or False) to large, double-precision values. You assign a value to a variables using the equal sign operator. Some examples of variable assignments are: x=1 Pressure = 0.075 Lift_Coefficient = 0.65 Counter = Counter + 1 UserName = "Mathew" DateStarted = #12/14/2006#
Data Types
VBA makes life easy for programmers because it can automatically handle all the details involved in dealing with data Data type refers to how data is stored in memory - as integers, real numbers, strings, and so on
+/-1.79769313486231 E308
January 1, 100 to December 31, 9999 0 to approximately 2 billion Same as for Double and String
Generally the Double and String data types are the most often used.
Data Types
It's good practice to define data types The main advantage of defining data types is to increase the speed of programs dealing with a lot of data. When using Arrays the Variant Data Type allows VBA to automatically determine the Data Type To force yourself to declare all the variables that you use, include the following as the first instruction in your VBA module: Option Explicit When this statement is present, VBA will not even execute a procedure if it contains an undeclared variable name.
Constants
You declare constants with the Const statement. Here are some examples: Const UltimateFactor as Double = 1.5 Const MaxG = 4.0, FlightTime = 12
Logical Operators
Operator Not And Or What It Does Performs a logical negation on an expression Performs a logical conjunction on two expressions Performs a logical disjunction on two expressions
The following will display a message box with the word true if either Sheet1 or Sheet2 is the active sheet.
MsgBox ActiveSheet.Name = "Sheet1" Or ActiveSheet.Name = "Sheet2"
Arrays
An array is a group of elements of the same type that have a common name. You refer to a specific element in the array by using the array name and an index number. You declare an array with a Dim statement, just as you declare a regular variable You can also specify the number of elements in the array. You do so by specifying the first index number, the keyword To, and the last index number - all inside parentheses Dim MyArray(1 To 10) As Integer
Arrays
To refer to a specific element in an array, you need to specify an index number Here's how you can assign a value to an element in the array MyArray(3) = 125
Arrays
Create an array yourself containing 3 integers and print them in cells A1 to A3. Your code will look something like this: Sub TestArray() Dim MyArray(1 To 3) As Integer MyArray(1) = 11 MyArray(2) = ...... .............. Range("A1") = MyArray(1) Range("A2") = ..... ....... End Sub
Dynamic Arrays
A dynamic array doesn't have a preset number of elements. You declare a dynamic array with a blank set of parentheses: Dim MyArray() As Integer
Before you can use a dynamic array in your code, however, you must use the ReDim statement to tell VBA how many elements are in the array. This is often done by using a variable, the value of which isn't known until the procedure is executing
ReDim MyArray (1 to x)
Loops
Often you need to control the flow of your routines by skipping over some statements, executing some statements multiple times, and testing conditions to determine what the routine does next.
Exercise: Can you reverse this code to take the values in Cells A1 to A3 and place them in an Array? Try using MsgBox MyArray(1) to check the contents of your array
Sub InPutArray() Dim MyArray(1 To 3) As Integer Dim Cell As Range Dim Counter As Integer Counter = 1 Range("A1:A3").Select For Each Cell In Selection MyArray(Counter) = Cell.Value MsgBox MyArray(Counter) Counter = Counter + 1 Next Cell End Sub
Solving Errors
This code works as expected: Sub ArrayTest() Dim MyArray(1 To 3, 1 To 1) As Integer MyArray(1, 1) = 1: MyArray(2, 1) = 2: MyArray(3, 1) = 3 Range("B2:B4").Value = MyArray End Sub Test this code and see if you can explain the error? Sub ArrayTest() Dim MyArray(1 To 3) As Integer MyArray(1) = 1: MyArray(2) = 2: MyArray(3) = 3 Range("B2:B4").Value = MyArray End Sub
If - Then Construct
The basic syntax of the If-Then construct is: If condition Then true_instructions [Else false_instructions] The following procedure demonstrates an If-Then structure without an Else clause. The example deals with time, and VBA uses a dateand-time serial number system similar to Excel's. The time of day is expressed as a fractional value - for example, noon is represented as .5: Sub GreetMe1() If Time < 0.5 Then MsgBox "Good Morning" End If End Sub
If - Then Construct
An If Then Else construct could be used to add an afternoon greeting: Sub GreetMe2() If Time < 0.5 Then MsgBox "Good Morning" Else MsgBox "Good Afternoon" End If End Sub
If - Then Construct
You can also use nested If Then loops if required: Sub GreetMe3() If Time < 0.5 Then MsgBox "Good Morning" Else If Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon" Else If Time >= 0.75 Then MsgBox "Good Evening" End If End If End If End Sub