Sunteți pe pagina 1din 21

Data Entry Tips

Daca selectati un range de celule inainte de a introduce datele, puteti


apasa Enter pentru a termina de scris intr-o celula si a te muta in
urmatoarea celula din range. De asemenea, folositi Shift+Enter ca sa va
mutati mai sus, Tab ca sa va mutati spre dreapta si Shift+Tab ca sa va
mutati spre stanga.
Pentru a introduce aceeasi data in mai multe celule dintr-un range,
selectati range-ul, scrieti informatia in celula activa si apoi apasati
Ctrl+Enter.
Pentru a copia continutul celului active in toate celelalte celule dintr-un
range selectat, apasati F2 si apoi Ctrl+Enter.
Pentru a completa un range cu increment al unei singure valori apasati
CTRL in timp ce trageti de celula.
Pentru a completa un range fara incrementare, trageti pur si simplu de
celula respectiva sau apasati Ctrl+D pentru a copia in jos sau Ctrl+R
pentru a copia la dreapta.
Puteti introduce taburi si linii noi intr-o celula pentru a face textul mai usor
de citit. Ca sa introduceti un tab, apasati Ctrl+Alt+Tab. Ca sa introduceti o
linie noua, apasati Alt+Enter.
Pentru a introduce o fractie, apasati 0, apoi un spatiu, apoi fractia folosind
/ (exemplu: 0 ).
Apasati Ctrl+; pentru a insera data curenta si Ctrl+Shift+; pentru a
introduce ora curenta intr-o celula.
Pentru a seta o celula sau un range sa accepte numai un anumit tip de
data, folositi Data Validation.

O formula care foloseste o referinta a unei celule din alt worksheet:


=Sheet2!A1+1

Puteti crea de asemenea si link formulas care se refera la o celula dintr-un


