Você está na página 1de 30

#1

Excel Macro(VBA)

Introduction to Excel VBA


VBA is the acronym for Visual Basic for
Applications. It is an integration of the
Microsoft's
event-driven
programming
language Visual Basic with Microsoft Office
applications such as Microsoft Excel, Microsoft
Word, Microsoft PowerPoint and more. By
running
Visual
Basic
IDE(Integrated
Development Environment) within the Microsoft
Office applications, we can build customized
solutions and programs to enhance the
capabilities of those applications.

Visual Basic Editor


There are two ways which you can start
VBA programming in MS Excel. The first is
to place a command button on the
spreadsheet and start programming by
clicking the command button to launch the
Visual Basic Editor. The second way is to
launch the Visual Basic Editor by clicking
on the Tools menu then select Macro from
the dropdown menu and choose Visual
Basic Editor.

Common Term Used in VBA

Modules:
Procedures:
Keywords
Data Type
Variables

Modules
Module is the location in Excel VBA
where the VBA code is typed and
stored and collections of module is
called as VBA project.
- VBA module window.
- To insert a new module

Procedures
Procedures are a named set of statements that
are executed as a whole. They tell Excel how to
perform a specific task. The task performed can
be very simple or very complicated. It is good
practice to break long or complicated procedures
into smaller sized logically ordered procedures.
The
two
main
types
of
Procedures
areSubandFunction.
A Sub procedure is what results from recording a
macro, while Function procedure must be written
manually.

Keywords
Keywords in Excel VBA are words that
Excel has set aside to use in the
execution of code. This means we
cannot use them for any other purpose.
For example, Select, Active, Sub, End,
Function etc are all Keywords that we
can only use for their indented purpose.
For any kind of help about any keyword,
just select the keyword and press f1.

Data Type
In excel VBA, the data type is used to specify
the type of value that a particular variable
store at program runtime.
There are two types of data types in Excel VBA
- Numeric Data Type
For handling numbers in VBA a Numeric
Data Type is required.
- Non Numeric Data Type
For handling Text, Date, Time,

Numeric Data Type


Require
VBA
Data Type or
d
Default
Consta
Subtype
Memor Value
nt
y
vbByte
Byte
1 byte
0
vbInteger
Integer
2 bytes
0
Long Integer 4 bytes

vbLong

Single

4 bytes

vbSingle

Double

8 bytes

vbDouble

Range
0 to 255
32,768 to 32,767
2,147,483,648 to
2,147,486,647
3402823E38 to
1.401298E45 or
1.401298E45 to
3.402823E38

1.79769313486232E308
to
4.94065645841247E
324 or
1.79769313486232E308

Non Numeric Data Type

Requir
VBA
Data Type or
ed
Default
Consta
Subtype
Memor Value
nt
y
Date

8 bytes

