Documente Academic
Documente Profesional
Documente Cultură
Si aceasta intoarce un obiect tip Range, dar se aplica numai unui obiect tip
Range si niciunei alte clase. Sintaxa este:
object.Offset(rowOffset, columnOffset)
Proprietatea Offset are 2 argumente care corespund pozitiei relative din
celula din stanga sus a range-ului. Argumentele pot fi pozitive (in jos sau
in dreapta), negative (in sus sau in stanga), sau zero.
Exemplul urmator introduce valoarea 12 in celula direct sub celula activa:
ActiveCell.Offset(1,0).Value = 12
For worksheet calculation, Excel uses the Double data type, so thats a
good
choice for processing numbers in VBA when you dont want to lose any
precision.
For integer calculations, you can use the Integer type if youre sure that
the values
will not exceed 32,767. Otherwise, use the Long data type. When dealing
with Excel
worksheet row numbers, youll want to use the Long data type because
the number
of rows in a worksheet exceeds the maximum value for the Integer data
type.
Declaring variables
If you dont declare the data type for a variable that you use in a VBA
routine, VBA
uses the default data type, Variant. Data stored as a Variant acts like a
chameleon: It changes type, depending on what you do with it.
Thanks to VBA, the data type conversion of undeclared variables is
automatic.
This process might seem like an easy way out, but remember that you
sacrifice
speed and memory.
Its an excellent habit to declare each variable in a procedure before you
use it.
Declaring a variable tells VBA its name and data type. Declaring variables
provides
two main benefits:
Your programs run faster and use memory more efficiently. The default
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 most
common way to declare a local variable is to place a Dim statement
between a Sub statement and an End Sub statement.
MODULEWIDE VARIABLES
Sometimes, youll want a variable to be available to all procedures in a
module. If
so, just declare the variable before the modules first procedure (outside of
any procedures
or functions).
The value of a module-wide variable 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 variable at the module level by using the Public keyword
rather
than Dim.
STATIC VARIABLES
Static variables are a special case. They are declared at the procedure
level, and
they retain their value when the procedure ends (unless the procedure is
halted with
an End statement).
You declare static variables by using the Static keyword
CONSTANTE
DECLARAREA CONSTANTELOR
Declararea constantelor se face folosind Const.
Ca si variabilele, si constantele au un scop. Daca vreti ca o constanta sa
fie disponibila intr-o singura procedura, declarati-o dupa Sub sau Function
pentru a o face o constanta locala. Pentru a face o constanta disponibila in
toate procedurile dintr-un modul, declarati-o inainte de prima procedura
din modul. Pentru a face o constanta vizibila in toate modulele dintr-un
workbook, folositi Public si declarati constanta inainte de prima procedura
dintr-un modul.
Lucrul cu variabile / constante tip string
In VBA exista 2 tipuri de siruri:
Siruri cu lungime fixa sunt declarate cu un anumit numar de
caractere. Lungimea maxima este de 65,535 caractere.
Siruri cu lungime variabila teoretic pot pastra pana la 2 billion
caractere.
Fiecare caracter dintr-un sir necesita 1 byte de stocare, si inca o mica
valoare pentru headerul fiecarui sir. Cand declarati o variabila tip string cu
Dim, puteti specifica si dimensiunea, daca o stiti (acesta va fi un sir cu
lungime fixa) sau puteti sa lasati VBA-ul sa lucreze cu ea dinamic (acesta
va fi un sir cu lungime variabila).
Dim MyString As String * 50
Dim YourString As String
Matrici
O matrice este un grup de elemente de acelasi tip, care au acelasi nume;
puteti sa va referiti la un anumit element din matrice folosind numele
matricei si un index. De exemplu, puteti defini o matrice de 12 variabile tip
string astfel incat fiecare sa ii corespunda unei luni. Daca numiti matricea
MonthNames, puteti sa va referiti la primul element din matrice ca
MonthNames(0), al doilea element ca MonthNames(1), si asa mai departe
pana la MonthNames(11).
Declararea matricilor
Matricile se declara cu Dim sau Public, la fel ca si celelalte variabile. De
asemenea, puteti specifica si numarul de elemente din matrice,
specificand primul index, apoi To apoi al 2-lea index, intre paranteze. De
exemplu:
Dim MyArray(1 To 100) As Integer
Cand declarati o matrice trebuie sa specificati numai indexul superior, caz
in care VBA presupune ca 0 este indexul inferior. Cele de mai jos au exact
acelasi efect:
Dim MyArray(0 to 100) As Integer
Dim MyArray(100) As Integer
In ambele cazuri, matricea consta in 101 elemente.
Daca vreti ca VBA sa presupuna ca 1 este indexul inferior, trebuie sa
includeti urmatorul statement inainte de orice procedura din modul:
Option Base 1
Declararea matricilor multidimensionale
Matricile din exemplele anterioare erau uni-dimensionale. Matricile in VBA
pot avea pana la 60 de dimensiuni, desi rareori e nevoie de mai mult de 3
dimensiuni (3-D array). Cum se declara o matrice de 100 elemente integer
cu 2 dimensiuni (2-D):
Dim MyArray(1 To 10, 1 To 10) As Integer
Pentru a va referi la un anumit element dintr-o matrice bi-dimensionala,
trebuie sa specificati indexul pentru rand si coloana. De exemplu, ca sa
asignati o valoare pentru un element din matricea de mai sus:
MyArray(3, 4) = 125
O matrice dinamica nu are un numar prestabilit de elemente. Declarati o
matrice dinamica cu un set de paranteze:
Dim MyArray() As Integer
Company As String * 25
Contact As String * 15
RegionCode As Integer
Sales As Long
End Type
Aceste tipuri de date se definesc la inceputul modulului, inainte de orice
procedura.
Dupa ce ati creat un tip de data user-defined, puteti folosi Dim pentru a o
declara. De obicei definiti o matrice. De exemplu:
Dim Customers(1 To 100) As CustomerInfo
Fiecare din cele 100 elemente din aceasta matrice in this array consists of
four components (as specified
by the user-defined data type, CustomerInfo). You can refer to a particular
component
of the record as follows:
Customers(1).Company = Acme Tools
Customers(1).Contact = Tim Robertson
Customers(1).RegionCode = 3
Customers(1).Sales = 150677
You can also work with an element in the array as a whole. For example, to
copy
the information from Customers(1) to Customers(2), use this instruction:
Customers(2) = Customers(1)
The preceding example is equivalent to the following instruction block:
Customers(2).Company = Customers(1).Company
Customers(2).Contact = Customers(1).Contact
Customers(2).RegionCode = Customers(1).RegionCode
Customers(2).Sales = Customers(1).Sales
To get a list of VBA functions while youre writing your code, type VBA
followed
by a period ( . ). The VBE displays a list of all its members, including
functions (see Figure 8-1).The functions are preceded by a green icon. If
this
technique doesnt work for you, make sure that the Auto List Members
option is selected.Choose ToolsOptions and then click the Editor tab.
The MsgBox Function
The official syntax of the MsgBox function has five arguments (those in
square
brackets are optional):
MsgBox(prompt[, buttons][, title][, helpfile][, context])
prompt: (Required) The message displayed in the pop-up display.
buttons: (Optional) A value that specifies which buttons and which icons,
if
any, appear in the message box. Use built-in constantsfor example,
vbYesNo.
title: (Optional) The text that appears in the message boxs title bar. The
default is Microsoft Excel.
helpfile: (Optional) The name of the help file associated with the
message
box.
context: (Optional) The context ID of the help topic. This represents a
specific
help topic to display.
Manipulating Objects and Collections
VBA offers two important constructs
that can simplify working with objects and collections:
With-End With constructs
For Each-Next constructs
With-End With constructs
The With-End With instruction construct enables you to perform multiple
operations
on a single object. To start understanding how the With-End With construct
works, examine the following procedure, which modifies five properties of
a selections
formatting (the selection is assumed to be a Range object):
Sub ChangeFont1()
Selection.Font.Name = Times New Roman
Selection.Font.FontStyle = Bold Italic
Selection.Font.Size = 12
Selection.Font.Underline = xlUnderlineStyleSingle
Selection.Font.ColorIndex = 5
End Sub
This procedure can be rewritten using the With-End With construct. The
following
procedure performs exactly like the preceding one:
Sub ChangeFont2()
With Selection.Font
.Name = Times New Roman
.FontStyle = Bold Italic
.Size = 12
.Underline = xlUnderlineStyleSingle
.ColorIndex = 5
End With
End Sub
Some people think that the second incarnation of the procedure is actually
more
difficult to read. Remember, though, that the objective is increased speed.
Although
the first version may be more straightforward and easier to understand, a
procedure
that uses the With-End With construct when changing several properties of
an
object can be significantly faster than the equivalent procedure that
explicitly references
the object in each statement.
For Each-Next constructs
GoTo statements
The most straightforward way to change the flow of a program is to use a
GoTo
statement. This statement simply transfers program execution to a new
instruction,
which must be preceded by a label (a text string followed by a colon, or a
number
with no colon). VBA procedures can contain any number of labels, and a
GoTo
statement cannot branch outside of a procedure.
The following procedure uses the VBA InputBox function to get the users
name.
If the name is not Howard, the procedure branches to the WrongName
label and
ends. Otherwise, the procedure executes some additional code. The Exit
Sub statement
causes the procedure to end.
Sub GoToDemo()
UserName = InputBox(Enter Your Name:)
If UserName <> Howard Then GoTo WrongName
MsgBox (Welcome Howard...)
-[More code here] 220 Part III: Understanding Visual Basic for Applications
Exit Sub
WrongName:
MsgBox Sorry. Only Howard can run this.
End Sub
This simple procedure works, but in general you should use the GoTo
statement
only when there is no other way to perform an action.
If-Then constructs
The basic syntax of the If-Then construct is
If condition Then true_instructions [Else false_instructions]
The If-Then construct is used to execute one or more statements
conditionally.
The Else clause is optional. If included, it lets you execute one or more
instructions
when the condition that youre testing is not True.
If condition Then
[true_instructions]
[ElseIf condition-n Then
[alternate_instructions]]
[Else
[default_instructions]]
End If
When you need to choose
among three or more alternatives, the Select Case structure is often a
better construct
to use.
[instructions]
[Exit Do]
[instructions]
Loop
or
Do
[instructions]
[Exit Do]
[instructions]
Loop [While condition]
Do While loops can also contain one or more Exit Do statements. When an
Exit Do statement is encountered, the loop ends immediately and control
passes to
the statement following the Loop statement.
DO UNTIL LOOPS
The Do Until loop structure is very similar to the Do While structure. The
difference
is evident only when the condition is tested. In a Do While loop, the loop
executes
while the condition is True. In a Do Until loop, the loop executes until the
condition is True.
Do Until also has two syntaxes:
Do [Until condition]
[instructions]
[Exit Do]
[instructions]
Loop
or
Do
[instructions]
[Exit Do]
[instructions]
Loop [Until condition]
Working with VBA
Sub Procedures
A procedure is a series of VBA statements that resides in a VBA module,
which
you access in the Visual Basic Editor (VBE). A module can hold any number
of
procedures.
You have a number of ways to call, or execute, procedures. A procedure is
executed
from beginning to end, but it can also be ended prematurely.
Some procedures are written to receive arguments. An argument is simply
information
that is used by the procedure that is passed to the procedure when it is
executed.
Procedure arguments work much like the arguments that you use in Excel
worksheet functions.
Declaring a Sub procedure
A procedure declared with the Sub keyword must adhere to the following
syntax:
[Private | Public][Static] Sub name ([arglist])
[instructions]
[Exit Sub]
[instructions]
End Sub
Private: (Optional) Indicates that the procedure is accessible only to
other procedures in the same module.
Public: (Optional) Indicates that the procedure is accessible to all other
procedures in all other modules in the workbook. If used in a module that
contains an Option Private Module statement, the procedure is not
available outside the project.
Static: (Optional) Indicates that the procedures variables are preserved
when the procedure ends.
Sub: (Required) The keyword that indicates the beginning of a procedure.
name: (Required) Any valid procedure name.
arglist: (Optional) Represents a list of variables, enclosed in parentheses,
that receive arguments passed to the procedure. Use a comma to
separate
arguments. If the procedure uses no arguments, a set of empty
parentheses
is required.
instructions: (Optional) Represents valid VBA instructions.
Exit Sub: (Optional) A statement that forces an immediate exit from the
procedure prior to its formal completion.
End Sub: (Required) Indicates the end of the procedure.
PUBLIC PROCEDURES
By default, procedures are publicthat is, they can be called by other
procedures in
any module in the workbook. Its not necessary to use the Public keyword,
but programmers
often include it for clarity. The following two procedures are both public:
Sub First()
... [code goes here] ...
End Sub
Public Sub Second()
... [code goes here] ...
End Sub
Every procedure must have a name. The rules governing procedure names
are generally
the same as for variable names. Ideally, a procedures name should
describe what its
contained processes do. A good rule is to use a name that includes a verb
and a noun
(for example, ProcessDate, PrintReport, Sort_Array, or CheckFilename).
Avoid meaningless names such as DoIt, Update, and Fix.
PRIVATE PROCEDURES
Private procedures can be called by other procedures in the same module
but not by
procedures in other modules.
You can force all procedures in a module to be privateeven those
declared with the Public keywordby including the following statement
before your first Sub statement:
Option Private Module
If you write this statement in a module, you can omit the Private keyword
from your Sub declarations
CALLING A PROCEDURE IN A DIFFERENT MODULE
If VBA cant locate a called procedure in the current module, it looks for
public procedures
in other modules in the same project.
If you need to call a private procedure from another procedure, both
procedures
must reside in the same module.
You cant have two procedures with the same name in the same module,
but you
can have identically named procedures in different modules. You can force
VBA to
execute an ambiguously named procedurethat is, another procedure in a
different
module that has the same name. To do so, precede the procedure name
with the
module name and a dot. For example, say that you define procedures
named MySub
in Module1 and Module2. If you want a procedure in Module2 to call the
MySub in
Module1, you can use either of the following statements:
Module1.MySub
Call Module1.MySub
If you do not differentiate between procedures that have the same name,
you get
an Ambiguous name detected error message.
Trapping errors
You can use the On Error statement to specify what happens when an error
occurs.
Basically, you have two choices:
Ignore the error and let VBA continue. You can later examine the Err
object to determine what the error was and then take action if necessary.
258 Part III: Understanding Visual Basic for Applications
Jump to a special error-handling section of your code to take action. This
section is placed at the end of the procedure and is also marked by a
label.
To cause your VBA code to continue when an error occurs, insert the
following
statement in your code:
On Error Resume Next
Some errors are inconsequential and can simply be ignored. But you may
want
to determine what the error was. When an error occurs, you can use the
Err object
to determine the error number. The VBA Error function can be used to
display the
text for Err.ValueNumber, which defaults to just Err. For example, the
following
statement displays the same information as the normal Visual Basic error
dialog
box (the error number and the error description):
MsgBox Error & Err & : & Error(Err)
Error-handling examples
Using the On
Error Resume Next statement simply prevents the error message from
appearing.
Sub SelectFormulas()
On Error Resume Next
Selection.SpecialCells(xlFormulas, xlNumbers).Select
On Error GoTo 0
...[more code goes here]
End Sub
Notice that the On Error GoTo 0 statement restores normal error handling
for
the remaining statements in the procedure.
The following procedure uses an additional statement to determine
whether an
error did occur:
Sub SelectFormulas2()
On Error Resume Next
Selection.SpecialCells(xlFormulas, xlNumbers).Select
If Err <> 0 Then MsgBox No formula cells were found.
On Error GoTo 0
...[more code goes here]
End Sub
I inserted the following instruction
at the beginning of SortSheets to turn off screen updating:
Application.ScreenUpdating = False
Creating Function
Procedures
Function procedures, on the other hand, usually
return a single value (or an array), just like Excel worksheet functions and
VBA
built-in functions do. Like with built-in functions, your Function procedures
can
use arguments.