VBA Reference Manual

33
PROJECT/JOB TITLE: Visual Basic For Applications Reference DOCUMENT TYPE: Reference DOCUMENT TITLE: Excel Visual Basic for Applications Reference Manual DOCUMENT NO./ FILE NAME: VBA Reference Manual.docx Rev Date Description Issued By Checked By Approved By Client Approval

description

Simple VBA guide

Transcript of VBA Reference Manual

Page 1: VBA Reference Manual

PROJECT/JOB TITLE: Visual Basic For Applications Reference

DOCUMENT TYPE: Reference

DOCUMENT TITLE: Excel Visual Basic for Applications Reference Manual

DOCUMENT NO./FILE NAME: VBA Reference Manual.docx

Rev Date Description Issued By Checked By

Approved By

Client Approval

Page 2: VBA Reference Manual

Table of Contents

1 OVERVIEW..........................................................................................................3

2 VARIABLES AND DATA TYPES........................................................................4

2.1 NUMERICAL DATA TYPES..................................................................................52.2 STRING DATA TYPE..........................................................................................52.3 BOOLEAN DATA TYPE.......................................................................................52.4 ARRAYS...........................................................................................................5

3 PROCEDURES....................................................................................................7

4 ACCESSING EXCEL OBJECTS.........................................................................8

4.1 APPLICATION OBJECT.......................................................................................84.2 WORKBOOK OBJECT........................................................................................84.3 WORKSHEET OBJECT.......................................................................................84.4 RANGE OBJECT...............................................................................................9

4.4.1 Values...................................................................................................10

4.4.2 Formulas...............................................................................................10

4.4.3 Offset.....................................................................................................10

4.4.4 Selecting................................................................................................11

4.4.5 Copy and Paste.....................................................................................11

4.4.6 Accessing Merged Cells........................................................................12

4.4.7 Cell Formatting......................................................................................12

5 BOOLEAN LOGIC AND CONDITIONAL STATEMENTS.................................14

5.1 BOOLEAN LOGIC............................................................................................145.2 IF-THEN-ELSE................................................................................................145.3 SELECT-CASE................................................................................................15

6 LOOPS...............................................................................................................17

6.1 FOR-NEXT.....................................................................................................171.1.1 Exit For..................................................................................................19

1.1.2 Nested For Loops..................................................................................19

1.1.3 For-Each-Next.......................................................................................20

6.2 DO-WHILE.....................................................................................................20

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 3: VBA Reference Manual

1 OVERVIEWThe purpose of this document is to provide a reference for basic commands and syntax for writing macros using the Visual Basic for Applications (VBA) programming language embedded within MS Excel. This document presupposes that the reader has some basic knowledge of programming and knows how to access the Visual Basic Editor from within Excel.For more in-depth tutorials on programming with VBA refer to the following online resources:

http://www.anthony-vba.kefra.com/index_011.htmhttp://excelvbatutor.com/vba_tutorial.htmlhttp://www.homeandlearn.org /

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 4: VBA Reference Manual

2 VARIABLES AND DATA TYPESA variable is a symbolic name used to refer to a particular quantity/data or to an object. Alternatively a variable can be thought of as an element of a program that stores information. The information can be stored in variables and then accessed later via the variables’ names.

As per good programming practice variables should be declared upfront before they are used and the variable given a descriptive name. Variables are declared in VBA with the ‘Dim’ statement as per the examples below.

Dim Fluid_Temp As DoubleDim Filename As StringDim Row_Num As IntegerDim IsEmpty As Boolean

Notice that the variables declared above have been given a data type. The data type defines what kind of data can be stored in the declared variable. Figure 2-1 below provides a summary of VBA data types.

Figure 2-1: VBA data types

The most commonly used data types are numerical data types (i.e. Integer, Long, Single or Double), String and Boolean. Note that when assigning/referencing an

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 5: VBA Reference Manual

object to a variable the Set keyword must be used such as in the example below which stores a reference to a range of cells in the variable myCells and then selects this range.

Dim myCells As RangeSet myCells = Sheet1.Range(“A1:D4”)myCells.Select