workbook diferit =[Budget.xls]Sheet1!A1+1
Daca workbookul de care e legat e inchis, trebuie sa ii completati si calea
intreaga, de exemplu: =C:\MSOffice\Excel\[Budget For 2003]Sheet1!
A1+A1
Folositi Links ca sa recuperati datele dintr-un fisier corupt
Daca nu puteti sa incarcati un fisier Excel corupt, puteti sa scrieti o link
formula pentru a recupera toate datele sau o parte din ele (dar nu si
formulele). Puteti face asta pentru ca fisierul sursa dintr-un link formula nu
trebuie sa fie deschis. Daca fisierul corupt se numeste Badfile.xls, de
exemplu, deschideti un workbook nou si introduceti formula urmatoare in
celula A1 a sheetului Sheet1 pentru a incerca sa recuperati datele din
fisierul corupt:
=[C:\Files\[Badfile.xls]Sheet1!A1
unde Badfile.xls este numele workbookului corupt. In noul workbook,
copiati formula in jos si in dreapta pentru a recupera informatia.
Adaugati un nou obiect tip comentariu
Range(A1).AddComment Formula developed by JW.
Metoda genereaza eroare daca celula contine deja un comentariu.

Obiecte tip Range


Un obiect tip Range este continut intr-un obiect Worksheet si consta intruna sau mai multe celule dintr-un singur worksheet.
Exista 3 moduri de a te referi la obiecte tip Range in VBA:
Proprietatea Range a unui Worksheet sau Range class object
Proprietatea Cells a unui worksheet
Proprietatea Offset a unui obiect tip Range
Proprietatea Range
Aceasta intoarce un obiect tip Range. Aceasta proprietate are doua
sintaxe:
object.Range(cell1)
object.Range(cell1, cell2)
De asemenea, proprietatea Range recunoaste si numele definite in
workbooks.
Proprietatea Cells
Aceasta are 3 sintaxe:
object.Cells(rowIndex, columnIndex)
object.Cells(rowIndex)
object.Cells
Proprietatea Offset

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

data type, Variant, causes VBA to repeatedly perform time-consuming


checks and reserve more memory than necessary. If VBA knows the data
type, it doesnt have to investigate, and it can reserve just enough
memory
to store the data.
You avoid problems involving misspelled variable names. This assumes
that you use Option Explict to force yourself to declare all variables
(see the next section). Say that you use an undeclared variable named
CurrentRate. At some point in your routine, however, you insert the
statement CurentRate = .075. This misspelled variable name, which is
very difficult to spot, will likely cause your routine to give incorrect
results.
FORCING YOURSELF TO DECLARE ALL VARIABLES
To force yourself to declare all the variables that you use, include the
following as
the first instruction in your VBA module:
Option Explicit
This statement causes your program to stop whenever VBA encounters a
variable
name that has not been declared. VBA issues an error message, and you
must
declare the variable before you can proceed.
Scoping variables

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

- sir cu lungime fixa de 50 caractere


- sir cu lungime variabila

Lucrul cu variabile / constante tip data


Exemple de declarare a variabilelor si constantelor ca tip Date:
Dim Today As Date
Dim StartTime As Date
Const FirstDay As Date = #1/1/2001#
Const Noon = #12:00:00#
Constantele tip Date sunt definite intotdeauna folosind formatul
month/day/year, chiar daca sistemul e setat sa afiseze datele in alt format,
de exemplu zi/luna/an. Daca folositi un MsgBox pentru a afisa o data va fi
afisata conform cu setarile sistemului.

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

Inainte sa puteti folosi o matrice dinamica in codul vostru, trebuie sa o


redimensionati folosind ReDim, pentru a-I spune cate elemente se afla in
matrice. Puteti folosi ReDim ori de cate ori doriti.
VARIABILE OBIECT
O variabila tip obiect este o variabila care reprezinta un intreg obiect, cum
ar fi un range sau un worksheet.
Variabilele tip obiect sunt declarate ca si celelalte variabile, cu Dim sau
Public. De exemplu, declaram InputArea ca obiect de tip Range:
Public InputArea As Range
Ca sa vedeti cum se simplifica codul folosind variabile tip obiect, vedeti
procedura urmatoare, care a fost scrisa fara a folosi variabile tip obiect:
Sub NoObjVar()
Worksheets(Sheet1).Range(A1).Value = 124
Worksheets(Sheet1).Range(A1).Font.Bold = True
Worksheets(Sheet1).Range(A1).Font.Italic = True
End Sub
Aceasta rutina introduce o valoare in celula A1 a Sheet1 din workbookul
activ si apoi bolduieste si face italic continutul celulei.
Puteti condensa rutina de mai sus cu o variabila tip obiect:
Sub ObjVar()
Dim MyCell As Range
Set MyCell = Worksheets(Sheet1).Range(A1)
MyCell.Value = 124
MyCell.Font.Bold = True
MyCell.Font.Italic = True
End Sub
Dupa ce variabila MyCell este declarata ca obiect tip Range, cu Set I se
asigneaza un obiect. Ulterior se poate folosi direct MyCell in loc de
Worksheets(Sheet1).Range(A1).
Dupa ce un obiect este asignat unei variabile, VBA o poate accesa mai
rapid. Deci, atunci cand viteza este critica, folositi obiecte.
Un alt mod de a imbunatati viteza codului este folosirea With-End With
Tipuri de date User-Defined
VBA permite sa creati tipuri de date user-defined. De exemplu, daca
aplicatia lucreaza cu informatii despre clienti, ati putea dori sa creati un tip
de data user-defined numit CustomerInfo, astfel:
Type CustomerInfo

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

Recall from the preceding chapter that a collection is a group of related


objects. For
example, the Workbooks collection is a collection of all open Workbook
objects.
There are many other collections that you can work with. You dont have to
know
how many elements are in a collection to use the For Each-Next construct.
Suppose that you want to perform some action on all objects in a
collection. Or
suppose that you want to evaluate all objects in a collection and take
action under
certain conditions. These are perfect occasions for the For Each-Next
construct.
The syntax of the For Each-Next construct is
For Each element In group
[instructions]
[Exit For]
[instructions]
Next [element]
The following procedure uses the For Each-Next construct to refer to each
of
the six members of a fixed-length array one at a time:
Sub Macro1()
Dim MyArray(5) As Double
For i = 0 To 5
MyArray(i) = Rnd
Next i
For Each n In MyArray
Debug.Print n
Next n
End Sub
The next procedure uses the For Each-Next construct with the Sheets
collection
in the active workbook. When you execute the procedure, the MsgBox
function
displays each worksheets Name property. (If there are five worksheets in
the active
workbook, the MsgBox function is called five times.)
Sub CountSheets()
Dim Item as WorkSheet
For Each Item In ActiveWorkbook.WorkSheets
MsgBox Item.Name
Next Item
End Sub
218 Part III: Understanding Visual Basic for Applications
In the preceding example, Item is an object variable (more specifically, a
Worksheet object). Theres nothing special about the name Item; you can
use any valid variable name in its place.
The next example uses For Each-Next to cycle through all objects in the
Windows collection:
Sub HiddenWindows()
Dim AllVisible As Boolean
Dim Item As Window
AllVisible = True

For Each Item In Windows


If Item.Visible = False Then
AllVisible = False
Exit For
End If
Next Item
MsgBox AllVisible
End Sub
If a window is hidden, the value of AllVisible is changed to False, and the
For
Each-Next loop is exited. The message box displays True if all windows are
visible
and False if at least one window is hidden. The Exit For statement is
optional. It
provides a way to exit the For Each-Next loop early. This is generally used
in conjunction
with an If-Then statement (which I describe later in this chapter).
Heres an example that closes all workbooks except the active workbook.
This
procedure uses the If-Then construct to evaluate each workbook in the
Workbooks
collection.
Sub CloseInActive()
Dim Book as Workbook
For Each Book In Workbooks
If Book.Name <> ActiveWorkbook.Name Then Book.Close
Next Book
End Sub
My final example of For Each-Next is designed to be executed after the
user
selects a range of cells. Here, the Selection object acts as a collection that
consists
of Range objects because each cell in the selection is a Range object. The
procedure
evaluates each cell and uses the VBA UCase function to convert its
contents to
uppercase. (Numeric cells are not affected.)
Chapter 8: VBA Programming Fundamentals 219
Sub MakeUpperCase()
Dim Cell as Range
For Each Cell In Selection
Cell.Value = UCase(Cell.Value)
Next Cell
End Sub
Controlling Execution
This section discusses the additional ways of controlling the execution of
your VBA procedures:
GoTo statements
If-Then constructs
Select Case constructs
For-Next loops
Do While loops
Do Until loops

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.

Select Case constructs


The Select Case construct is useful for choosing among three or more
options.
This construct also works with two options and is a good alternative to IfThenElse. The syntax for Select Case is as follows:
Select Case testexpression
[Case expressionlist-n
[instructions-n]]
[Case Else
[default_instructions]]
End Select
VBA offers an alternative to the If-Then construct: the IIf function. This
function
takes three arguments and works much like Excels IF worksheet function.
The syntax is
IIf(expr, truepart, falsepart)
expr: (Required) Expression you want to evaluate.
truepart: (Required) Value or expression returned if expr is True.
falsepart: (Required) Value or expression returned if expr is False.
If you use only one instruction per
case, as in the preceding example, you might want to put the instruction
on the
same line as the Case keyword (but dont forget the VBA statementseparator character,
the colon). This technique makes the code more compact. For example:
Sub Discount3()
Dim Quantity As Variant
Dim Discount As Double
Quantity = InputBox(Enter Quantity: )
Select Case Quantity
Case : Exit Sub
Case 0 To 24: Discount = 0.1
Case 25 To 49: Discount = 0.15
Case 50 To 74: Discount = 0.2
Case Is >= 75: Discount = 0.25
End Select
MsgBox Discount: & Discount
End Sub
Looping blocks of instructions
FOR-NEXT LOOPS
The simplest type of a good loop is a For-Next loop. Its syntax is
For counter = start To end [Step stepval]
[instructions]
[Exit For]
[instructions]
Next [counter]

Following is an example of a For-Next loop that doesnt use the optional


Step
value or the optional Exit For statement. This routine executes the Sum =
Sum +
Sqr(Count) statement 100 times and displays the resultthat is, the sum
of the
square roots of the first 100 integers.
Sub SumSquareRoots()
Dim Sum As Double
Dim Count As Integer
Sum = 0
For Count = 1 To 100
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub
In this example, Count (the loop counter variable) started out as 1 and
increased
by 1 each time the loop repeated. The Sum variable simply accumulates
the square
roots of each value of Count.
For-Next loops can also include one or more Exit For statements within the
loop. When this statement is encountered, the loop terminates
immediately and
control passes to the statement following the Next statement of the
current ForNext loop. The following example demonstrates use of the Exit For
statement.
This procedure determines which cell has the largest value in column A of
the
active worksheet:
Sub ExitForDemo()
Dim MaxVal As Double
Dim Row As Long
Dim TheCell As Range
MaxVal = Application.WorksheetFunction.Max(Range(A:A))
For Row = 1 To 65536
Set TheCell = Range(A1).Offset(Row - 1, 0)
If TheCell.Value = MaxVal Then
MsgBox Max value is in Row & Row
TheCell.Activate
Exit For
End If
Next Row
End Sub
DO WHILE LOOPS
A Do While loop is another type of looping structure available in VBA.
Unlike a
For-Next loop, a Do While loop executes while a specified condition is met.
A Do
While loop can have either of two syntaxes:
Do [While condition]

[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.

S-ar putea să vă placă și