VBA

10
VISUAL BASIC FOR APPLICATIONS Visual Basic for Applications (VBA) is a powerful but easy- to-use programming language available in Microsoft Excel version 5.0 or later. For scientific and engineering purposes it is similar to BASIC and FORTRAN. VBA is actually a shortened version of the Visual Basic programming language. The language also has other features that make it useful for automating certain tasks on Excel worksheets, including such things as buttons and menus. This document introduces the reader to some of the features of Visual Basic in Excel. More detailed information can be found in Excel written documentation and help files. VBA commands are entered into two types of procedures. The first type of procedure is sometimes called macro or sub (function) procedures. Macros generally (but not always) perform actions on worksheet(s) but do not return values. Macros are generally executed through menus or buttons. A function procedure, on the other hand, returns a value (or values) to a spreadsheet or another procedure (although it may also be used to manipulate worksheets as well). Macros A macro is a set of Visual Basic commands that can be used to manipulate a worksheet automatically, for example formatting cells, typing in repeated text, etc. Excel has a shorthand way to enter macros. It includes a recording process that will automatically record actions taken on a worksheet and convert the actions into Visual Basic code. Recording a macro starts with the pulldown menu sequence Tools>Macro>Record New Macro command. Each macro is assigned a name and options through dialog boxes. The pulldown menu sequence Tools>Macro>Stop Recording ends the process of macro recording. Visual Basic for Applications (MAM 23.Nov.98) 1

description

manejo de VBA

Transcript of VBA

Page 1: VBA

VISUAL BASIC FOR APPLICATIONS

Visual Basic for Applications (VBA) is a powerful but easy-to-use programming language available in Microsoft Excel version 5.0 or later. For scientific and engineering purposes it is similar to BASIC and FORTRAN. VBA is actually a shortened version of the Visual Basic programming language. The language also has other features that make it useful for automating certain tasks on Excel worksheets, including such things as buttons and menus. This document introduces the reader to some of the features of Visual Basic in Excel. More detailed information can be found in Excel written documentation and help files.

VBA commands are entered into two types of procedures. The first type of procedure is sometimes called macro or sub (function) procedures. Macros generally (but not always) perform actions on worksheet(s) but do not return values. Macros are generally executed through menus or buttons. A function procedure, on the other hand, returns a value (or values) to a spreadsheet or another procedure (although it may also be used to manipulate worksheets as well).

Macros

A macro is a set of Visual Basic commands that can be used to manipulate a worksheet automatically, for example formatting cells, typing in repeated text, etc. Excel has a shorthand way to enter macros. It includes a recording process that will automatically record actions taken on a worksheet and convert the actions into Visual Basic code.

Recording a macro starts with the pulldown menu sequence Tools>Macro>Record New Macro command. Each macro is assigned a name and options through dialog boxes. The pulldown menu sequence Tools>Macro>Stop Recording ends the process of macro recording.

Once a macro has been created, it can be executed in a variety of ways: 1) using the Tools>Macro menu, 2) adding a reference in the Tools menu, 3) assigning a macro to a button on a sheet, 4) assigning a macro to an item on a toolbar, 5) assigning a macro to a graphic object. These modes of executing are set as a part of the macro options. Further information can be found in the Excel manual and help files.

User-Defined Functions

User-defined functions are generally used to automatically perform mathematical calculations and return them to a worksheet. User-defined functions are similar to functions built in to Excel, except they are created by the user. User-defined functions will appear on a Module sheet the same as a recorded macro. The difference is that a macro will start with the keyword Sub and end with the keywords End Sub, while a user-defined function will start with the keyword Function and end with the keywords End Function. A user-defined function is also manually typed onto a module sheet rather

Visual Basic for Applications (MAM 23.Nov.98) 1

Page 2: VBA

than input using the recording procedure. A user-defined function has the following elements:

1. Function and End Function statements marking the beginning and end of the function.

2. A name that identifies the function. The name immediately follows the Function keyword. There are some restrictions on what symbols can be used in the names, and in general function names should not conflict with functions already built in to Excel.

3. Arguments. These are the values supplied to the function from a spreadsheet or another function. There may be any number of arguments, including none. Argument names are enclosed in parentheses following the function name. Arguments are separated by commas. Arguments can either be single values or arrays.

4. Visual Basic code. These are the instructions that tell the function which calculations to perform. It is a combination of numbers, variables, control statements, and mathematical operators that yield a value.

