Vous êtes sur la page 1sur 3

Excel VBA Guide (v1.

0)
Last Update: 09/01/2014

ALT + F8 : Opens macro menu
ALT + F11 : Opens Visual Basic Editor (VBE)

INTRODUCTION
Macros are sets of instructions for Excel to interpret and
execute automatically. Macros must start and end with
the following syntax:

Sub MacroName()
[Code goes here]
End Sub

Excel programming is object-oriented programming
(OOP). OOP is based on the idea that software deals
with distinct objects that have attributes (or properties)
and can be manipulated. A key concept of OOP is
hierarchy, the idea that objects can contain other
objects. For instance, the Range object is contained in
the Worksheet object. In Excel, collections are groups
of objects of the same type.

The syntax for referring to objects is based on the
hierarchy of objects. To refer to the value of the cell A1,
we must first call the proper worksheet and then call the
Range object. Finally, we refer to the property known
as Value to access the particular cells value.

Worksheets(Sheet1).Range(A1).Value

Objects have both properties and methods. Properties
are attributes that describe the object. Using VBA, we
can either examine the current setting of a property, or
change its setting. Value is the most common property
of objects. Methods are actions we perform with an
object. A method such as ClearContents gets rid of the
value of a cell. Methods can also have arguments, which
are values that further specify the action to perform. A
common example is the Copy method, which allows us
to copy content from one place to another. The Copy
method has an argument built in that allows us to specify
where to paste the content. The syntax is as follows:

Sub Copy()
Worksheets(Sheet1).Activate
Range(A1).Copy Range (B1)
End Sub

First, the worksheet Sheet1 is activated. After the cell
A1 is activated, the argument Range(B1) tells Excel
where to paste the content from A1. The space after the
Copy method indicates an argument for the method.

BASIC LANGUAGE SYNTAX
Comments are used to describe code. They are not read
by VBA. To insert a comment, start each line with an
apostrophe ().

Variables are storage locations in the computers
memory that are used by program. In other words, they
define the data that we use. VBA has several data types,
the most notable of which include:


Data Type Bytes Used Range of
Values
Boolean 2 True or False
Long 4 -2,147,483,648
to 2,147,483,648

Date 8 1/1/0100 to
12/31/9999
String 1 per character Varies


Variant Varies Varies
In VBA, we must declare the variables before using
them. The most common of doing this is using
Dimension (or Dim), which allows procedures to use the
variable. The syntax is as follows:

Sub DefineVariables()
Dim Revenue As Long
Dim Today As Date
Dim First as Long, Last as Long
End Sub

As seen above, one can declare several variables with a
single Dim statement.

Excel VBA also supports arrays. An array is a group of
variables that share a common name. Similarly to
variables, we must declare arrays before using them.
The following examples show how to declare an array
(and a multi-dimensional one).

Dim MyArray (1 To 100) As Integer
Dim MyArray (1 to 9, 1 to 9) As Integer

To refer to a specific element in the array, we need to
specify its row and column in the matrix. The following
example assigns the single element a value of 42.

MyArray (3, 4) = 42

RANGE SYNTAX
When referring to a Range object, the address is always
surrounded by double quotes. The smallest range is a
single cell.

Range(A1:C5) or Range(K9) or Range(NetIncome)

The object Range has an abundance of properties and
methods. Below you can find a sampling of some
commonly used ones and syntax for each one:

1.) Offset property
Refers to ranges that are nearby the selected cell. For
example, the expression:

Range(A1).Offset(1, 2)

refers to the cell one row below A1 and two columns to
the right of it. The first number in the parentheses
represents the number of rows below, and the other
represents the number of columns to the right. Offset
also accepts negative numbers.

2.) Value property
Describes the value that a cell may have.

Worksheets(Sheet1).Range(A1).Value = 23

3.) Font property
Access the Font object, which has many objects inside
of it such as Boldness, Color, and Size.

Range(A1).Font.Bold = True

4.) Interior property
Describes the background of a cell.

Range(A1).Interior.Color = RGB(255, 0, 0)

4.) Color property
VBA accepts a variety of color formats. The one that is
most used is RGB, which takes advantage of the fact
that all of the 16,777,216 colors in the MS Office
universe can be expressed using a combination of red,
green, and blue. Each color is expressed on a scale
from 0 to 255. Some sample colors can be found below:



5.) Select method

Range(A1:C12).Select

6.) Copy and paste methods

