Académique Documents
Professionnel Documents
Culture Documents
• 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
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 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.
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.
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.
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
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.
The Code window is replaced by the Form Editor when you click Insert, user form, as shown
in Figure below.
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.
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:
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.
In the following statement, intX and intY are declared as type Variant; only intZ is declared as
type 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.
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:
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.
The following procedure uses three local variables declared by using dim statements:
Sub Mysub()
Dim x As Integer
End Sub
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.
Sub MySub()
End Sub
Sub YourSub()
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:
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).
Sub MySub()
End Sub
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 :
Or
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):
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:
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.
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.
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.
To declare a constant and set its value, you use the Const statement. The syntax for declaring
a constant is:
For example, the syntax for declaring a constant to store the value of tax rate is as follows:
These constants are only available when your project has an explicit reference to the
appropriate type library containing these constant definitions.
The following constants can be used anywhere in your code in place of the actual values:
VarType Constants
The following constants can be used anywhere in your code in place of the actual values:
StrConv Constants
The following constants can be used anywhere in your code in place of the actual values:
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.
Syntax
Part Description
Result Required; any numeric variable.
Expression1 Required; any expression.
Expression2 Required; any expression.
Remarks
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:
Or Operator
Syntax
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:
Xor Operator
Syntax
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:
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:
Eqv Operator
Syntax
Remarks
If either expression is Null, result is also Null. When neither expression is Null, result is
determined according to the following table:
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:
Imp Operator
Syntax
Remarks
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:
Not Operator
Syntax
Remarks
In addition, the Not operator inverts the bit values of any variable and sets the corresponding
bit in result according to the following table:
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.
Syntax
Loop
Do
[statements]
[Exit Do]
[statements]
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.
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.
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
Next [counter]
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:
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.
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.
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
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.
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
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
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
ÏÏÏÏÏÏÏ