2.1 Numerical Data TypesFigure 2-1 above lists 4 numerical data types: Integer, Long, Single and Double. Integer and Long data types can only store whole numbers. Single and Double data types can store floating-point/decimal numbers. If you attempt to store a floating-point number in integer or long variable the number will be rounded to the nearest whole number.

The example below demonstrates multiplication of numerical variablesDim hrs_worked As IntegerDim pay_rate As DoubleDim total_pay As Double

hrs_worked = 8pay_rate = 41.5total_pay = hrs_worked * pay_rate

2.2 String Data TypeString variables hold text. Strings are denoted by quotation marks as shown in the example below.

Dim reg_number As Stringreg_number = “1ABC 234”

2.3 Boolean Data TypeBoolean variables can hold a value of either True or False. Numbers can also be stored as Booleans with 0 being False and non-zero numbers being True.

Dim condition As Booleancondition = False

2.4 ArraysArrays are a collection of variables of the same data type referred to by the same name. Arrays are declared by defining the array name and its bounds. E.g.

Dim exampleArray(1 to 10) As IntegerThe lower bound can be omitted and VBA will assume that the lower bound is 0 by default E.g.

Dim exampleArray(10) As Integer

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 6: VBA Reference Manual

A specific variable within an array can then be accessed via the array name and an index number which indicates the position of the variable within the array. E.g.

exampleArray(5) = 1345Range(“A5”) = exampleArray(5)

Arrays can be multidimensional as per the example below.Dim exampleArray(1 to 3, 1 to 10) As Integer

Again the lower bound can be omitted and VBA will assume that the lower bound is 0 by default E.g.

Dim exampleArray(2, 9) As IntegerVariables can be accessed by specifying its position in each dimension defined for the array. E.g.

exampleArray(2, 5) = 1345Range(“A5”) = exampleArray(2, 5)

Arrays can be declared dynamically, where the size/dimensions of the array are not defined up front. E.g.

Dim exampleArray() As IntegerThe dimensions of the array can then be defined at a later point with the ReDim method. E.g.

ReDim exampleArray(5, 5)The ReDim method can be used with any array that has previously been declared whether the dimensions have previously been defined or not. The ReDim method will clear all values previously stored in the array unless the preserve statement is used E.g.

ReDim Preserve exampleArray(5, 5)

The lower and upper bounds of an array dimension can be reported using the LBound and UBound methods. E.g.

if an array has been declared exampleArray(8), then LBound(exampleArray) will return 0 and UBound(exampleArray) will return 8.

If an array has been declared exampleArray(2 to 9), then LBound(exampleArray) will return 2 and UBound(exampleArray) will return 9.

If an array has been declared exampleArray(3 to 6, -3 to 4) then:o LBound(exampleArray, 2) will return -3 i.e. lower bound of 2nd

dimension.o UBound(exampleArray, 1) will return 6 i.e. upper bound of 1st

dimensiono LBound(exampleArray) will return 3 i.e. lower bound of 1st dimension

because if no dimension is specified the LBound and UBound methods assume the 1st dimension be default.

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 7: VBA Reference Manual

3 PROCEDURESMost code programmed in VBA will be contained in either a sub, function or event procedure.

A sub procedure contains code that will execute a programmed action or series of actions when that sub procedure is specifically called upon.

A function procedure contains code that will perform actions and calculations and return a single value similar to SUM, MAX or MIN excel functions

An event procedure contains code that will execute programmed actions when a certain event occurs. E.g. the workbook is opened or a button is clicked.

3.1 Public and Private Procedure ScopeProcedures can be declared either public or private. Declaring a procedure public makes the procedure accessible to all other procedures in all modules in the project. Declaring a procedure private that the procedure is accessible only to other procedures within the same module. If private or public is not specified, then the procedure is public by default.

3.2 Sub ProceduresA sub procedure is created according to the following syntax

[Private/Public] Sub Sub_Name(Arg1 As DataType, … etc)[VBA code to execute actions]

End SubEach procedure must be given a unique name and may contain a number of arguments that can be passed to the sub procedure to be used in the code within the procedure. The type of each argument must be specified.

