excel vba handout

34
Microsoft Office Excel 2003 Visual Basic for Application

Upload: jay

Post on 07-Apr-2015

165 views

Category:

Documents


9 download

DESCRIPTION

overview of visual basics..

TRANSCRIPT

Page 1: Excel VBA Handout

Microsoft Office Excel 2003Visual Basic for Application

Page 2: Excel VBA Handout

Course Content

What is Macros Recording and running macro Security Levels in Macro Editing macros using VBA Editor Understanding the project explorer Exploring properties window Modifying code in code window Variables, data types and constants Arrays Object variables Conditional Structures (If…Then, Select Case) Logical Operators Looping Constructs Built in functions Creating Subroutines

Microsoft Office Excel 20032

Page 3: Excel VBA Handout

Create a macro

Introduction:You have used Excel enough to know that there are certain tasks that you repeat over and over again. You now need a way to automate repeated tasks so that tasks can be repeated with minimal interaction by you. In this topic you will create a macro.

Macros

Definition:A macro is a set of command and programming instructions grouped together as a single command. Each macro is uniquely identified by a macro name. A macro can perform any repeatable combination of commands. Macros can be stored in documents or in templates.

Macro Security

Because macros contain programming code, they have the potential to produce harmful effects on your system. These effects can be caused inadvertently, by improper macro construction. Or, they can be caused deliberately if the macro writer uses the macro code as a delivery method for malicious programs such as computer viruses. To reduce the risk of unsafe macros, Microsoft has constructed a macro security system that which means that unsafe code in the macro cannot execute, thus protecting your system. Macros are enabled or disabled when you open the document or load the template that contains the macros.You can view or change the macro security level on the Security Level page of the Security dialog box.Choose ToolsMacroSecurity.There are four macro security levels.

Security LevelExcel’s Actions when Opening a Document Containing Macros

Very High Only macros installed in trusted locations will be allowed to run. All other signed and unsigned macros are disabled.

High Automatically enables macros from trusted publishers; automatically disables unsigned macros. For signed macros from publishers not on the trusted list, Excel provides the option to add the publisher to the list.

Medium Automatically enables macros from trusted publishers; For unsigned macros, Excel prompts the user to enable or disable the macros. For signed macros from publishers not on the trusted list, Excel provides the option to add the publisher to the list.

Low Automatically enables all macros. Use this setting only if you have a separate virus-scanning program or some other local security system in place.

How to Create a Macro

Microsoft Office Excel 20033

Page 4: Excel VBA Handout

Procedure Reference: To Create a Macro:1. Select the worksheet where you want to begin recording the macro.2. Choose ToolsMacroRecord New Macro to open the Record Macro dialog box.3. Name the macro.4. Add a shortcut key for the macro.5. Designate where the macro will be saved, then add a description of the macro.6. Clock OK to begin recording the macro.7. Perform the tasks you want to record in the macro.8. Click the stop recording button on the Stop Recording toolbar to stop recording the

macro.9. Apply the macro.

To Apply the Macro Using the Menu Systema. Choose the worksheet to which you want to apply the macrob. Choose ToolsMacroMacros.c. From the Macro List, select the macro you want to apply and then click Run.

To Apply the Macro Using a Keyboard Shortcuta. Choose the worksheet to which you want to apply the macrob. Press the keyboard shortcut combination you designed for the macro.

Edit a MacroYou have created macros in Excel. You now need to alter a macro you have already created. In this topic, you will edit a macro.

Figure: The Microsoft Visual Basic Window

How to Edit a Macro

Procedure Reference: To Edit a Macro:

Microsoft Office Excel 20034

Page 5: Excel VBA Handout

1. Choose ToolsMacroMacros.2. If necessary, in the Macro Name list, select the macro you want to edit. 3. Click Edit.4. Make the changes to the macro in the Microsoft Visual Basic Window.5. Save the changes.6. Return to Excel.

Apply the newly edited macro.

Introducing the Visual Basic Editor

The Visual Basic Editor is a powerful tool that lets you extend the power and versatility of macros beyond anything that can be done through recording alone. So that you can fully understand how to use the Visual Basic Editor, this chapter examines all facets of the Visual Basic Editor: what the various components are, what they do, and how to use them. With that purpose stated, it’s time to examine the Visual Basic for Applications language, which is used to program all macros.