5. The return value. This is the value the function returns after performing the calculations. The way this is specified is to enter the name of the function followed by an equal sign followed by an expression.

Example:

To create a user-defined function, first go to the VBA editor with the menu sequence Tools>Macro>Visual Basic Editor command. To start a new module sheet use the menu sequence Insert>Module. Type in the function statements on the editing sheet that comes up. Below is an example of a function that returns the cube root of a variable.

Function Cube_Root (x)Cube_Root = x ^ (1/3)

End Function

To call a user-defined function from a cell on a worksheet, simply type the equal sign followed by the name of the function and the arguments enclosed in parentheses (just as you would any other function). As with the built in functions, arguments can either be numbers, cell references, or formulas.

User-defined functions can also be accessed through the function wizard by looking under User Defined Functions. The reader is referred to the VBA manual for more detailed information.

Variables

Variables are the “place keepers” where VBA stores data. Although the function name and arguments appear as variables, they are actually storage places where data is transmitted to and from worksheets or other procedures.

Visual Basic for Applications (MAM 23.Nov.98) 2

Page 3: VBA

A variable in VBA can be thought of in the same manner as a cell on a worksheet, except that it has a named reference instead of a cell reference (named references, of course, can also be used on a worksheet). Variables have three attributes: a) type, b) scope, and c) dimensionality.

Variable type refers to kind of data that can be stored in the variable. Excel has the following variable types:

Integer 16-bit integerLong 32-bit integerSingle 32-bit floating point numberDouble 64-bit floating point numberCurrency 64-bit integerDate Date and time informationString Text informationBoolean Logical True or FalseObject 32-bit addresses that refer to objects within an applicationVariant General type that is set a runtime, i.e., when data is put into a variable

Variable scope refers to the range of procedures and/or modules over which the value of the variable is available. There are three levels of scope: a) local, b) module, and c) public.

Local variables are only available within a specific procedure. Statements declaring the variable (either Dim or Static) are made within the desired procedure. Local variables declared with Dim remain in existence only as long as the procedure is executing, while those declared with Static remain in existence the entire time VB is running.

Module-level variables are available to all procedures on a given module sheet, but not to procedures on other module sheets or in other workbooks. Statements declaring the variable (either Dim, Static, or Private) are made outside of procedures, usually at the top of the module sheet. At the module level there is no difference between Private and Dim, but Private might be a better statement to use to contrast against the Public statement used for public variables.

Public variables are available to every procedure in every module in the workbook (and can also be made available to all workbooks selected in the Available References box of the References dialog box, Tools menu, if desired). Public variables cannot be declared within a procedure. Like module-level variables, they are generally declared in a declarations section of a module (usually at the top). The Public statement is used for all public variables.

Variables can have “dimensionality” from zero to 60 different dimensions. A zero-dimension variable has only a single value. A one-dimensional variable has a single index, two-dimensional variable two indexes, etc. Multidimensional arrays are referred to in a declaration statement as variablename (n1,n2,...), where the values n1,n2, etc. refer to the number of variables in that dimension. For example Counters (5) refers to a variable

Visual Basic for Applications (MAM 23.Nov.98) 3

Page 4: VBA

called Counters that has five elements, and Sums (2,3,7) refers to a variable called Sums that is a 237 array.

The Option Base statement declares whether the first index (lower bound) starts with zero or one. For example Option Base 1 means that numbering starts at one. The Option Base statement is usually given at the top of the module sheet or within a procedure.

Another way to specify the lower bound is to provide it explicitly using the To keyword. For example, Counters (101 To 105) would have the index for counters running from 101 to 105.

Good programming practice is to require that all variables (other than those that appear in a Function statement) to be declared. This allows VBA to generate an error message if a variable name is mistyped or not explicitly declared. The statement Option Explicit at the top of the module sheet will do this. Option Explicit can also be added to every module created using the menu sequence Tools>Options>Module General>Require Variable Declaration.

Declaration statements for variables have the form:

Dim variablename As type

Dim, of course, could also be Static, Private or Public. “As type” is optional. If this is left off the declaration statement, the variable type is assumed to be variant.

Often it may be useful to have constant values in the code. Although a constant resembles a variable, it cannot be modified. Constants are declared with a Constant statement of the type:

Const Pi = 3.14159

Program Control