Number
of
spaces
String's
Fixed String
to
length
accomm
odate
string
10 bytes
plus the Zeronumber length
Variable String
of
string
characte ("")
rs
Nothing
Object
4 bytes (vbNothin

Range

vbDate

January 1, 100 to
December 31, 9999

vbString

1 to 65,400 characters

vbString

0 to 2 billion characters

vbObject

Any Access object, ActiveX

Variables in Excel VBA


Variables are like mail boxes in the post
office. The contents of the variables
change every now and then, just like the
mail boxes. In Excel VBA, variables are
areas allocated by the computer memory
to hold data. Like the mail boxes, each
variable must be given a name. To name
a variable in Excel VBA, you have to
follow a set of rules, as follows

Variable Names
The following are the rules when
naming the variables in VBA
It must be less than 255 characters
No spacing is allowed
It must not begin with a number
Period is not permitted
Keywords not allowed

Examples of valid and invalid


variable names
Valid Name

Invalid Name

My_Car

My.Car

NewBoy1

1NewBoy

My_Name

My&Name

Declaring Variables
In VBA, we need to declare the variables before
using them by assigning names and data types.
There are many VBA data types, which can be
grossly divided into two types, namely the
numeric data types and the non-numeric data
types.
Like
Dim variableName As Data Type (return type)

Note:

You can declare the variables implicitly or


explicitly. For example, sum=text1.text
means that the variable sum is declared
implicitly and ready to receive the input in
textbox1. Other examples of implicit
declaration
are
volume=8
and
label=Welcome. On the other hand, for
explicit declaration, variables are normally
declared in the general section of the code
window using the Dim statements.

Important Definitions
OBJECTS
METHOD
S

PROPERT
IES

Objects
The wordObjectin the context that we use it is
used to describe just about everything in Excel.
You will find as you get deeper and deeper into
VBA that there are manyObjects. Don't
confuse the word with its usual use of referring
to something tangible. In Excel, anObjectcan
be a range, a worksheet, a chart or even the
Visual Basic Editor (VBE) itself.
he very least that you need to know
aboutObjectsis that there is what is known as
theObject Hierarchy.

you need to know at this stage is the following


order
Application
Workbook
Worksheet
Range
When you have a group of Objects that are
related, this is then known as a "Collection".
So when we use the termWorkbooks, we are
referring toallopen Workbooks, and when we
use the term Workbook, we are only referring
to an individual Workbook (the active
Workbook).

Method
Like Properties,Objectsalso haveMethods.A
Method is simply a procedure that acts on a
Object.
like Properties, Objectsalso have Methods. A
Method is simply a procedure that acts on a
Object. By this I mean it causes the Object do
do something, this might be opening a
Workbook (which is an Object) or deleting a
Worksheet (another Object) or any one of
thousands of other things.

Properties
Propertiesare
an
attribute
of
anObject. They are used to define an
Objects characteristics, so to use an
example; theWorksheetObject has
many Properties, one of which would
be itsname. So by changing it's
name, you are directly changing one of
its Properties. Also by making the
Worksheet hidden, you are again
changing one of its Properties, in this

OPERATOR
VBA includes several built-in operators, which
can be used for building expressions and quickly
performing basic tasks in your VBA code.
In other word, Operators are the symbol which
specify the action on any given value.
There are mainly four types of operators in VBA
- Mathematical Operator
- String Operator
- Comparison Operator
- Logical Operator

Mathematical Operator
The main Mathematical VBA operators
are listed in the table below.
The precedence that are listed
alongside the operators are the
defaults, which are applied in the
absence of brackets. However, the
order in which the VBA operators are
applied can be controlled by adding
brackets to an expression

Operator

Action

^
*

The power operator


The multiplication
operator
The division operator
The integer division
operator (divides two
numbers and returns the
integer result - e.g. 7\4
gives a result of 1)
The modulus operator
(divides two numbers
and returns the
remainder - e.g. 8 Mod 3
gives a result of 2)
The addition operator
The subtraction operator

/
\

Mod

+
-

Precedence
(1=top;
5=bottom)
1
2
2
3

5
5

String Operator
The concatenate operator & can be
used to join together strings
Operator
&

Action
The concatenate operator (e.g.
"A" & "B" gives the result "AB")

Comparison Operator
Comparison operators compare two
numbers or strings and return a logical
(True or False) result. The main Excel
VBA comparison operators are listed in
the table below

Operator

Action

Equal To

<>

Not Equal To

<

Less Than

>

Greater Than

<=

Less Than or Equal To

>=

Greater Than or Equal To

Logical Operator
Logical operators also return a logical
(True or False) result. The main Excel
VBA logical operators are listed in the
table below
Operator
Action
And

Logical Operator And (e.g. the expression 'A And B' returns
True if BOTH A AND B are true and returns False otherwise)

Or

Logical Operator Or (e.g. the expression 'A Or B' returns


True if EITHER A OR B is true and returns False otherwise)

Not

Negates an evaluation (e.g. the expression 'Not A' returns


True if A is false and returns False if A is true)

Example
Private Sub CommandButton1_Click ()
Dim number1, number2, number3 as Single
Dim total, average as Double
number1=Cells (1, 1).Value
number1=Cells (2, 1).Value
number3= Cells (3, 1).Value
Total=number1+number2+number3
Average=Total/3
Cells (5, 1) =Total
Cells (6, 1) =Average
End Sub

Example
Private Sub CommandButton1_Click()
Dim secondName As String, yourName As
String
firstName = Cells(1,1).Value
secondName = Cells(2,1).Value
yourName = firstName + " " + secondName
Cells(3,1) = yourName
End Sub

Você também pode gostar