If you have never worked with the Visual Basic Editor before, you might find it more convenient to work through this chapter from start to finish. If you’ve worked with the Visual Basic Editor before, jumping to specific sections will allow you to quickly find the information you are seeking.

Opening the Visual Basic Editor

As with most Microsoft Windows–based applications, there are several methods for opening the Visual Basic Editor. You can select Tools, Macro, Visual Basic Editor from the menu bar or press Alt+F11. If there is a specific macro that you want to edit or view, you can select Tools, Macro, Macros to bring up the Macro dialog box. From there, you can highlight the macro you want to work with and select the Edit button. You can also open the Macro dialog box by pressing Alt+F8.

Recognizing Parts of the Visual Basic Editor

When you open the Visual Basic Editor directly, you use the Project Explorer window to select the macro you want to work on. The Project Explorer presents all projects (groupings of code) and the macros they contain in a tree view that works the same as the tree view in Windows Explorer. The root object, or base object of the tree, is the current workbook that you are working in, along with any other workbooks and Add-Ins that might be open.

The main elements utilized by VBA projects are each stored in a separate folder within the project. Those elements include objects, modules, which contain the macro code associated with a worksheet; class modules, which are definitions of user-defined objects you’ve created for your workbook; and user forms.

In the example shown in Figure below, the current workbook is identified as VBAProject (DateTimeManipulations.xls). The three worksheets included in the workbook (Sheet1, Sheet2, Sheet3), along with the entire workbook (ThisWorkbook), are inside the Microsoft Office Excel Objects folder. Any macros programmed in VBA or recorded also appear in the

Microsoft Office Excel 20035

Page 6: Excel VBA Handout

Modules folder. Any class modules or user forms would appear in a Class Modules or a Forms folder, respectively.

.

Directly below the Project Explorer window is the Properties window, which is used to examine and change the various properties associated with the selected object. For modules and worksheets, usually the Name property is the only one available, although worksheets do have additional properties that can be changed. Working with properties is most often done when working with user forms.

The Code window is the largest window within the Visual Basic Editor and is topped with two drop-down boxes, as shown in Figure below. The drop-down box on the left, the Object box, is used to select an object to work on. When working with code only, the box will display the default General object. The second drop-down box, the Procedure box, is used to select individual macros within the current module. As macros are added and deleted from the module, they are also added and deleted from the Procedure box.

Microsoft Office Excel 20036

Page 7: Excel VBA Handout

Besides using the Procedure box to select a macro, you can also use the up and down arrow keys to scroll through the code listings until you reach the macro you want. As you scroll through each macro, the Procedure box is updated to reflect the macro the insertion point is in.

The Code window is replaced by the Form Editor when you click Insert, user form, as shown in Figure below.

Microsoft Office Excel 20037

Page 8: Excel VBA Handout

Just like every other Windows-based application, the Visual Basic Editor has a menu bar and tool bar providing access to many other features. Most of the menu options available on the File, Edit, Window, and Help menus reflect the same options available in other Windowsbased applications. The rest of the menus, however, contain valuable capabilities that you’ll use frequently while working with the Visual Basic Editor.

Creating a Module

A module is a file that holds code or pieces of code that belong either to a form, a report, or is simply considered as an independent unit of code. This independence means that a unit may also not belong to a particular form or report. Each form or report has a (separate) module.

While recording a macro, Excel automatically translates the keystrokes and commands into VBA code language. Each macro consists of a block of VBA code. Macro code is grouped together in larger VBA code blocks known as modules. Documents and templates can contain one or more modules, and modules can contain one or more macros.

VARIABLES

Like all programming languages, VBA enables you to work with variables. In VBA (unlike in some languages), you don’t need to declare variables explicitly before you use them in your code (although doing so is definitely a good practice). In the following example, the value in cell A1 on Sheet1 is assigned to a variable named Rate:rate = Worksheets(“Sheet1”).Range(“A1”).Value

You then can work with the variable Rate in other parts of your VBA code. Note that the variable Rate is not a named range, which means that you can’t use it as such in a worksheet formula.

Declaring Variables

When declaring variables, you usually use a Dim statement. A declaration statement can be placed within a procedure to create a procedure-level variable. Or it may be placed at the top of a module, in the Declarations section, to create a module-level variable.

The following example creates the variable strName and specifies the String data type.

Dim strName As String