E.g. the following procedure will receive a message and a cell row and cell column and write the message to that cell.

Private Sub WriteMsgtoCell(Msg As String, row As Integer, col As Integer)Cells(row, col) = Msg

End Sub

The above sub procedure can then be called from another procedure e.g.Private Sub PersonalMsg()

Dim name As Stringname = Val(InputBox(“What is your name?”))WriteMsgtoCell “Hi ” & name, 2, 2

End SubWhich gets a name from the user and writes a message with that name into cell B2.

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 8: VBA Reference Manual

Sub procedures with no arguments can be run from the visual basic editor by pressing the F5 key or the run sub/userform icon with the sub procedure selected in the code window. Alternatively sub procedures can be assigned to buttons or shapes in the worksheets and will execute when the button/shape is clicked.

3.3 Function ProceduresA function procedure is created according to the following syntax

[Private/Public] Function Func_Name(Arg1 As DataType, … etc) As DataType[VBA code to execute actions/calculations]Func_Name = expression

End FunctionThe function procedure works in the same way as the sub procedure except that it will return a value as defined by the code in the expression in the syntax example above. The code below is an example of a function that will calculate the area of a triangle of base length ‘b’ and height ‘h’

Function TriArea(b As Double, h As Double) As DoubleTriArea = 0.5 * b * h

End Function

This function can then be used in other procedures e.g.Sub OutputTriArea()

Dim base As DoubleDim height As DoubleDim result As Doublebase = Val(InputBox(“Enter the base length.”, “Base”))height = Val(InputBox(“Enter the height.”, “Height”))result = TriArea(base, height)MsgBox (“The area is” & result)

End Sub

3.4 Event ProceduresAn event procedure is a subset of the sub procedure type. They are declared in exactly the same was as an ordinary sub procedures. Event procedures automatically execute upon a particular event in Excel occur. Examples of such events include:

A workbook is opened/closed. A workbook/worksheet is activated/deactivated. A workbook is saved. A workbook is calculated. When a button is clicked When a particular key or key combination is pressed. A particular time of day occurs. An error occurs.

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 9: VBA Reference Manual

Event procedures have specific names reflecting the associated object and event i.e. Object_Event. Event procedures can be most easily added via the Visual Basic Editor by selecting the relevant object and event from the dropdown boxes at the top of the code window. E.g. the screenshot below shows a NewSheet even being added for the workbook. This sub procedure will execute when ever a new sheet is created.

Figure 2-2: Visual Basic Editor - Adding Event Procedure

The code sample below if included in the code for the ‘ThisWorkbook’ module will enter the date and time the workbook was opened in the first cell in the workbook and force the workbook to calculate every time the workbook is opened in Excel.

Private Sub Workbook_Open()Sheet1.Range(“A1”) = NowApplication.Calculate

End Sub

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 10: VBA Reference Manual

4 ACCESSING EXCEL OBJECTSExcel objects are the various ‘parts’ of excel that can be accessed and modified via macros. The hierarchy of excel objects is as follows:

1. Application2. Workbooks3. Workbook4. Sheets5. Worksheet6. Range

I.e. the Excel Application contains a collection of workbooks; Each workbook contains a collection of sheets and each sheet contain ranges of cells.

4.1 Application ObjectThe application object refers to the entirety of the Excel Application. Below are some examples of access Excel functionality via the Application object.

Calculate all formulas in all open workbooks.Application.Calculate

Set calculation to manual or automaticApplication.Calculation = xlCalculationManualApplication.Calculation = xlCalculationAutomatic

Use Excel Internal Functions e.g.Range(“A1”) = Application.WorksheetFunction.Sum(Range(“B1:B10”))

For more examples see http://www.xlpert.com/partC.htm section (b)

4.2 Workbook ObjectA workbook object refers to an open excel workbook within the Excel application. These objects are not referenced often. For examples with accessing the workbook object see http://www.xlpert.com/partC.htm section (c)

4.3 Worksheet ObjectA worksheet object refers to sheets in an open excel workbook. A particular sheet can be accessed in a number of ways.

