51
Introduction to VBA Mathew Stoessiger

VBA 2010 Day1 Presentation

Embed Size (px)

Citation preview

Page 1: VBA 2010 Day1 Presentation

Introduction to VBA

Mathew Stoessiger

Page 2: VBA 2010 Day1 Presentation

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

Page 3: VBA 2010 Day1 Presentation

Setting up Excel and the VBE

• The Excel 2007 Ribbon does not display the Developer tab by default. If you're going to be working with VBA, it's essential that you turn on the Developer tab:

• Choose Office Excel Options.• In the Excel Options dialog box, click the Popular tab.• Place a checkmark next to Show Developer Tab in the

Ribbon.

Page 4: VBA 2010 Day1 Presentation

Activating the VBE

• When you're working in Excel, you can switch to the VBE by using either of the following techniques:

• Press Alt+F11.• Choose Developer Code Visual Basic.• Right-click a sheet tab and choose View Code

(this takes you to the code module for the sheet).

Page 5: VBA 2010 Day1 Presentation

The VBE

Page 6: VBA 2010 Day1 Presentation

Customizing the VBE Environment

• Tools →Options

Page 7: VBA 2010 Day1 Presentation

Recording Macros

• We'll now look at some examples of how to record macros.

Page 8: VBA 2010 Day1 Presentation

Limitations on recording Macros

• You can't undo a macro• The Macro recorder creates a lot of

unnecessary code • Just because it's a repetitive action does not

mean that you can record a macro• The macro recorder does not record actions

that don't happen in Excel

Page 9: VBA 2010 Day1 Presentation

Exercises

• Modifying the .bdf files

Page 10: VBA 2010 Day1 Presentation

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

Page 11: VBA 2010 Day1 Presentation

Objects• Thus 4 Objects were used to specify Cell A1

Application.Workbooks("Book1").Worksheets("Sheet1").Range("A1")

Application Object

Workbook Object

Worksheet Object

Range Object

Page 12: VBA 2010 Day1 Presentation

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

Page 13: VBA 2010 Day1 Presentation

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

Page 14: VBA 2010 Day1 Presentation

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:

Sub ShowValue() Msgbox Worksheets("Sheet1").Range("A1").Value End Sub

• Try it out!Object Property

Page 15: VBA 2010 Day1 Presentation

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

Page 16: VBA 2010 Day1 Presentation

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

Page 17: VBA 2010 Day1 Presentation

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 hereEnd 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!

Page 18: VBA 2010 Day1 Presentation

Useful PropertiesProperty Object Returned

ActiveCell The active cell.

• Some commonly used Methods of ActiveCell are: ActiveCell.Value = 1 and ActiveCell.ClearContents

• Try them out for yourself

Page 19: VBA 2010 Day1 Presentation

PropertiesProperty Object Returned

ActiveSheet The active sheet (worksheet or chart).

ActiveWorkbook The active workbook.

• The example that follows displays a message that tells you the name of the active sheet: MsgBox ActiveSheet.Name

•If you want to know the name and directory path of the active workbook, use a statement like this: MsgBox ActiveWorkbook.FullName

Page 20: VBA 2010 Day1 Presentation

PropertiesProperty Object Returned

Selection The object selected. (It could be a Range object, Shape, ChartObject, and so on.)

• If a range on a worksheet is selected, you can fill the entire range with a value by executing a single statement: Selection.Value = 12

Page 21: VBA 2010 Day1 Presentation

Working with Range Objects

• The Range property returns a Range object. If you consult the Help system for the Range property, you learn that this property has two syntaxes: object.Range(cell1) object.Range(cell1, cell2)

• We have seen previously a statement like: Worksheets("Sheet1").Range("A1").Value = 12.3

Page 22: VBA 2010 Day1 Presentation

Working with Range Objects• The example that follows enters the same value into a range of 20

cells on the active sheet. ActiveSheet.Range("A1:B10").Value = 2

• The next example produces exactly the same result as the preceding example: Range("A1", "B10") = 2

• And finally, this next example enters the value 4 into five cells: that is, a non-contiguous range. The comma serves as the union operator: Range("A1,A3,A5,A7,A9") = 4

Page 23: VBA 2010 Day1 Presentation

The Cells Property• Another way to reference a range is to use the Cells property. This

property is particularly useful when using loops. The syntax is: object.Cells(rowIndex, columnIndex)

• The first example enters the value 34 into cell A1 on Sheet1 using index number of the row (from 1 to 1,048,576) and the index number of the column (from 1 to 16,384): Worksheets("Sheet1").Cells(1, 1) = 34

• Here's an example that enters the value 67 into cell C5 (that is, row 5, column 3) in the active worksheet:

ActiveSheet.Cells(5, 3) = 67

Page 24: VBA 2010 Day1 Presentation

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

• What Cell is modified below? Range("B3:C10").Cells(3, 2) = 89

Page 25: VBA 2010 Day1 Presentation

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)

• An example would be• Sub Offset()

ActiveCell.Offset(0, 0) = 1 ActiveCell.Offset(1, 0) = 2 ActiveCell.Offset(2, 0) = 3 End Sub

