Vous êtes sur la page 1sur 25

Microsoft Office Excel 2003

Visual Basic for Application


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

2 MicrosoftOffice Excel 2003


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 ToolsMacroSecurity.
There are four macro security levels.

Security Level
Excel’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.

3 MicrosoftOffice Excel 2003


How to Create a Macro
Procedure Reference: To Create a Macro:
1. Select the worksheet where you want to begin recording the macro.
2. Choose ToolsMacroRecord 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 System


a. Choose the worksheet to which you want to apply the macro
b. Choose ToolsMacroMacros.
c. From the Macro List, select the macro you want to apply and then click Run.

To Apply the Macro Using a Keyboard Shortcut


a. Choose the worksheet to which you want to apply the macro
b. Press the keyboard shortcut combination you designed for the macro.
Edit a Macro
You 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

4 MicrosoftOffice Excel 2003


Procedure Reference: To Edit a Macro:
1. Choose ToolsMacroMacros.
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

5 MicrosoftOffice Excel 2003


Office Excel Objects folder. Any macros programmed in VBA or recorded also appear in the
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.

6 MicrosoftOffice Excel 2003


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.

7 MicrosoftOffice Excel 2003


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 String


Visual Basic Naming Rules
Use the following rules when you name variables in a Visual Basic module:

8 MicrosoftOffice Excel 2003


• 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 proccedures


Single 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 module
All 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.

9 MicrosoftOffice Excel 2003


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

10 MicrosoftOffice Excel 2003


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.

11 MicrosoftOffice Excel 2003


12 MicrosoftOffice Excel 2003
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.

13 MicrosoftOffice Excel 2003


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:

14 MicrosoftOffice Excel 2003


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 Description


vbGeneralDate 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 Description


vbScrollBars 0x80000000 Scroll bar color
vbDesktop 0x80000001 Desktop color
vbActiveTitleBar 0x80000002 Color of the title bar for the active window
vbInactiveTitleBar 0x80000003 Color of the title bar for the inactive window
vbMenuBar 0x80000004 Menu background color

VarType Constants

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

Constant Value Description


vbEmpty 0 Uninitialized (default)
vbNull 1 Contains no valid data
vbInteger 2 Integer
vbLong 3 Long Integer
vbSingle 4 Single-precision floating-point number
vbDouble 5 Double- precision floating-point number
vbCurrency 6 Currency
vbDate 7 Date
vbString 8 String
vbObject 9 Object

StrConv Constants

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

Constant Value Description


vbUpperCase 1 Converts the string to uppercase characters.

15 MicrosoftOffice Excel 2003


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 Description
Result Required; any numeric variable.
Expression1 Required; any expression.
Expression2 Required; any expression.

Remarks

16 MicrosoftOffice Excel 2003


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 The result is


is
True True True
True False False
True Null Null
False True False
False False False
False Null False
Null True Null
Null False False
Null 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 is


0 0 0
0 1 0
1 0 0
1 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 is


True True True
True False True
True Null True
False True True
False False False
False Null Null
Null True True
Null False Null
Null 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:

17 MicrosoftOffice Excel 2003


If bit in expression1 is And bit in expression2 is The result is
0 0 0
0 1 1
1 0 1
1 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 Description
result 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 is


True True False
True False True
False True True
False 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 is


0 0 0
0 1 1
1 0 1
1 1 0

Eqv Operator

Used to perform a logical equivalence on two expressions.

Syntax

18 MicrosoftOffice Excel 2003


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 is


True True True
True False False
False True False
False 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 is


0 0 1
0 1 0
1 0 0
1 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 is


True True True
True False False
True Null Null
False True True
False False True
False Null True
Null True True
Null False Null
Null 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

19 MicrosoftOffice Excel 2003


0 0 1
0 1 1
1 0 0
1 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 is


True False
False True
Null 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 is


0 1
1 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

20 MicrosoftOffice Excel 2003


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 Description
condition 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, Counter


Check = 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

21 MicrosoftOffice Excel 2003


Loop
Loop 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 Description
counter 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 if


Positive or 0 counter <= end
Negative 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.

22 MicrosoftOffice Excel 2003


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 J
Next 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, MyString


For 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 Description
condition 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.

23 MicrosoftOffice Excel 2003


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 Counter
Counter = 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 Statement
Executes 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 Description
condition 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

24 MicrosoftOffice Excel 2003


.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 With
End With

ÏÏÏÏÏÏÏ

25 MicrosoftOffice Excel 2003

Vous aimerez peut-être aussi