Figure 4-3 below shows the project window for a workbook containing 3 worksheets.The examples below shows how to enter the string “ABCD” in the top left cell in the second sheet in this workbook by referencing the second worksheet in 3 different ways.

Sheet2.Range(“A1”) = “ABCD”Sheets(2).Range(“A1”) = “ABCD”Sheets(“Second Sheet”).Range(“A1”) = “ABCD”

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 11: VBA Reference Manual

Figure 4-3: Example Workbook and Worksheets

 The example code below will rename the second worksheet to “Sheet B”.Sheets(“Second Sheet”).Name = “Sheet B”

The example code below will add a sheet to the end of the workbook and rename it to “Sheet Z”.

Dim newSheet As WorksheetSet newSheet = Sheets.Add(After:=Sheets(Sheets.Count))newSheet.Name = “Sheet Z”

The example code below will delete the first sheet in the workbook.Sheets(“First Sheet”).Delete

The example code below will activate the third sheet in the workbook. Activating a worksheet is sometimes necessary prior to executing certain actions such as selecting cells.

Sheets(“Third Sheet”).Activate

For more examples see http://www.xlpert.com/partC.htm section (d) and (e)

4.4 Range ObjectThe range object is used to refer to one or more cells in a worksheet. The range object can be used to access a single cell e.g. Range(“D3”), a connected group of cells e.g. Range(“D3:F6”), a disconnected group of cells e.g. Range(“D3:F6”, “G8:G10”, “Z100”) or an entire row e.g. Range(“4”) or column e.g. Range(“E”).

Single cells can also be accessed using the cell property using the following syntax - Cells(Row, Column). The code below shows how to enter the string “ABCD” in cell B3 via 2 different methods.

Cells(3, 2) = “ABCD”

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 12: VBA Reference Manual

Cells(3, “B”) = “ABCD”Cells can be used in conjunction with a Range to access a particular cell within a Range by specifying a relative position. E.g. Range(“D3:J10”).Cells(4, 3) will access cell ‘F6’ (i.e. 4 rows down from ‘D’ and 3 columns across from ‘3’).

When accessing ranges/cells be careful to specify the worksheet the range/cell belongs to. E.g.

Sheets(“Third Sheet”). Range(“A4”) = “ABCD”If the sheet is not specified VBA will assume:

the current active worksheet if the code is written within a module or the worksheet containing the code if the code is written within a sheet.

Below are some examples of interacting with Range/Cell objects via VBA.

4.4.1 Values

The value contained within a range/cell is accessed (written or read) via the value property. E.g.

Dim prop As StringDim propVal As Double

Range(“A2”).Value = “Temperature”Range(“B2”).Value = 120.2prop = Range(“A2”).ValuepropVal = Range(“B2”).Value

However if no range property is specified then the value property is assumed by VBA. E.g.

Range(“A2”) = “Temperature”prop = Range(“A2”)

4.4.2 Formulas

The example below enters a simple addition formula in a cell.Range(“A1”).Formula = “=B1+B2”

The example below enters a summation formula in each cell in A1:D1. The formulas will be entered with relative referencing i.e. A1 will contain SUM(A2:A6), B1 will contain SUM(B2:B6) etc.

Range(“A1”).Formula = “=SUM(A2:A6)”

4.4.3 Offset

Cells can also be accessed relative to other cells using the offset method. Offset(RowOffset, ColumnOffset)

The example below writes “ABCD” in cell E3.Range(“C5”).Offset(-2, 2) = “ABCD”

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 13: VBA Reference Manual

4.4.4 Selecting

Macros can be used to replicate navigation around a worksheet with keyboard and mouse with VBA code. Any excel object can be ‘selected’ with the select method. The selection can then be accessed with further commands.Any range can be selected. Note that the worksheet contain the cells must be the active sheet. For example a group of cells can be selected:

Sheets(“First Sheet”).ActivateSheets(“First Sheet”).Range(“B2:B5”).Select

Or a column or row:Sheets(“First Sheet”).Range(“B:B”).SelectSheets(“First Sheet”).Range(“2:2”).Select

Or all cells in a worksheetSheets(“First Sheet”).Cells.Select