If this statement appears within a procedure, the variable strName can be used only in that procedure. If the statement appears in the Declarations section of the module, the variable strName is available to all procedures within the module, but not to procedures in other modules in the project. To make this variable available to all procedures in the project, precede it with the Public statement, as in the following example:

Public strName As StringVisual Basic Naming RulesUse the following rules when you name variables in a Visual Basic module:

Microsoft Office Excel 20038

Page 9: Excel VBA Handout

You must use a letter as the first character. You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in

the name. Name can't exceed 255 characters in length. Generally, you shouldn't use any names that are the same as the functions, statements,

and methods in Visual Basic. You end up shadowing the same keywords in the language. To use an intrinsic language function, statement, or method that conflicts with an assigned name, you must explicitly identify it. Precede the intrinsic function, statement, or method name with the name of the associated type library.

Variables can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, or Variant. If you do not specify a data type, the Variant data type is assigned by default. You can also create a user-defined type using the Type statement. For more information on data types, see "Data Type Summary" in Visual Basic Help.

You can declare several variables in one statement. To specify a data type, you must include the data type for each variable. In the following statement, the variables intX, intY, and intZ are declared as type Integer.

Dim intX As Integer, intY As Integer, intZ As Integer

In the following statement, intX and intY are declared as type Variant; only intZ is declared as type Integer.

Dim intX, intY, intZ As Integer

You don't have to supply the variable's data type in the declaration statement. If you omit the data type, the variable will be of type Variant.

Understanding Variable Scope

A variable’s scope determines which modules and procedures, the variable can be used in a variable’s scope can be any of the following:

scope How a variable with the procceduresSingle procedure Include a Dim or Static statement within the procedure in a

module.Single module Include a Dim or Private statement before the first procedure in

a moduleAll modules Include a public statement before the first procedure in a

module.

Local Variables

A local variable is a variable declared within a procedure. Local variables can be used only in the procedure in which they are declared. When the procedure ends, the variable no longer exists, and Excel frees up its memory.

Microsoft Office Excel 20039

Page 10: Excel VBA Handout

The most common way to declare a local variable is to place a Dim statement between sub statement and an End Sub statement. Dim statements usually are placed right after the sub statement, before the procedure’s code. Dim is a shortened form of dimension.

The following procedure uses three local variables declared by using dim statements:

Sub Mysub()

Dim x As Integer

Dim first As Long

Dim InterestRate As single

End Sub

Module Level Variables

Sometimes, you will want a variable to be available to all procedures in a module. If so, just declare the variable before the module’s first procedure(outside of any procedures or functions).

In the following example, Dim statement is the first instruction in the module. Both MySub and Yoursub have access to the CurrentValue variable.

Dim CurrentValue as Integer

Sub MySub()

‘ - [ Code goes here] –

End Sub

Sub YourSub()

‘ - [ Code goes here] -

End Sub

The value of a module-level scope variables does not change when a procedure ends an exception to this occurs if the procedure is halted with an End statement. When VBA encounters an END statement, all module-wide variables lose their values.

PUBLIC VARIABLES

To make a variable available to all the procedures in all the VBA modules in a project, declare the variables at the module level by using the Public keyword rather than Dim. Here’s an example:

Public CurrentRate as Long

Microsoft Office Excel 200310

Page 11: Excel VBA Handout

The Public keyword makes the CurrentRate variable available to any procedure in the project, even those in other modules within the project. you must insert this statement before the first procedure in a module. This type of declaration must also appear in a standard VBA module, not in a code module for a sheet or a UserForm.

Working with Static Variables

Static variables are a special case. They are declared at the procedure level, and they retain value when the procedure ends (unless the procedure is halted with an end statement).

You declare static variables by using the Static keyword:

Sub MySub()

Static Counter as Integer

‘ - [ Code goes here] -

End Sub

DEFINING DATA TYPES

Data type refers to how data is stored in memory – as integers, real numbers, strings, and so on. Although VBA can take care of data typing automatically, it does so at a cost: slower execution and less efficient use of memory. As a result, letting VBA handle data typing may present problems when you’re running large or complex applications. If you need to conserve every last byte of memory, you need to be on familiar terms with data types. The following table lists the basic variable data types supported by VBA.

Microsoft Office Excel 200311

Page 12: Excel VBA Handout

Microsoft Office Excel 200312