Range(A1:A12).Copy Range(C1)

7.) Clear method
Deletes the contents of a range.

Range(A1:A13).Clear

8.) Delete method
Deletes a range, but shifts the remaining cells to fill up
the range you deleted.

Rows(6:6) Delete

This deletes the row 6 and shifts all the rows up. When
you are not deleting an entire row or column, you need
to tell Excel how to fill the deleted cells. The following
statement deletes a range and then fills the resulting gap
by shifting the other cells to the left:

Range(C6:C10).Delete x1ToLeft

The constant x1Up can be used for rows of cells.

FUNCTIONS
Functions perform calculations and return single values.
The SUM function is a type of function. To use functions
in VBA, we call them through the following syntax:

WorksheetFunction.Sum

For instance, to set the variable Total to the sum of the
range A1 to A12, we write:

Total = WorksheetFunction.Sum(Range(A1:A12))

As long as your excel function has a VBA equivalent,
you can access it in writing your macro.

Some useful built-in functions:

Function Description
Abs Absolute value
Format
Expresses expression in a certain
format
Left
Returns specified number of
characters from the left of a string
Len
Returns the number of characters
in a string
Right
Returns specified number of
characters from the right of a
string
Trim
Returns a truncated part of a
string
UCase Converts a string to uppercase

Excel VBA also allows custom functions. For example:

Function Multiply(num1, num 2) As Double
Multiply = num1 * num2
End Function

DECISION FLOW SYNTAX
1.) If Then Else Structure
The If-Then structure is the most commonly used control
structure. Two examples are given as follows:

Red Green Blue Expressed as:
255 255 255 RGB(255, 255, 255)
51 51 153 RGB(51, 51, 153)
255 255 153 RGB(255, 255, 153)
0 0 0 RGB(0, 0, 0)
Sub GreetMe()
If Time < 0.5 Then MsgBox Good Morning
End Sub

SubGreetMe4()
If Time < 0.5 Then
MsgBox Good Morning
Else
MsgBox Good Afternoon
End If
End Sub

2.) Select Case Structure
The Select Case is useful for decisions involving three or
more options. An example is as follows:

Sub ShowDiscount3()
Dim Quantity As Integer
Dim Discount As Double
Quantity = InputBox(Enter Quantity: )
Select Case Quantity
Case 0 To 24
Discount = 0.10
Case 25 To 49
Discount = 0.15
Case 50 to 74
Discount = 0.20
Case Is >= 75
Discount = 0.25
End Select
MsgBox Discount: & Discount
End Sub

First the macro sets two variables, Quantity and
Discount. The Quantity variable is set from user input.
The selected value will fall into one of the four buckets,
which determines the discount rate. Finally, a message
box is produced with the corresponding discount rate.

3.) For-Next Structure
The simplest type of loop is a for-next loop. The looping
is controlled by a counter variable, which starts at one
value and stops at another view. An example, that colors
every third row in the excel sheet is found below:

Sub ColorEveryThirdRow()
Dim i as Long
For i = 1 To 100 Step 3
Rows(i).Interior.Color = RGB (200, 200, 200)
Next i
End Sub

4) Do-While Loop Structure
Unlike a For-Next loop, a Do-While loop continues until a
specified condition is met. The following example
multiplies each cells value by 2 and continues until the
routine encounters an empty cell.

Sub DoWhileDemo()
Do While ActiveCell.Value <> Empty
ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
End Sub

5) Do-Until Loop Structure
The Do-Until loop differs from the Do-While loop in that
the program executes until the condition is true (not
while he condition is true like a Do-While loops).

Sub DoUntilDemo()
Do Until IsEmpty(ActiveCell.Value)
ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
End Sub

AUTOMATIC EVENTS AND PROCEDURES
Some useful worksheet-related events:

Event

Trigger
Activate Worksheet is
activated
BeforeDoubleClick Cell in worksheet is
double clicked
BeforeRightClick Cell in worksheet is
right-clicked
Change A change is made
to cell in worksheet
Deactivate Worksheet is
deactivated
SelectionChange Selection is
changed

An example of an automatic event handling macro is as
follows:

Private Sub Workbook_Open()
Dim Msg As String
If Weekday(Now) = 6 Then
Msg = Today is Friday. TGIF!
MsgBox Msg
End If
End Sub



Q.E.D.

Source: Excel VBA Programming For Dummies by
John Walkenbach

Vous aimerez peut-être aussi