The selected range can then be copied or deleted for exampleSelection.CopySelection.Delete

Or the cell addresses of the selection can be returnedSelection.Address

The following code replicates the CTRL+, CTRL+, CTRL+↑ and CTRL+↓ keyboard short cuts.

Selection.End(xlLeft).SelectSelection.End(xlRight).SelectSelection.End(xlUp).SelectSelection.End(xlDown).Select

Worksheets can also be selected e.g.Sheets(“Third Sheet”).Select

4.4.5 Copy and Paste

The example below copies the contents of a range of cells from the first worksheet to the second worksheet in Figure 4-3.

Sheets("First Sheet").Range("C6:C12").CopySheets("Second Sheet").Paste Sheets("Sheet2").Range("A2")

The use excel Paste Special functionality a slightly different syntax is used. The following example will Paste the values and formats of a range of cells from the first worksheet to the second worksheet in Figure 3-1.

Sheets("First Sheet ").Range("C6:C12").CopySheets("Second Sheet ").Range("A2").PasteSpecial Paste:=xlPasteValuesSheets("Second Sheet ").Range("A2").PasteSpecial Paste:=xlPasteFormats

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 14: VBA Reference Manual

4.4.6 Accessing Merged Cells

Merged cells can only be accessed via the top left cell of the merged area. For example if the range F3:G6 is a merged area containing the text “ABCD”:

x = Range(“F3”).Value Range(“F3”).Value = “EFGH”

will work normally, butx = Range(“F4”).ValueRange(“F4”).Value = “EFGH”

will not get or set any value.

When trying to access the contents of merged cells via a cell that is not the top left cell code similar to the code below can be used. Again the merged area is F3:G6.

x = Sheets("First Sheet").Range("G4").MergeArea.Cells(1, 1)Sheets("First Sheet").Range("G4").MergeArea.Cells(1, 1) = "EFGH"

The code above effectively finds and then accesses the top left cell of the merged area that cell “G4” belongs to.

4.4.7 Cell Formatting

The following code will highlight a cell with a red background.Range(“B4”).Interior.ColorIndex = 3

This sets the interior of the cell to the colour matching the numerical identifier of 3, which is red. Figure 4-4 below shows all the maps all colour indices from 0 to 56 with its matching colour.

Alternatively the following code can also be used to highlight a cell red.Range(“B4”).Interior.Color = RGB(255, 0, 0)

The RGB function creates a colour by mixing amounts (from 0 to 255) of red, green and blue. E.g. white is RGB(255, 255, 255), black is RGB(0, 0, 0) and Yellow is RGB(255, 255, 0).

The font colour of a cell can be similarly changed. E.g.Range(“B4”).Font.ColorIndex = 3Range(“B4”).Font.Color = RGB(255, 0, 0)

Font can be bolded or italicised E.g.Range(“B4”).Font.Bold = TrueRange(“B4”).Font.Italic = True

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 15: VBA Reference Manual

Figure 4-4: Colour Index Chart

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 16: VBA Reference Manual

5 BOOLEAN LOGIC AND CONDITIONAL STATEMENTSBoolean logic and conditional statements can be used to execute different actions based on a condition is true or false. This can be done with a If-Then-Else statement or a case-select statement.

5.1 Boolean LogicBelow are examples of common boolean operations that can be used in conditional statements, where A, B and C are variables that can be compared e.g. integers or strings. These operations will return a value of true or false.

A = B A equals BA <> B A does not equal BA > B A greater than BA < B A less than BA >= B A greater than or equal to BA <= B A less than or equal to BA=B And B<C A equals B and B less than CA<B Or C<B A less than B or C less than BNOT A+B>C Not A+B greater than C i.e. A+B less than C

5.2 If-Then-ElseThe most basic conditional statement is the If-Then statement which will execute a block of code if the stated condition is met. The syntax for the statement in VBA is:

If Condition Then ‘Block of code statementsEnd If 

For example, the code below compares two variables operating_pressure and design_pressure and will enter text in Cell A1 if the operating_pressure is greater than design_pressure.

If operating_pressure > design_pressure Then Range(“D2”) = “Warning: Operating P is higher than the Design P”End If