Page 13: Excel VBA Handout

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. For example, you can define an array of 12 string variables so than each variable corresponds to threw name of a month. If you name the array MonthNames, you can refer to the first element of the array as MonthNames (0), the second element as MonthNames (1), and so on, up to MonthNames(11).

Declaring arrays

You declare an array with a Dim or Public 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. For example, here’s how to declare an array comprising exactly 100 integers :

Dim MyArray ( 1 To 100 ) As Integer

Or

Dim MyArray (100 ) as Integer.

In both cases,the array consists of 101 elements.

Declaring Multidimensional arrays

The arrays example in the preceding were one- dimensional arrays. VBA arrays can up to 60 dimensions, although it’s rare to need more than 3 dimensions(a 3-D array). The following statement declares a 100-integer array with two dimensions (2-D):

Dim MyArray(1 To 10, 1 To 10)As Integer

You can think of the preceding array as occupying a 10 x 10 matrix. To refer to a specific element in a 2-D array, you need to specify two index numbers. For example, here’s how you can assign a value to an element in the preceding array:

MyArray (3, 4) = 125.

Declaring a Dynamic Array

By declaring a dynamic array, you can size the array while the code is running. Use a Static, Dim, Private, or Public statement to declare an array, leaving the parentheses empty, as shown in the following example.

Dim MyArray() As Single

Note   You can use the ReDim statement to declare an array implicitly within a procedure. Be careful not to misspell the name of the array when you use the ReDim statement. Even if the Option Explicit statement is included in the module, a second array will be created.

Microsoft Office Excel 200313

Page 14: Excel VBA Handout

In a procedure within the array's scope, use the ReDim statement to change the number of dimensions, to define the number of elements, and to define the upper and lower bounds for each dimension. You can use the ReDim statement to change the dynamic array as often as necessary. However, each time you do this, the existing values in the array are lost. Use ReDim Preserve to expand an array while preserving existing values in the array. For example, the following statement enlarges the array varArray by 10 elements without losing the current values of the original elements.

ReDim Preserve varArray(UBound(varArray) + 10)

Note   When you use the Preserve keyword with a dynamic array, you can change only the upper bound of the last dimension, but you can't change the number of dimensions.

Working with Constants

A named item that retains a constant value throughout the execution of a program. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except is and exponentiation. Each host application can define its own set of constants. Additional constants can be defined by the user with the Const statement. You can use constants anywhere in your code in place of actual values. A constant is a variable with a static value. You can declare a constant when the value of the variable is not expected to change throughout the life of the program. For example, the value of pir(3.14) is static and cannot change.

To declare a constant and set its value, you use the Const statement. The syntax for declaring a constant is:

Const ConstName as DataType = Value

‘ConstName’ is the name of the Constant

‘Datatype is the type of the data that constant holds.

‘Value is the value you want to assign to the constant.

For example, the syntax for declaring a constant to store the value of tax rate is as follows:

Cons TaxRate as Long = .02

Using Built-In Constants

Visual Basic for Applications defines constants to simplify your programming. The following constants can be used anywhere in your code in place of the actual values:

Microsoft Office Excel 200314

Page 15: Excel VBA Handout

Date Format Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant Value DescriptionvbGeneralDate 0 Display a date and/or time. For real numbers, display a data

and time. If there is no fractional part, display only a date. If there is no integer part, display time only. Date and time display is determined by your system settings.

vbLongDate 1 Display a date using the long date format specified in your computer's regional settings.

vbShortDate 2 Display a date using the short date format specified in your computer's regional settings.

System Color Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant Value DescriptionvbScrollBars 0x80000000 Scroll bar colorvbDesktop 0x80000001 Desktop colorvbActiveTitleBar 0x80000002 Color of the title bar for the active windowvbInactiveTitleBar 0x80000003 Color of the title bar for the inactive windowvbMenuBar 0x80000004 Menu background color

VarType Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant Value DescriptionvbEmpty 0 Uninitialized (default)vbNull 1 Contains no valid datavbInteger 2 IntegervbLong 3 Long IntegervbSingle 4 Single-precision floating-point numbervbDouble 5 Double- precision floating-point numbervbCurrency 6 CurrencyvbDate 7 DatevbString 8 StringvbObject 9 Object

StrConv Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant Value DescriptionvbUpperCase 1 Converts the string to uppercase characters.

Microsoft Office Excel 200315