Program control refers to statements within the VBA code that direct the sequence of statements to be executed. The two general types of program control are branching and looping.

Branching

Branching is used to select alternative paths within a code based on some specified condition(s). There are two types of branching statements, If statements and Select Case statements.

If sequences have the following format:

If (logicalcondition1) Then

Statements

Visual Basic for Applications (MAM 23.Nov.98) 4

Page 5: VBA

ElseIf (logicalcondition2) Then

Statements

Else

Statements

End If

The If statement first tests logicalcondition1. If true, the next series of statements is executed. If not, the next series of statements are bypassed and program execution moves on to the ElseIf statement. If the logicalcondition2 is true, the next set of statements is executed. If logicalcondition2 is false, the statements after the Else keyword are skipped. End If defines the end of the If sequence.

This sequence can have any number of ElseIf statements (including none). The Else keyword can be also eliminated. If this is done, the statements inside the If sequence are only executed if logicalcondition1 is true, otherwise the whole sequence is simply skipped.

Logicalconditions are expressions that can be tested. These are generally of the form

lhexpression {< = >} rhexpression

In this statement the lhexpression is compared to the rhexpression with a “test” operator (<, =, or >). The symbols <, =, and > can be combined to form other operators as well. For example, <= means “less than or equal to” and <> means “not equal to”

The Select Case statement is used when there are a number of different specific “cases” to be selected from, as opposed to making a branch based on a logical condition. Select Case statements have the following format.

Select Case testexpression

Case expressionlist1

Statements

Case expressionlist2

Statements

Case Else

Statements

End Select

Visual Basic for Applications (MAM 23.Nov.98) 5

Page 6: VBA

The testexpression is evaluated once to determine which case is to be selected. Selection is based on which expressionlist the testexpression equals. If it equals none of the expressionlists, then the Case Else statements are executed.

Looping

Looping is used to execute a given sequence of code repetitively, perhaps while changing some counter within the loop so that the code is executed over a range of variables. In VBA there are two kinds of loops, For/Next and Do/Loop. For/Next has a form of:

For counter=start To end Step stepsize

Statements

Next counter

Another similar type sequence, called the For Each/Next sequence can be used for a collection of objects. The reader is referred to the Excel VBA manual for more information on this.

Counter is the variable that is changed during each subsequent execution of the loop sequence. Counter starts off with a value of start, ends with a value of end and is incremented in each subsequent execution by a value of stepsize. The Next statement defines the end of the executed statements. The For/Next sequence is executed a fixed number of times, and is useful for doing recurring calculations over a range of counter values.

The Do/Loop sequence, on the other hand, is more generally used for loops where a logical test defines when a loop should be terminated. Do/Loop sequences have the following format.

Do {While or Until logicalcondition}

Statements

Loop {While or Until logicalcondition}

One and only one While or Until keyword (along with it’s associated logicalcondition) should be used in a given Do/Loop. The keyword While means that the loop will be executed so long as the given logicalcondition remains true. In this situation the logicalcondition would generally start out true and then switch to false at some subsequent execution of the loop. The keyword Until, on the other hand, means the loop will be executed up to the time the logicalcondition becomes true, having generally started out as false.

Whether the While or Until keyword is placed with the Do or the Loop statement depends on whether you desire the logicalcondition to be checked before the loop is executed or after. This choice is case-specific, and is generally made on the basis of

Visual Basic for Applications (MAM 23.Nov.98) 6

Page 7: VBA

whether you want the loop to be executed at least once or not. Many programming tasks can be constructed to use any of the above.

Note that it is possible for Do/Loop sequences to get into an “infinite loop”. This refers to the situation when the desired condition is never satisfied. This, of course, should be avoided (but is often the result of a programming error). If this happens, simply press the Esc key to terminate the VBA procedure, and then proceed to debug your code.

Looping sequences can also be exited if some condition is met prior to doing all of the specified loops. The Exit For statement is used to exit directly from a For/Next loop and the Exit Do is used to exit a Do/Loop.

Loop sequences of any type may be nested, that is, one looped may be called “inside” of another loop. As many nesting levels as desired can be used. It is common coding practice to indent nested structures to make them more readable.

References

Visual Basic User’s Guide, Microsoft Corporation (1993-94).

Visual Basic Online Magazine: http://www.vbonline.com/vb-mag/

Visual Basic for Applications (MAM 23.Nov.98) 7