The If-Then statement can be expanded into an If-Then-Else statement. The syntax for an If-Then-Else statement is:

If Condition Then ‘This block of code executes if the condition is true

  Else ‘This block of code executes if the condition is false.End If

For example the code below uses an If-Then-Else statement to enter the smaller of two numbers, A and B, into cell D2

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 17: VBA Reference Manual

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 18: VBA Reference Manual

If A < B Then Range(“D2”) = AElse Range(“D2”) = BEnd If

Additional conditions can be added to If-Then-Else statements by using the ElseIf according to the following syntax

If Condition 1 Then ‘This block of code executes if the condition 1 is trueElseIf Condition 2 Then ‘This block of code executes if the condition 1 is false and condition 2 is ‘trueElse ‘This block of code executes if the condition 1 is false and condition 2 is ‘falseEnd If

For example the following code enters the smallest of three numbers, A, B and C, into cell D2.

If A < B And A < C Then Range(“D2”) = AElseIf B < A And B < C Then Range(“D2”) = BElse Range(“D2”) = CEnd If

5.3 Select-CaseA select-case statement can be used in place of If-Then-Else statements in situations that require large numbers of ElseIf statements. The syntax of a select-case statement is:

Select Case expression Case condition 1 ‘This block of code executes if condition 1 is true. Case condition 2 ‘This block of code executes if condition 2 is true. … Case condition n This block of code executes if condition n is true. Case Else ‘This block of code executes if all conditions above are false.End Select

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 19: VBA Reference Manual

The expression is a statement that is evaluated (often just a single variable) and compared to the condition/value of each case in the select-case structure. If there is a match between the expression and the condition of a case, then the block of code associated with the case is executed.

The following example uses a select-case structure to map integers from 1 to 7 to the days of the week.

Select Case Range(“A1”) Case 1 Range(“B1”) = “Monday” Case 2 Range(“B1”) = “Tuesday” Case 3 Range(“B1”) = “Wednesday” Case 4 Range(“B1”) = “Thursday” Case 5 Range(“B1”) = “Friday” Case 6 Range(“B1”) = “Saturday” Case 7 Range(“B1”) = “Sunday” Case Else Range(“B1”) = “Warning: Not a number from 1 to 7”End Select

Case conditions can also consist of condition statements or express a range of values. E.g.

Case 1 To 5, 7, 9, Is > 20

The case conditions also apply to strings. E.g. in the code below the case matches strings that are exactly equal to SST, fall alphabetically between ALI and GAJ and are exactly equal to the string stored in the variable initials.

Case “SST”, “ALI” To “GAJ”, initials

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 20: VBA Reference Manual

6 LOOPSLoops are used to execute a block of code multiple times. There are two types of loop structures, the For-Next loop and the Do-While loop.

6.1 For-NextThe For-Next loop structure is used when the number of iterations/repetitions is known. The For-Next loop has the following syntax:

For counter = start To end [Step stepval][statements]

Next [counter]The counter variable increments from the start To end values with the increment intervals set by the stepval value. The code statements between the For and Next statements are executed each increment.

The example below calculates the sum of integers from 0 to 10.Dim n As IntegerDim total As IntegerFor n = 0 To 10 total = total + nNext n

Using the step statement the above code can be modified to sum only the even numbers from 0 to 10 E.g.

Dim n As IntegerDim total As Integer Step 2For n = 0 To 10 total = total + nNext n

The example below uses a For-Next loop to find the largest number stored in an array named numbers.

Function Maximum(numbers() As Single) As Single Dim i As Integer Maximum = -3.402823E+38 For i = LBound(numbers) To UBound(numbers) If numbers(i) > Maximum Then Maximum = numbers(i) End If Next iEnd Function

Note that the Maximum variable is initialised to -3.402823E+38, which is the lowest value that a Single can take (see Figure 2-1). This ensures that the function will

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 21: VBA Reference Manual