Page 16: Excel VBA Handout

vbLowerCase 2 Converts the string to lowercase characters.vbProperCase 3 Converts the first letter of every word in string to uppercase.vbWide 4 Converts narrow (single-byte) characters in string to wide

(double-byte) characters. Applies to Far East locales.vbNarrow 8 Converts wide (double-byte) characters in string to narrow

(single-byte) characters. Applies to Far East locales.

Working with String Expressions

Like Excel, VBA can manipulate both numbers and text (strings). There are two types of strings in VBA:

Fixed-Length strings are declared with a specified number of characters.The maximum length is 65,535 characters

Variable-Length strings theoretically can hold up to 2 billion characters.

Each character in a string requires 1 byte of storage, and a small additional amount of storage is used for the header of each string. When you declare a string variable with a Dim statement, you can specify the length if you know it (that is, a fixed-length string),or you can let VBA handle it dynamically ( a variable-length string).

In the following example, the MyString variable is declared to be a string with a maximum length of 50 characters.MyString1 is also declared as a string, but its length is unfixed.

Dim MyString As String * 50

Dim MyString1 As String

Working with Logical Expressions

And Operator

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

The And operator syntax has these parts:

Part DescriptionResult Required; any numeric variable.Expression1 Required; any expression.Expression2 Required; any expression.

Remarks

Microsoft Office Excel 200316

Page 17: Excel VBA Handout

If both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined:

If expression1 is And expression2 is

The result is

True True TrueTrue False FalseTrue Null NullFalse True FalseFalse False FalseFalse Null FalseNull True NullNull False FalseNull Null Null

The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is And bit in expression2 is The result is0 0 00 1 01 0 01 1 1

Or Operator

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

The Or operator syntax has these parts:

If expression1 is And expression2 is The result isTrue True TrueTrue False TrueTrue Null TrueFalse True TrueFalse False FalseFalse Null NullNull True TrueNull False NullNull Null Null

The Or operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

Microsoft Office Excel 200317

Page 18: Excel VBA Handout

If bit in expression1 is And bit in expression2 is The result is0 0 00 1 11 0 11 1 1

Xor Operator

Used to perform a logical exclusion on two expressions.

Syntax

[result =] expression1 Xor expression2

The Xor operator syntax has these parts:

Part Descriptionresult Required; any numeric variable.Expression1 Required; any expression.Expression2 Required; any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is And expression2 is The result isTrue True FalseTrue False TrueFalse True TrueFalse False False

The Xor operator performs as both a logical and bitwise operator. A bit-wise comparison of two expressions using exclusive-or logic to form the result, as shown in the following table:

If bit in expression1 is And bit in expression2 is The result is0 0 00 1 11 0 11 1 0

Eqv Operator

Used to perform a logical equivalence on two expressions.

Syntax

Microsoft Office Excel 200318

Page 19: Excel VBA Handout

result = expression1 Eqv expression2

Remarks

If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is And expression2 is The result isTrue True TrueTrue False FalseFalse True FalseFalse False True

The Eqv operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is And bit in expression2 is The result is0 0 10 1 01 0 01 1 1

Imp Operator

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

Remarks

The following table illustrates how result is determined:

If expression1 is And expression2 is The result isTrue True TrueTrue False FalseTrue Null NullFalse True TrueFalse False TrueFalse Null TrueNull True TrueNull False NullNull Null Null

The Imp operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is And bit in expression2 is The result is

Microsoft Office Excel 200319

Page 20: Excel VBA Handout

0 0 10 1 11 0 01 1 1

Not Operator

Used to perform logical negation on an expression.

Syntax

result = Not expression

The Not operator syntax has these parts:

Remarks

The following table illustrates how result is determined:

If expression1 is The result isTrue FalseFalse TrueNull Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table:

If bit in expression1 is The result is0 11 0

Creating Subroutines with looping and branching

Do...Loop Statements

You can use Do...Loop statements to run a block of statements (A syntactically complete unit that expresses one kind of action, declaration, or definition. A statement generally occupies a single line, although you can use a colon (:) to include more than one statement on a line. You can also use a line-continuation character (_) to continue a single logical line onto a second physical line) an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

Repeating Statements While a Condition is True

Syntax

Microsoft Office Excel 200320

Page 21: Excel VBA Handout

Do [{While | Until} condition][statements][Exit Do][statements]