Page 26: VBA 2010 Day1 Presentation

Outline

• Introduction to programming in VBA• Variables• Data Types• Loops• Error Checking

Page 27: VBA 2010 Day1 Presentation

Introduction to Programming

• We now have learnt about objects, properties, and methods but we haven’t really done anything very useful with them.

• We will now look at VBA language elements so we can start writing VBA routines.

Page 28: VBA 2010 Day1 Presentation

Introduction to VBA Programming• The program below calculates the value of

1 x 2 x 3 x 4 x 5.

Sub Factorial() 'Calculates the factorial of 5 Dim Total As Integer, i As Integer Total = 1 For i = 1 To 5 Total = Total * i Next i MsgBox Total End Sub

Page 29: VBA 2010 Day1 Presentation

Introduction to VBA Programming

• The accepted practice is to use one instruction per line as it looks neater

• Each line can be as long as you like; for readability VBA's line continuation sequence is a space followed by an underscore Dim Total As Integer, _ i As Integer

• VBA variable names are not case-sensitive• VBA scans the instruction for syntax errors. If VBA finds an

error, it changes the color of the line and might display a message describing the problem

Continuation Sequence

Page 30: VBA 2010 Day1 Presentation

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

Page 31: VBA 2010 Day1 Presentation

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.65Counter = Counter + 1UserName = "Mathew" DateStarted = #12/14/2006#

Page 32: VBA 2010 Day1 Presentation

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

Page 33: VBA 2010 Day1 Presentation

Main Data TypesData type Range

Boolean True or False

Integer -32,768 to 32,767

Long(long integer) -2,147,483,648 to 2,147,483,647

Double(double-precision floating-point)

+/-1.79769313486231 E308

Date January 1, 100 to December 31, 9999

String(variable-length) 0 to approximately 2 billion

Variant Same as for Double and String

• Generally the Double and String data types are the most often used.

Page 34: VBA 2010 Day1 Presentation

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.

Page 35: VBA 2010 Day1 Presentation

Constants

• You declare constants with the Const statement. Here are some examples:

Const UltimateFactor as Double = 1.5

Const MaxG = 4.0, FlightTime = 12

Page 36: VBA 2010 Day1 Presentation

Using Predefined Constants• Excel and VBA make available many predefined

constants, which you can use without declaring. In fact, you don't even need to know the value of these constants to use them.

• The macro recorder generally uses constants rather than actual values. The following procedure uses a built-in constant (xlLandscape) to set the page orientation to landscape for the active sheet

Sub SetToLandscape() ActiveSheet.PageSetup.Orientation = xlLandscape End Sub

Page 37: VBA 2010 Day1 Presentation

Logical OperatorsOperator What It Does

Not Performs a logical negation on an expression

And Performs a logical conjunction on two expressions

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

• Other operators are also valid such as< > *+

Page 38: VBA 2010 Day1 Presentation

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

Page 39: VBA 2010 Day1 Presentation

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 arrayMyArray(3) = 125

Page 40: VBA 2010 Day1 Presentation

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

Page 41: VBA 2010 Day1 Presentation

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)

Page 42: VBA 2010 Day1 Presentation

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.

Page 43: VBA 2010 Day1 Presentation

For – Next LoopsThe factorial program we looked at earlier contains a For – Next loop

Sub Factorial() 'Calculates the factorial of 5 Dim Total As Integer, i As Integer Total = 1 For i = 1 To 5 Total = Total * i MsgBox "The value of i = " & i & " and Total = " & Total Next i MsgBox "The factorial of 5 is " & Total End Sub

Page 44: VBA 2010 Day1 Presentation

For Each – Next Loop

• A variation on the For Next Loop is very powerful and allows you to perform actions on Objects in a Collection.

• A common use for the For Each-Next construct is to loop through all cells in a range

Page 45: VBA 2010 Day1 Presentation

For Each – Next Loop• The code we used before for the arrays can be modified to take advantage of the For

Each – Next loop

Sub OutPut() Dim MyArray(1 To 3) As Integer Dim Cell As Range Dim Counter As Integer MyArray(1) = 11 : MyArray(2) = 12 : MyArray(3) = 13 Counter = 1 Range("A1:A3").Select For Each Cell In Selection Cell.Value = MyArray(Counter) Counter = Counter + 1 Next CellEnd Sub

• 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

Page 46: VBA 2010 Day1 Presentation

For Each – Next Loop• This is what your code could look like

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 CellEnd Sub

Page 47: VBA 2010 Day1 Presentation

Transferring Arrays to Worksheets

• Looping through the cells in a range is not the fastest way to transfer an Array to a worksheet you can also do this:

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 = MyArrayEnd Sub

Page 48: VBA 2010 Day1 Presentation

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 = MyArrayEnd 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 = MyArrayEnd Sub

Page 49: VBA 2010 Day1 Presentation

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 date-and-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

Page 50: VBA 2010 Day1 Presentation

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 IfEnd Sub

Page 51: VBA 2010 Day1 Presentation

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