always return some value from the array because the statement numbers(i) > Maximum will be true at least once.The example below uses a For-Next Loop to find the position of the entry in the first 10 rows of a spreadsheet in Column ‘A’ that matches the entry in Cell ‘B1’. A value of True will be entered in Cell ‘C1’ if a match exists and False if the match does not exist. If a match exists the row of the match will be entered in Cell ‘C2’.

Sub Example() Dim i As Integer Dim found As Boolean Dim matchRow As Integer found = False For i = 1 To 10 If Cells(i, 1) = Range("B1") Then found = True matchRow = i End If Next i Range("C1") = found Range("C2") = matchRowEnd Sub

Figure 5-1 below shows an example of the results of running the above code. Notice how the row of the match returned in Cell C2 is the 6, the last found occurrence of ‘duck’, the value in ‘B1’.

Figure 6-5: Example Spreadsheet

If you wish to return the row of the first match found then you can use code such as the following:

Sub Example()

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 22: VBA Reference Manual

Dim i As Integer Dim found As Boolean Dim matchRow As Integer found = False For i = 1 To 10 If Cells(i, 1) = Range("B1") And found = False Then found = True matchRow = i End If Next i Range("C1") = found Range("C2") = matchRowEnd Sub

Running this code will return row 5 in Cell ‘C2’ instead of row 6.

1.1.1 Exit For

Alternatively the first match can be returned by modifying the code to use a Exit-For statement. An Exit-For statement will cause the For loop to pre-maturely terminate before it has finished all the iterations.

Sub Example() Dim i As Integer Dim found As Boolean Dim matchRow As Integer found = False For i = 1 To 10 If Cells(i, 1) = Range("B1") Then found = True matchRow = i Exit For End If Next i Range("C1") = found Range("C2") = matchRowEnd Sub

1.1.2 Nested For Loops

For loops can be nested within each other. This is typically done to iterate through a data structure with more than 1 dimension e.g. a matrix of some form. The following example method will evaluate each cell in a range in a worksheet and replace all empty cells with a value of 0.

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 23: VBA Reference Manual

Sub Example(rng As Range) Dim i As Integer Dim j As Integer

For i = 1 To rng.Rows.Count For j = 1 To rng.Columns.Count If rng.Cells(i, j) = "" Then rng.Cells(i, j) = 0 End If Next j Next iEnd Sub

1.1.3 For-Each-Next

The For-Each-Next loop structure is a variation of the For-Next structure. This is used to iterate through objects in a collection. The syntax for a For-Each-Next loop is:

For Each element In collection [statements]Next [element]

For example, the code below will change the tab colour of every sheet in the workbook.

Dim ws As WorksheetFor Each ws In Sheets ws.Tab.ColorIndex = 19Next ws

6.2 Do-WhileA do-while loop structure is typically used when you require repetition to terminate upon satisfying a certain condition. The syntax of a Do-While Loop is:

Do [While condition] [statements]Loop

For example the code below uses a Do-While loop to find the smallest number greater than 30 from column ‘A’ in a spreadsheet where the column is sorted in ascending order and it is unknown how long the column of numbers is. The result is output to cell ‘A3’

Dim i As Integeri = 1Do While Range(“A” & i) <> “” And Range(“A” & i) < 30

i = i + 1

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1

Page 24: VBA Reference Manual

LoopRange(“A3”) = Range(“A” & i)

Note that if there is no number in the column that is greater than 30 then cell ‘C3’ remains empty because when the loop terminates due to the condition Range(“A”&i)<> “” being False the empty string value, i.e. “” at Range(“A” & i), will be copied to cell ‘A3’

Alternatively a do-loop-while loop structure can be used which uses the syntax:Do [statements]Loop [While condition]

The difference between a do-loop-while and a do-while loop structure is that: The Do-While loop always performs its conditional test first and will not

execute the statements inside the loop if the test is not true. the Do-Loop-While loop always performs its conditional test after the

instructions inside the loop are executed. It run at least once

For example the code below performs the exact same function as the earlier do-while loop example.

Dim i As Integeri = 0Do i = i + 1Loop While Range(“A” & i) <> “” And Range(“A” & i) < 30Range(“A3”) = Range(“A” & i)

Page of Date: February 11File name: VBA Reference Manual.docx Revision

:A1