Loop

Or, you can use this syntax:

Do[statements][Exit Do][statements]

Loop [{While | Until} condition]

The Do Loop statement syntax has these parts:

Part Descriptioncondition Optional. Numeric expression or string expression that is True or

False. If condition is Null, condition is treated as False.statements One or more statements that are repeated while, or until, condition

is True

There are two ways to use the While keyword (A word or symbol recognized as part of the Visual Basic programming language; for example, a statement, function name, or operator) to check a condition in a Do...Loop statement. You can check the condition before you enter the loop , or you can check it after the loop has run at least once.

You can exit a Do...Loop using the Exit Do.

Note:   To stop an endless loop, press ESC or CTRL+BREAK

Example:

This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

Dim Check, CounterCheck = True: Counter = 0 ' Initialize variables.Do ' Outer loop. Do While Counter < 20 ' Inner loop. Counter = Counter + 1 ' Increment Counter. If Counter = 10 Then ' If condition is True. Check = False ' Set value of flag to False. Exit Do ' Exit inner loop. End If

Microsoft Office Excel 200321

Page 22: Excel VBA Handout

LoopLoop Until Check = False ' Exit outer loop immediately.

For...Next Statement

You can use For...Next statements to repeat a block of statements a specific number of times. For loops use a counter variable whose value is increased or decreased with each repetition of the loop.

Syntax

For counter = start To end [Step step][statements][Exit For][statements]

Next [counter]

The For…Next statement syntax has these parts:

Part Descriptioncounter Required. Numeric variable used as a loop counter. The variable

can't be a Boolean or an array element.start Required. Initial value of counter.end Required. Final value of counter.step Optional. Amount counter is changed each time through the loop.

If not specified, step defaults to one.statements Optional. One or more statements between For and Next that are

executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value Loop executes ifPositive or 0 counter <= endNegative counter >= end

After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Note:   Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

Microsoft Office Excel 200322

Page 23: Excel VBA Handout

Any number of Exit For statements may be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating of some condition, for example If...Then, and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 ... Next K Next JNext I

Note:   If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

Example:

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

Dim Words, Chars, MyStringFor Words = 10 To 1 Step -1 ' Set up 10 repetitions. For Chars = 0 To 9 ' Set up 10 repetitions. MyString = MyString & Chars ' Append number to string. Next Chars ' Increment counter MyString = MyString & " " ' Append a space.Next Words

While...Wend Statement

  This statement used for executing a series of statements as long as a given condition is True.

Syntax

While condition[statements]

Wend

The While...Wend statement syntax has these parts:

Part Descriptioncondition Required. Numeric expression or string expression that evaluates to

True or False. If condition is Null, condition is treated as False.statements Optional. One or more statements executed while condition is True.

Microsoft Office Excel 200323

Page 24: Excel VBA Handout

Remarks

If condition is True, all statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Tip   The Do...Loop statement provides a more structured and flexible way to perform looping.

Example:

This example uses the While...Wend statement to increment a counter variable. The statements in the loop are executed as long as the condition evaluates to True.

Dim CounterCounter = 0 ' Initialize variable.While Counter < 20 ' Test value of Counter. Counter = Counter + 1 ' Increment Counter.Wend ' End While loop when Counter > 19.Debug.Print Counter ' Prints 20 in the Immediate window.

With StatementExecutes a series of statements on a single object or a user-defined type.

Syntax

With object[statements]

End With

The With statement syntax has these parts:

Part Descriptioncondition Required. Name of an object or a user-defined type.statements Optional. One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel

Microsoft Office Excel 200324

Page 25: Excel VBA Handout

.Height = 2000 .Width = 2000 .Caption = "This is MyLabel"End With

Note   Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Note   In general, it's recommended that you don't jump into or out of With blocks. If statements in a With block are executed, but either the With or End With statement is not executed, a temporary variable containing a reference to the object remains in memory until you exit the procedure.

Example

This example uses the With statement to execute a series of statements on a single object. The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject .Height = 100 ' Same as MyObject.Height = 100. .Caption = "Hello World" ' Same as MyObject.Caption = "Hello World". With .Font .Color = Red ' Same as MyObject.Font.Color = Red. .Bold = True ' Same as MyObject.Font.Bold = True. End WithEnd With

ÏÏÏÏÏÏÏ

Microsoft Office Excel 200325