addendum. vba language · 2017-02-27 · option is not disabled, when creating a module, vba is...

54
1 Addendum. VBA Language By Alessandro Rezzani This addendum introduces several advanced topics concerning VBA programming. 1.1 VARIABLE, CONSTANT AND DATA TYPES VBA’s main objective is data manipulation. Data can be found in spreadsheets, within Ranges, as shown in the previous chapter, or stored within VBA variables and constants. Variables and constants can be characterized according to the type of data they store. 1.1.1 Data Types When defining a variable or a constant two options are possible: either to allow VBA to manage the data type they will contain, or declare in advance the variable or constant by assigning them a predefined data type. The first case, easier for the programmer, involves a decrease in the performance of execution of the program and a less efficient use of memory. On the other hand, the declaration of variables (or constants) avoids performance problems, but forces the programmer to choose carefully the correct data type. With data type it is meant the way in which data are represented in memory: number, string (or set of characters), date, etc. VBA makes available several data types, each of which capable of representing a set of data, defined by nature (number, string, etc.) and size (numbers that occupy up to 4 bytes, up to 8 bytes, etc.). The reason for this distinction is in the mode of representation in memory: when saving a string, VBA will use the memory in a certain way, different from the way a whole number is saved. For instance, a string is constituted by single characters, each of which requires a byte of memory, while in a byte of memory it would be possible to save a number from 0 to 255. The use of different data types allows the programmer not to waste memory for the representation of small size data: to save the number 1000, the type Integer is required, which only occupies 2 bytes, while it would not make sense to use the Double type which uses 8 bytes and is specific to decimal, high precision numbers (or huge numbers, up to 1.79769313486232E308 1 ). Therefore, as a rule, the data type to be selected should always be the less memory consuming to contain the value that has to be saved in a variable. The following table shows the list of data types available in VBA and, for each of them, indicates the size in bytes and the range of values that can be represented. 1 Scientific notation expresses numbers with the format mEn meaning that m*10 n . Therefore, 1.79769313486232E308 is equal to 1.79769313486232*10 308 .

Upload: others

Post on 19-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

1

Addendum. VBA Language

By Alessandro Rezzani This addendum introduces several advanced topics concerning VBA programming. 1.1 VARIABLE, CONSTANT AND DATA TYPES

VBA’s main objective is data manipulation. Data can be found in spreadsheets, within Ranges, as shown in the previous chapter, or stored within VBA variables and constants. Variables and constants can be characterized according to the type of data they store. 1.1.1 Data Types

When defining a variable or a constant two options are possible: either to allow VBA to manage the data type they will contain, or declare in advance the variable or constant by assigning them a predefined data type. The first case, easier for the programmer, involves a decrease in the performance of execution of the program and a less efficient use of memory. On the other hand, the declaration of variables (or constants) avoids performance problems, but forces the programmer to choose carefully the correct data type. With data type it is meant the way in which data are represented in memory: number, string (or set of characters), date, etc. VBA makes available several data types, each of which capable of representing a set of data, defined by nature (number, string, etc.) and size (numbers that occupy up to 4 bytes, up to 8 bytes, etc.). The reason for this distinction is in the mode of representation in memory: when saving a string, VBA will use the memory in a certain way, different from the way a whole number is saved. For instance, a string is constituted by single characters, each of which requires a byte of memory, while in a byte of memory it would be possible to save a number from 0 to 255. The use of different data types allows the programmer not to waste memory for the representation of small size data: to save the number 1000, the type Integer is required, which only occupies 2 bytes, while it would not make sense to use the Double type which uses 8 bytes and is specific to decimal, high precision numbers (or huge numbers, up to 1.79769313486232E3081). Therefore, as a rule, the data type to be selected should always be the less memory consuming to contain the value that has to be saved in a variable. The following table shows the list of data types available in VBA and, for each of them, indicates the size in bytes and the range of values that can be represented.

                                                            1 Scientific notation expresses numbers with the format mEn meaning that m*10n. Therefore, 1.79769313486232E308 is equal to 1.79769313486232*10308.

Page 2: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

2

Type  Bytes  Range of Values 

Byte 1 byte From 1 to 255

Boolean 2 bytes True or False

Integer 2 bytes From -32,768 to 32,767

Long 4 bytes from -2,147,483,648 to 2,147,483,647

Single 4 bytes From -3.402823E38 to -1.401298E-45 (for negative values); from 1.401298E-45 to 3.402823E38 (for positive values)

Double 8 bytes From -1.79769313486232E308 to -4.94065645841247E-324 (for neg. val.); from 4.94065645841247E-324 to 1.79769313486232E308 (for pos. val.)

Currency 8 bytes From -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 without decimals +/- 7.9228162514264337593543950335 with 28 decimal figures

Date 8 bytes From 1/ 1/0100 to 31/12/9999 String (variable length, without size specification)

10 bytes the length of the string

From 0 to almost 2,000,000,000 characters

String (fixed length) String length from 1 to approximately 65,400 characters Variant (containing numbers)

16 bytes Any number (up to the Double capacity)

Variant (containing characters)

22 bytes + string length From 0 to almost 2,000,000,000 characters

Object 4 bytes Any reference to an Object User Defined data types Variable Variable

Table 1.1 ‐ Data types in VBA 

From the table, it appears clear that numbers can be represented in different data types, depending on whether they are integers (Byte, Integer, Long) or numbers with decimal figures (Single, Double, Decimal, Currency). Each data type can manage different dimensions.

Figure 1.1 ‐ Numerical data types 

Strings only have one data type, String, with either fixed or variable length. It should be noted that strings should always be included in quotation marks.

Figure 1.2 ‐ String data type 

Page 3: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

3

Dates are managed in a specific data type: Date. It is important to highlight that, in VBA, all Date data types are expressed in the format month/day/year (in numbers), independently of the format of the system’s cells. Moreover, the date must be enclosed in hash signs (#). For example, January 1, 2016 is valued as #1/31/2016#. Another way for inserting dates consists in the use of the DateSerial function, which accepts three numbers as parameters, corresponding to year, month, and day.

Figure 1.3 ‐ Dates data type 

There exist also two special data types: Object and Variant. The first is used to contain a reference to any object in the VBA object model. In the Figure, only the basic data types are shown, but it should be noted that any object can be considered a complex data type and employed to declare variables. The Variant data type acts as a ‘wildcard’ as it may contain any value of any data type. One may wonder then if it is not worth always using the Variant type. It should be noted that, unfortunately, the flexibility of the Variant comes at the expense of performance, so it is not recommendable to use it extensively. When writing code that includes Variant variables, it is useful to know the exact data type it contains. The function TypeName performs this task.

Figure 1.4 ‐ Variant data type 

The Decimal data type differs from the others for the particular feature that it cannot be declared: it is not possible to create explicitly a variable with this data type, but a Variant variable may contain it. The Decimal type is obtained by using the conversion function CDec.

Figure 1.5 ‐ Decimal data type 

Page 4: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

4

Now user-defined data types will be briefly mentioned. User-defined data types are created starting from basic data types (Integer, String, etc.), and are useful when complex data have to be managed. For example, if managing information related to customers, it could be possible to create a ‘Customer’ data type consisting of Name, Surname, City and Last purchase date.

Figure 1.6 ‐ User‐Defined Data Type 

1.1.2 Variables

As already stated, variables act as a container for the data that have to be processed in VBA (in addition to the data contained in Excel spreadsheets), and provide a name to the memory area where the data is contained. In VBA, there exist two options for the creation of variables. The first is simply to assign a value to a name, without declaring in advance that that name represents a variable with a certain data type. This option is only possible if the Require Variable Declaration option is disabled. In case the mentioned option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces variable declaration before using it. It should be noted that such command can be written by the programmer manually, even without enabling the editor option.

Figure 1.7 ‐ Option Explicit for the mandatory declaration of variables 

Mandatory variable declaration is a recommended practice, since it allows assigning a data type as well, avoiding using Variants, which are less effective than specialized types.

Page 5: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

5

Variable declaration occurs through the Dim instruction, followed by the name that the programmer wants it to be assigned, by keyword As, and the data type. A variable may have several visibility levels (also called scope), according to where it is declared and the specifier used (either Public or Private). The possible cases are as follows: Variable declared in a Sub or Function: it will be visible, and thus usable, only within that

procedure. Variable declared out of the Subs or Functions, within a module.

In this latter case, two further possibilities must be analyzed: If the variable is declared with the Dim instruction, or with the Private specifier, it will only be

visible within the module to which it belongs. If the variable is declared with the Public specifier, then it will be visible in all modules and

procedures. An important special characteristic concerns the Object type variables. They contain object references, and not the objects themselves. This is a very similar concept to the one of the pointer, widespread in other programming languages such as C. The reference allows modifications to the object, without making a copy of it. Since the concept of assigning a reference is different from assigning a value, it is necessary to use a different technique, which consists in adding the keyword Set before assigning. Such technique is also effective when complex data types are used (for example Range).

Figure 1.8 Use of the Set keyword 

It is important to notice that when trying to insert a non-compliant value into a variable, VBA will return an error. In particular, the programmer will get an Overflow error type when trying to assign to a variable a greater value than the capacity of the datatype in the declaration statement: for example, this error occurs when entering the value 1,000,000 in an integer variable. Another anomalous situation occurs when a data is assigned to a type but it is not compatible with respect to the one of the variable. For example, if the programmer declares a type Integer variable and then he/she tries to assign it the string ‘abcd’, he/she will get the error Type mismatch. 1.1.3 Constants

The value of a variable may change, if operations of declaration of new data occur. If a value is set to never change while the program is running, it is more correct to use a constant instead of a variable. Constants are declared by using the word Const followed by the name, the keyword As, the data type, and the immediate value assignment. It is possible to use the Public specifier to declare constants and make them visible in all modules. It is good practice to use constants, perhaps created with the Public specifier in a module specifically dedicated to them, instead of directly writing values in the code (called hard-coded values). The advantage, for the programmer, is in the rapidity and simplicity of managing possible variations: using a constant, the value is only written once, during the preliminary value assignment phase, and only the name of the constant is repeated in the code. Therefore, it will be

Page 6: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

6

sufficient to change the assignment of the value to the constant to make a change that otherwise would require several changes.

Figure 1.9 ‐ Declaration of a Constant  

1.1.4 Array

An Array is constituted by a set of elements of the same type, such as a set of integer numbers, or a set of strings. The assignment operation gives a name to the array, just like already seen for the variables. However, in declaring the array, its size must be specified, which can be fixed or dynamic. In the first case, the syntax is as that represented in the following figure, in which it is possible to see that the data type is simply followed by round brackets that enclose the size specified by the user.

Figure 1.10 ‐ Declaration and use of a fixed‐size array 

In the second case, the statement is made without specifying the size of the array, leaving the parentheses without content, instead. However, before using the array, it needs to be prepared by using the statement ReDim, which specifies its size. What is therefore the advantage of dynamic arrays, if it is still necessary to indicate their size? Dynamic arrays allow to vary as many times as necessary the dimension of the array in the VBA program. This scaling can be done either by deleting existing values (only the ReDim instruction will be sufficient), or keeping them: in the latter case ReDim instruction will be followed by the keyword Preserve.

Figure 1.11 ‐ Declaration and use of a dynamic‐size array  

The maximum size of an array is (2^31)-1 elements (i.e. 2,147,483,647). It is actually limited by the amount of available RAM: if exceeded, an Out of Memory type of error occurs.

Page 7: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

7

Figures also show the use of arrays: in order to assign (or read) a value in any position, it is necessary to specify in round brackets that position’s index. It is also possible to declare a multidimensional array (up to a maximum of 32 dimensions), thus creating an n-dimensional matrix. The figure below shows how to declare and use a multidimensional array.

Figure 1.12 ‐ Declaration and use of a multidimensional array (2 dimensions) 

Finally, it is worth mentioning the functions UBound and LBound, which accept an array as input and the number of the dimensions to be checked (in the case of arrays with more than one dimension), returning the maximum and minimum index respectively. For example, with regard to the array in Figure 1.12, the instruction UBound(a,1) returns 100. 1.2 CONDITIONAL EXPRESSIONS

When writing a VBA Sub or Function, it may be necessary to run code only if a certain condition is true. For example, the programmer might want to delete the contents of some cells, but only if the value present in them is greater than 10,000. The test of a logical condition (also called predicate) involves the use of so-called conditional statements, involving the use of comparison operators (=, >, <, >=, <=) and logical operators (AND, OR, NOT). The examples below will focus on the construction of predicates. Example 1: In order to test whether a cell contains a value >10,000, the condition to be used is:

(Range("A1").Value > 10000)

Where: Range("A1").Value returns the value of cell A1 > is a comparison operator 10000 is the comparison value

Example 2: In order to test if cell A1 contains the value 10 and cell A2 contains the value 20, it will be necessary to write:

(Range("A1").Value = 10 And Range ("A2").Value = 20)

Where And is a logical operator that returns True only if both expressions are true.

Example 3: In order to test whether cell A1 contains the value 10 or cell A2 contains the value 20, it will be necessary to write:

Page 8: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

8

(Range ("A1").Value = 10 Or Range("A2").Value = 20)

In this case, the logical operator Or returns True if at least one of the two conditions is true.

Example 4: In order to test if cell A1 does not contain the value 10 and cell A2 does not contain the value 20, it is possible to write:

Not (Range("A1").Value = 10 And Range ("A2").Value = 20)

The operator Not makes the condition in parentheses negative.

The combination of two or more comparison operators allows the creation of increasingly complex conditions: for this reason, the correct use of round brackets is fundamental to separate logic blocks.2 1.2.1 The IF statement

Predicates are tested through two different statements. The first is the If statement, which reminds of Excel’s If function. Its syntax is:

If «condition» then «instructions» End if

Or

If «condition» Then «instructions» Else «instructions» End if

In the first case the code is executed only if the condition is true; in the second case the program performs a test on the condition: if the condition is true, then the first block of instructions is executed, otherwise the second block (the one after the Else statement) is executed. The example in the figure below describes both cases.

Figure 1.13 ‐ Example of If statement 

It often happens that the logical conditions to be evaluated provide more than two possibilities. Such cases require the use of nested If statements (as shown in the figure below) and the use of the keyword IfElse (Figure 1.15).

                                                            2 The use of parentheses is fundamental to the construction of complex conditions. For example, the condition "(a=b Or c=d) And e= f" is different from "a=b Or (c=d And e=f)". If a=b were true, c=d were true and e=f were false, the first condition would return false, while the second would return true.

Page 9: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

9

Figure 1.14 ‐ Example of nested If statements 

Figure 1.15 ‐ Example of IfElse 

1.2.2 Select… Case

The block Select… Case represents an alternative to the If statement, when there are three or more possible choices. The block is composed by the instruction Select Case, followed by the value that must be evaluated and, finally, the instruction End Select. Within the block, for each condition an instruction Case will appear, followed by the logical condition and the code to be executed if the latter is true. Logical conditions can be expressed in four different syntax: Case value1, value2, value3: this syntax is used when the initial value is compared to one or more

values, and a part of code has to be executed if the initial value matches to one of those.

Page 10: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

10

Figure 1.16 ‐ Select Case statement with multiple specified values  

Case value1 To value2: the comparison is carried out within a range that goes from Value1 to Value2. If the data is included in that range, the code that follows the Case statement will be executed.

Figure 1.17 ‐ Select Case with To keyword 

Case Is complex_predicate: in order to specify inequality or complex logical conditions (for instance, involving one or more logical operators) the keyword Is is used, followed by the condition to be tested.

Figure 1.18 ‐ Select Case with Is keyword 

Case Else: this last possible syntax concerns the residual case, which contains all those values not provided for by the preceding Case instructions.

1.3 LOOPS

Loops are an extremely important component both in VBA and, in general, in all programming languages. They have the aim of executing several times a group of instructions, thus avoiding replicating the code to perform operations repeated in sequence. The structures that implement loops are more than the simple repetition of instructions: in fact, through the use of counter variables that are incremented in each loop, they allow to make the execution of the instructions dynamic. In VBA there exist the following structures: For… Next

Page 11: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

11

Do…While and Do…Until For Each… Next

1.3.1 For... Next

This construct allows creating a loop through the increase in a variable that goes from a starting value to a final value. The level of increase is defined by the programmer. The syntax is as follows:

For variable = initial_value To final_value Step increase Instruction to be executed in the loop Next variable Where: Variable is a numeric variable Initial_value is the value assumed by the variable during the first execution of the loop final_value is the value to which the variable will be increased through an increase in each run Step represents the increase. If omitted, the value is 1. The value could also be negative (decrease).

In this case, final_value will be lower than the initial_value.

Figure 1.19 For…Next Loop 

The loop For...Next can be interrupted by the instruction Exit For. Such instruction is often used within If expressions to test a certain exit condition. 1.3.2 Do…While and Do...Until

The Do...While loops always repeat a block of instructions while a certain condition remains true. The syntax is: Do While condition instructions to be executed in the loop Loop For example, the condition may consist in the comparison between a counter variable and a limit value, beyond which the loop necessarily must stop. The variable must be increased within the loop, otherwise the program will never leave the loop. It has to be noted that the check on the condition can be done either at the beginning or at the end of the block of instructions. In all cases, attention should be paid when setting the test condition. The example in the figure below shows two loops (the second and the third) sharing the same condition (i<=10).

Page 12: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

12

Figure 1.20 Do…While Loop 

In the first loop, the check on the condition is carried out at the beginning and the execution of the instruction does not occur, since the variable i is set to value 11. In the second, the loop instructions are executed: the control on the variable i is performed at the end of the loop so even if it is worth 11, the loop is executed, albeit only once. There is an alternative syntax for the loops Do...While, which is useful mentioning for compatibility with previous versions of the program, and is shown in the figure below.

Figure 1.21 While…Wend Loop 

The loops Do...Until are similar to the Do…While loops, with regard to their syntax. What changes is how the condition is controlled: in fact, the loop is active until the moment a certain condition occurs, meaning until it remains false. Even with Do…Until the condition can be controlled both at the beginning and at the end of the loop.

Page 13: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

13

Figure 1.22 Do…Until 

It is possible to anticipate stopping the Do...While and Do...Until loops by the use of the instruction Exit Do. 1.3.3 For Each…Next

Loops such as For Each…Next use, in lieu of a numerical counter variable, an Object type variable: these loops are used to retrieve objects of a collection one by one, creating a reference within the Object variable. It is possible to perform an action on each of the collection’s objects, as displayed in the following figure.

Figure 1.23 ‐  For Each Loop 

1.3.4 Nested loops

Nested loops are created within other loops. They are used when, in presence of two lists (Array or Collection), for each element of the first an operation must be performed on each element of the second. Of course, it is possible to nest more than two loops. For example, suppose that a matrix of random numbers has to be created in a Worksheet. Number generation occurs through the Rnd function, which generates a random number between 0 (included) to 1 (not included) every time it is used. The nested loop allows to move across the rows and columns of the spreadsheet, and enter a number in any cell.

Page 14: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

14

Figure 1.24 ‐ Nested loops: creation of a random number matrix 

 

1.3.5 Reading a Text File

Loops can also be employed for reading text files. The loop can read the lines of the file and write its content in a cell. In the example below, in addition to the loop, also the functionalities for opening and closing a file (Open e Close), for reading line by line (Line Input), and for controlling the end of the file (EOF), are used.

Figure 1.25 ‐ Using a Reading_from_file loop 

Page 15: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

15

1.4 SUBS AND FUNCTIONS: INSIGHT

Having become more familiar with VBA, it is worth analyzing in detail some aspects connected to Sub and Function, such as the methods for calling, passing parameters, and optional parameters. 1.4.1 Calling Subs and Functions

Once implemented, Subs and Functions can be called in numerous different ways. With regard to Subs, it is possible to use: The name of the Sub, without specifying any keywords but specifying the possible parameters,

instead. It is worth highlighting that, in this case, parameters are not considered as default references (cf. later paragraphs).

The keyword Call, followed by the name of the Sub and the parameters. The method Application.Run followed either by a text enclosed in double quotes, or by a text type

variable and possible parameters. The text (or variable) contains the name of the Sub. Such method is particularly useful to make the call dynamic, selecting the name of the procedure that has to be launched through an algorithm.

Figure 1.26 ‐ Example of Sub calling 

Similarly, also Functions can be called, even if, contrary to Subs, they can return a value. It is possible to use the Call instruction or the method Application.Run with Functions, although not advisable, since both Call and Application.Run do not allow the output value of the Function to be retrieved. The aim of a Function is that of retrieving a value: if this value cannot be retrieved, the Function becomes useless.

Page 16: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

16

Figure 1.27 ‐ Examples of Function calling 

1.4.2 Static Specifier

In addition to the Public and Private specifiers previously treated, Subs and Functions have a further optional specifier: Static. This allows the programmer to preserve the value of variables declared within the procedure among different calls. It means that if, for example, a variable is declared as an integer in a Sub and is assigned a value of 10, in a possible subsequent call to the same sub, the variable will still have the same value (10). Such value could still be modified at a later time, since the concept of static does not mean that the value can never be changed, but it means that the value persist even after exiting a Sub. The following figure shows an example in which a Function is declared as Static. Calls made in sequence return a value gradually increased by 1. If the Function had not had the Static specifier, the value returned would have always been 1.

Figure 1.28 ‐ Static Function 

Page 17: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

17

It is worth mentioning that the maintenance of a value between procedures can be achieved simply through the use of module variables, that means declared outside individual procedures at the beginning of a module. 1.4.3 Passing Parameters

In the examples seen so far, Sub and Function that accept parameters were introduced. However, this topic has not been analyzed in detail. First of all, it is important to state that parameters allow to pass values from procedures to other procedures (either Subs or Functions). Passing of a Function’s parameters can also be performed directly by the user, using the function of the Excel spreadsheet. It is worth noticing that parameters are actually declarations of variables, enclosed in parentheses that follow the procedure’s name: in the same way as variables, parameters have a name followed by the keyword As and the data type. A procedure can behave in different ways with regard to the presence of parameters: Do not accept parameters Accept a fixed number of parameters Have optional parameters Accept an undefined number of parameters

In the examples below, the mentioned possibilities are displayed. The first and the second example show cases that were previously analyzed: a Sub (or a Function) without parameters is simply defined by empty parentheses that follow its name; procedures with a fixed number of parameters, instead, require a list of parameters and their names and data type enclosed in round parentheses. To declare an optional parameter, the parameter itself must be preceded by the keyword optional. It is possible to assign the optional parameters a default value, which is used in case the parameter is not passed during the call.

Figure 1.29 ‐ Optional parameters 

Page 18: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

18

Sometimes it is necessary to provide an undefined number of parameters. For example, a sum function could be created to work with 2, 3, 4, ..., n addends, passed as parameters. The keyword ParamArray allows to implement Subs or Functions with a non-pre-defined number of arguments. The parameter defined by ParamArray is an array, as the keyword suggests, and its data type can only be Variant. Furthermore, the ParamArray keyword can be used only for the last parameter of the procedure.

Figure 1.30 ‐ Use of ParamArray 

Finally, it is appropriate to distinguish between passing parameters by value and passing parameters by reference: in the first case, the value that is passed to the called procedure is copied into the parameter, and any change that is made on it in the calling process does not affect the original value in the calling Sub or Function. In the latter case, the reference to the value is passed to the called procedure, therefore any modification affects the original data. The default setting for passing parameters is by reference (still, it is possible to make it explicit using the keyword ByRef). For this reason, to prevent a Sub or Function from modifying data in the calling procedure, passing by value must be explicitly specified (by keyword ByVal).

Figure 1.31 ‐ Passing parameters ByRef and ByVal  

Page 19: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

19

Figure 1.32 ‐ Testing procedure on ByRef and ByVal 

1.5 BUILT-IN FUNCTIONS

In the closing paragraph, a list of the most common VBA functions is presented, divided by subject matter (for example functions that work on strings, math functions, date functions, etc.). A complete list is available at the Microsoft MSDN website, or at excelfunctions.net3, which offers a wide perspective of the available functions. In each of the following paragraphs, a table with the function name, a brief description, and a small example of use is shown. Before presenting the list of VBA functions, it is necessary to specify that they cover only part of the Excel functions. However, if during the creation of a program a function of the spreadsheet that is not present in VBA is needed, it can still be used through the property Application.WorksheetFunction, which contains all the functions of the spreadsheet.

Figure 1.33 ‐ Some members of Application.WorksheetFunction 

                                                            3 http://www.excelfunctions.net/vba-functions.html.

Page 20: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

20

1.5.1 String Functions

Functions for manipulation of strings are particularly useful, since it is often necessary to prepare and format data contained in text strings. Function  Description  Example 

Left Returns the first n characters of a string, starting from the left Left(“test”,2)

Right Returns the last n characters of a string from the right Right( "test",2)

MID Returns a portion of string, starting from the position and the number of characters specified

Mid("test string",5,2)

Len Returns the length of a string Len(var_string)

Replace Replaces a portion of the string Replace(“ciao a tutti”, “ciao”, “Buongiorno”)

Split Splits a string, according to the given delimiter, creating an Array of strings

Split(str, ",")

Join Joins several strings contained in an Array into one string. The concatenation is performed using a delimiter, specified as a parameter

Join(str_array, "-")

Format Returns a string containing an expression formatted according to instructions contained in a format expression.

Format(# 12/31/2016 12:00:00 PM #, "dd / mm / yyyy")

INSTR Specifies the position of the first occurrence of one string within another. InStr("string functions in VBA", "for") Table 1.2 ‐ String functions 

1.5.2 Date Functions

Dates are a complex data type, as the concept of date includes the concepts of year, month, day, hours, minutes and seconds. Moreover, operations on dates, such as for example the difference between two dates, would be very complex without the adequate functions. Function  Description  Example 

Now Returns the current date and time Now()

Day, Month, Year, Hour, Minute, Second

Return the corresponding part of date or time Year (# 1/1/2016 #)

DateAdd Adds a specified time interval to a date. The interval is represented by an integer. The type of interval can be: “d” for days "h" for hours “n” for minutes "m" for months "q" for quarters "s" for seconds "ww" for weeks "yyyy" for years

DateAdd(”yyyy”,1,var_date)

DateDiff Returns the number of time intervals between two specified dates. The interval type is specified in the same way as in the DateAdd function

DateDiff(“d”,var_Date1,VarDate2)

DateSerial Returns a date for a specified year, month, and day DateSerial (2016,8,31) DateValue Returns a date from a string DateValue ("12/31/2016")

Table 1.3 ‐ Date Functions 

Page 21: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

21

1.5.3 Mathematical Functions

VBA, just like every programming language, is provided with a certain number of mathematical functions. Function  Description  Example 

Abs Absolute value Abs(num_var)

EXP Exponential function Exp(num_var)

Log Natural Logarithm Log(num_var)

Mod Remainder of division Num_var Mod divisor_var

Rnd Generating a random number> = 0 and <1 Rnd()

Round Rounding (to a specified number of decimals) Round(10.1234, 2) Sqr Square root Sqr(2)

Table 1.4 ‐ Mathematical Functions 

1.5.4 Information Functions

Information functions, identified by their prefix Is, test certain conditions on data or variables. For instance, they allow to distinguish between numerical data and Objects. Function  Description  Example 

IsDate Recognizes if the expression is a date IdDate(string_var)

IsEmpty Checks whether the Variant variable is empty IsEmpty(variant_var)

IsMissing Checks whether an optional parameter is missing IsMissing(p_opt)

IsNumeric Checks whether an expression can be evaluated as a number IsNumeric(var_string)

IsObject Checks whether an expression can be evaluated as an object IsObject(var) IsDate Checks whether an expression can be evaluated as a date IdDate(var_string)

Table 1.5 ‐ Information Functions 

1.5.5 Conversion Functions

Conversion functions are used to convert values into different data types. For example, a string containing a date remains a string and cannot be manipulated with date functions, unless it is transformed with the function CDate. Function  Description  Example 

Asc Returns an integer representing the ASCII character code Asc("A")

Chr Returns a character associated with the ASCII code Chr(13)

CDate Converts a value to a date CDate("12/31/2016")

CDbl Converts a value to a double CDbl("10,123")

CInt, CLong, CSng, CDec, CVar

Converts a value to Integer, Long integer, Single-precision number, Decimal, and Variant

CInt(variable)

Table 1.6 ‐ Conversion Functions 

Page 22: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

22

1.5.6 Other Functions

In the table below some useful function are listed, which are not classifiable into the previously mentioned categories. Function  Description  Example 

MsgBox Displays a message MsgBox("Test")

InputBox Requires user input v = InputBox("Enter a number")

LBound Returns a Long containing the smallest available subscript for the indicated dimension of an array.

LBound(array, 1)

UBound Returns a Long containing the largest available subscript for the indicated dimension of an array.

UBound(array, 1)

Array Creates an array with data passed as parameters Array(1,2,3,4) Filter Returns an array containing subset of a string array based

on a specified filter criteria Filter(string_array, str_filter)

Table 1.7 ‐ Other functions 

1.6 OBJECT-ORIENTED PROGRAMMING

1.6.1 OOP

Object-oriented programming has been an important step in the evolution of programming techniques. Among the main advantages of object-oriented programming, it is possible to mention the ability to reuse code, thus avoiding duplication and making program maintenance easier. In chapter 9, objects have been defined as software elements that contain both data structures, called properties, and procedures that act on them, called methods. In the same chapter, the evolution of programming languages has been traced, and it has been stated that some languages implement mixed programming paradigms. In this section, the characteristics of a ‘pure’ object-oriented language will be described in detail, then analyzing whether these characteristics are present in VBA. The key attributes of an object-oriented language are: Encapsulation Abstraction Polymorphism Inheritance

Encapsulation is the characteristic of an object of containing everything that is logically connected to it: both in terms of data and procedures that perform actions and transformations on data. Therefore, each object uses only the data it contains or that have been passed to it. In a way, the object ‘hides’ the data, since the internal structures can only be reached if they are exposed through properties or methods. The concept of abstraction is particularly important and its comprehension is fundamental for the correct use to object-oriented programming. It concerns the process of abstracting data and procedures from a class. The class represents the behavior of an entity, while the actual object is an instance of a class. The class is the model, an empty container, while the object is the final product created according to the model. The model is one, while different objects can be created depending on the data with which they are filled. For example, a Customer class, from which an abstract model of a typical customer can be created, could have the properties Code, Name, Surname, City. An instance of that class could have the properties valued as follows: Code = 1, Name = "Mary", Surname = "Smith", City = "Milan". Similarly, numerous other instances could be created, representing different clients. Polymorphism indicates the ability of different objects to exhibit a similar group of properties and methods. Inheritance refers to the process by which the subclasses derived from a superclass (or base class, i.e. the class from which other classes derive) can use the methods and properties of the latter. This mechanism allows the programmer to write generic code in the superclass, implementing the specific code in each of

Page 23: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

23

the subclasses. Inheritance can be exploited in two ways: the first is the one just described, by which it is possible to not duplicate the generic code, encapsulating it in the methods of the base class; the second consists in only defining the structure of the base class, leaving the methods empty, which can thus be defined as virtual. Inheriting from this type of class implies that the interface is adopted and every method implemented in each derived class. Now polymorphism and inheritance will be described through an example. A generic class from which classes that are more specific are derived will be considered. Each of the derived specific classes implements a method of the parent class in a different way. It is possible to think, for example, to a MusicalInstrument class, which represents the common characteristics of the instruments. The class might have an InstrumentType property (for example percussion, string, wind instruments, etc.), and a PlayNote method, (which accepts a Note parameter). A derived class might be Guitar, which inherits the PlayNote method from the base class, but this method will be implemented to produce a particular sound (the sound of the guitar). The same thing would be true for the Piano class or the Violin class. The MusicalInstrument class is able to recognize what kind of instrument (object) should be used and which PlayNote method called to produce the desired sound. Thus, classes are created that have all the same interface (set of properties and methods), while the call to a certain method of any of the classes always takes place in the same way. To further exemplify, it is possible to mention the case of a Collection of MusicalInstrument objects, where several instruments can be inserted. Scrolling the collection with a For Each loop, it is possible to extract each instrument assigning it to a MusicalInstrument variable (it would not be possible to do anything else, since the individual instruments are incompatible with each other!). At this point, by calling the method playNote, the correct sound for each of them would be obtained.

Figure 1.34 ‐ Base class and derived classes 

In general, when methods with the same name and the same parameters are present in different objects, polymorphism is used. Object-oriented programming is implemented differently in different languages. In particular, there are two types of implementations: ‘Pure’ object-oriented languages (Smalltalk, C++, etc.) Object-modeling techniques used in languages that were born as procedural (e.g. Cobol, Visual

FoxPro, Visual Basic 6 and VBA)

Page 24: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

24

1.6.2 Object-Oriented Programming Elements in VBA

Object-oriented programming in VBA makes almost all the features highlighted in the previous section available. Each of these characteristics will be exemplified with specific reference to the following paragraphs. Encapsulation is achievable by maintaining the data in the class isolated from the outside world, making them accessible only through properties (Property Get and Property Let specifiers), and methods (Sub or Function declared as public). The principle of abstraction also exists in VBA: a class is defined within a specific module (in fact called class module) and to use it, it has to be ‘instantiated’4 by the keyword New; it will then be possible to define properties and execute methods with regard to the instance only, i.e. the actual object. There is therefore separation between the class structure and its instances. Even polymorphism is achievable. It is sufficient that two objects expose the same method to call that method from a generic type variable (a variable of the Object type or a parent class from which the two objects may inherit) used in place of the two classes. Inheritance is only partially implemented in VBA, since it is limited to the class ‘interface’, meaning the set of public methods and properties that the parent class exposes. In practice it is as if all the methods and properties of the latter were virtual (i.e. without code), and properties or methods of the parent class, whether public or private, cannot be accessed from the derived classes. This forces the developer always to implement the methods and properties in derived classes, thus imposing a limitation to the full ability of object-oriented programming. 1.6.3 Naming Convention

Naming convention is a set of rules used to define the names of variables, methods, properties, and classes. Here a naming convention too rich in detail will not be given, but limited to simple common sense rules. A complete naming convention can be retrieved on the Microsoft MSDN site5. Using some Microsoft specific rules, a simple naming convention can be defined as follows. All names: they must be readily understandable, must explain the contents of the object, variable,

method. In addition, it is necessary to keep names quite simple. For class, methods, properties, events, and modules’ variables names, the uppercase should be used and, if more words to form the name were needed, they have to be consecutive, without separators and with the first letter capitalized (e.g. Customer, CustomerName, CustomerSurname)

Class names: the name will have the prefix cls. For example, a class dedicated to describing customers might be called clsCustomer

Names of global variables: the name will have the prefix g Names of module variables (defined outside of procedures): the name will have the prefix m Names of variables internal to procedures: they have lowercase letter, and do not have any prefix.

In case of compound names, the second word will have a capital letter (for example discountPercentage)

The prefix that indicates the type of data in variables6, such as in Microsoft naming convention, is not used

                                                            4 Instantiate means using a class as a template to create a real object, to which a space in memory is reserved and which allows the programmer to interact by reading or setting property values, or by executing the methods. 5 https://msdn.microsoft.com/en-us/library/aa733744%28v=vs.60%29.aspx: at this address and related pages, the rules for naming objects, variables, properties, and methods are listed. 6 According to the Microsoft naming convention, an Integer type variable should have the prefix int, for example intValue, intCounter, etc. Similarly, a double variable would have dbl as a prefix, and a string variable would start with str.

Page 25: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

25

1.7 CLASSES

1.7.1 Classes in VBA

In the previous paragraph, the difference between class and instance has been exposed. Class has been defined as the structure of an entity designed to contain data (properties) and to act on them through methods. The instance, on the other hand, is the realization of a class, for which a memory space is reserved and in which the specific data of an entity are inserted. The class is represented by code that has certain characteristics. In this case, using VBA, the creation of a class is a fairly simple operation, and feasible with few steps: In the VBA editor, in the VBAProject node, and then in the Project window, a class module must

be inserted: with a right-click on the Class Modules folder, it is possible to enter the command Insert/Class Module

Afterwards the module must be renamed, through the Name item, in the Properties window The last step consists in inserting the code

In the class module, various elements can be inserted, each of them with a very specific task. The following figure shows the example of the clsCustomer class, which will be used in the following explanation. The clsCustomer class describes customers of a hypothetical company.

Figure 1.35 ‐ The clsCustomer class 

Class variables will be now taken into consideration. They are variables, declared outside of procedures or properties, that have the task of containing the data of the single instance of the object. In general, they should always be declared with the specifier Private, making them visible only within the class. From the outside, access to the variables takes place through the properties. In the example, it is shown how two class variables have been declared: mName, which will contain the customer's name and mQt,

Page 26: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

26

which will contain the sum of the quantities purchased. It could also be possible to avoid the properties and expose a public variable directly, if there is no logical calculation or control, but only the assignment of a value is needed. Anyway, behind the scenes, VBA creates the elements Property Get and Property Let also for public variables, but without exposing them explicitly through code. 1.7.2 Properties

The declaration of a property can be carried out by creating one or two elements that act on a class variable. An item, actually a Function, is introduced by the keywords Public Property Get and allows to return the property value. The other element, preceded by Public Property Let, sets the value of the property. The latter looks like a Sub with a parameter. The data type of the property is defined both in the Get, through the specification of the return value, and in the Let, through the specification of the type of the input variable. In the class in the example, the Name property presents both the Get and the Let element that respectively read and set the mName variable. On the other hand, the TotalPurchases property only presents the Get element, being it configured as a read-only property. Below, all the possible types of property arising from the use of the specifier and keywords Get and Let are listed: Public properties: they are visible outside the class Private properties: they are visible only within the class itself. They are useful when attributing a

value of a variable, although it takes place internally to the class, is not limited to the simple assignment of a value, but requires writing complex code (for example to check if a value is in the range considered correct etc.)

Read-only properties: allow the programmer to read the value of the property, but not to set it. They are realized by writing only the Get procedure. These properties allow the programmer to access values that do not have to be set directly from outside. In the example, the TotalPurchases property allows the programmer to read the mQt variable, which is set by a (simple) calculation, when the customer completes the purchase action, carried out with the method of the same name

Write-only properties: they are characterized by the implementation of the Let element only. Generally, they are used when it is not necessary to return the value of a property, but still it is necessary to give the possibility to set it from the outside

Properties with reading and writing: they are made with either the Get element and the Let element, and allow both to read and set the value

1.7.3 Methods

Methods are created as Subs or Functions and can be both public and private: in the first case they are accessible from the outside, in the second case they are visible only within the module. The class clsCustomer has two Public methods, one implemented as a Sub, to manage the Purchase operation, the other implemented as a Function, to determine and return the discount rate to which the customer is entitled. There are methods with and without parameters. About the latter, it is worth mentioning the use of the keywords Optional and ParamArray. Optional allows the creation of optional parameters, to which a default value is assigned. The method is then called in different ways: by specifying the non-optional parameters only, or specifying also the optional ones (wholly or partially). ParamArray specifies array type parameters, which do not have a predefined size. Such a system allows a procedure to receive any number of values. The mechanism by which a method presents various calling mode is defined overloading. In VBA, this mechanism is implemented only through the instructions Optional and ParamArray, while in other languages it is implemented by rewriting the method and assigning it different parameters or return values.

Page 27: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

27

1.7.4 Class Instances

Once created, the class can be used as a data type for variables. However, declaring a variable is not enough to access methods and properties. In fact, the class should be instantiated first, meaning that an implementation has to be created, reserving a space in memory. This operation can be carried out by using the keyword New, as shown in Figure 1.36. In case of attempt to use an object variable that is not instantiated, the error displayed in Figure 1.37 would be shown.

Figure 1.36 ‐ Creating a class instance 

Figure 1.37 ‐ Error caused by the missing instantiated object variable 

1.7.5 Class_Initialize and Class_Terminate Events

Class variables, methods and properties are not the only elements that can be created within a class. Events, which will be discussed extensively in Chapter 1.8, should be added to such elements. It is worth mentioning briefly the event Class_Initialize: this is a Sub that is automatically performed when a class is instantiated. For this reason, it is useful to include in that event the code necessary to initialize the object’s properties. Similarly, with Class_Terminate, it is possible to execute code automatically in conjunction with the destruction of the object, which occurs by setting the variable that contains it to the value Nothing. The two events are accessed by clicking on the drop-down list box above the code window, on the left, where the list of interfaces is. From this box, Class must be selected, the main interface, then moving to the right drop-down box, the event selected.

Page 28: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

28

Figure 1.38 ‐ Initialize event 

 

1.7.6 Constructors and «Helper» Functions

For a complete analysis of classes, it should be noted that, unlike in other object-oriented languages, in VBA the ‘constructor’ method does not exist, i.e. a method with the same name of the class, in which the programmer can insert both the initialization code, and parameters to be passed at the time of instance creation. This lack can be remedied by creating a fake constructor with a Public method, with the parameters that have to be passed to initialize the class variables. To further ease the task in the process of creating an instance, a simple and effective technique is here described: the implementation in a module of a helper function, able to create and return an instance of the desired class. The following figure shows an example of a fake constructor method (added to clsCustomer class), the implementation of a helper function, and their use. As it can easily be seen, the CreateCustomer function returns an instance of the class clsCustomer already initialized with the name, passed as a parameter of the function.

Figure 1.39 ‐ Fake constructor method and helper 

1.7.7 Polymorphism

Although VBA poses limitations to the inheritance and, therefore, also to the polymorphism, it is still possible to realize both characteristics. The major limitation is the derived classes’ inability to use methods and properties of the base class. Essentially, VBA allows the definition of interfaces with virtual methods, but not the definition of base classes with implemented and inheritable code. However, it is possible to use techniques that simulate the latter features. First, the construction of two polymorphic objects will be introduced. For example, two distinct classes for the representation of a private and a corporate customer have to be created. The classes differ in the presence of a specific property related to the type of customer (FidelityCard for the private and VATid for the corporate customer), and the implementation of the method ComputePercDiscount, which occurs with a slightly different algorithm. However, the classes are very similar to each other, having in common the ComputePercDiscount method, the Name property, and the Buy method.

Page 29: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

29

Figure 1.40 ‐ CorporateCustomer class 

Page 30: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

30

Figure 1.41 ‐ PrivateCustomer class 

This similarity allows to put in a variable of the Object type an instance of each of them, and to perform, for example, the ComputePercDiscount method, without knowing in advance which of the two classes is called. The usefulness is obvious when the ability to create generic procedures that manage both objects is considered. In the example, the display of the discount rate is managed through a Sub that accepts an Object as a parameter and displays the discount rate (of course, in real life, implementations are more complex!). The method call occurs through a mechanism known as late binding, which determines the object type only at run time (only when it is executed). Late binding is convenient because it allows to generalize the code extremely, but has the disadvantage of being very slow (even hundreds of times slower than the early binding, i.e. the mechanism used in presence of a variable that represents the object specifically). In the following figure, the example described above is displayed.

Page 31: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

31

Figure 1.42 ‐ Use of polymorphism 

Polymorphism between two or more classes may be partial or total, if it involves all methods and properties. Therefore, if a non-existent method is called through the technique mentioned above, VBA will return to a run time error, while in the programming stage there will be no evidence of the problem. As in the case of the Variant, for classes as well it is possible to control the type of object contained in a generic data type; this control is carried out in two ways: TypeName Function, which returns the name of the object type Keyword TypeOf ... Is, which tests the data type of an object by comparing it with a type specified

by the programmer

Figure 1.43 ‐ Test of Object Types 

Page 32: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

32

1.7.8 Interfaces and Inheritance

In addition to the previous academic examples, in actual programming, often dozens of properties and methods are attributed to an object. Dividing them into groups becomes an organizational necessity, since it makes their identification and use easier. A group of properties and methods related to each other is called interface. As already seen before, VBA allows programmers to create interfaces, achievable through the definition of a class (not implementing methods and properties). Attribution of one or more interfaces to a class takes place via the keyword Implements, and forces to define the methods and properties of the interfaces in the class. It is worth reminding that VBA does not allow the full inheritance that would make inheritance and use of methods and properties possible also in derived class, if a base class with methods and properties had been defined. Interfaces are the only form of inheritance admitted by VBA. The inclusion of Implements and one or more interfaces in the class module makes all properties and inherited methods available, which are placed in the drop-down boxes above the code window (Figure 1.38). As already mentioned, users are forced to implement them all, otherwise an error at run time will occur. The example in the following figures contains: The creation of ICustomer interface, which exposes common methods and properties (Figure 1.44) The creation of two classes (clsPrivateCustomerInterface and clsCorporateCustomerInterface)

that implement ICustomer (Figure 1.45) A Sub that instantiates objects and uses both methods/properties of the ICustomer interface, and

methods/properties of the two classes (Figure 1.46) A Sub that accepts a parameter of type ICustomer (Figure 1.46)

In both classes, properties and methods of the interface are declared as Private and are prefixed ICustomer_ (i.e. the interface name followed by the underscore). The specifier Private makes the members of the interface invisible when using the final class as a data type; such members will only be accessible through variables with data types corresponding to the interface. Figure 1.46 shows such a peculiarity: for each object, two variables are declared in the code, one for the class itself and one for the interface; the latter is assigned a reference to the first.

Figure 1.44 ‐ Icustomer Interface 

Page 33: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

33

Figure 1.45 ‐ Classes with ICustomer Interface 

Figure 1.46 ‐ ICustomer Interface Testing Procedures  

 

1.7.9 Inheritance by Delegation

Inheritance in VBA is partially feasible, due to the impossibility to access the methods and properties of the parent class (or base class). To mitigate the problem, a technique is presented, called inheritance by delegation, which provides: The definition of an interface, using an abstract class (with no code in methods and properties), as

seen in Figure 1.44 The definition of a base class that implements the interface, in which methods and properties,

shared by all classes that will be derived, are created (see Figure 1.47)

Page 34: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

34

The creation of derived classes that implement the interface and contain a variable of the interface type (to which an instance of the base class is assigned). In the interface’s methods and properties, instead of rewriting the code, it is possible to use the methods and the properties of the base class (as displayed in Figure 1.48)

Figure 1.47 ‐ CustomerBase class 

Page 35: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

35

Figure 1.48 ‐ Derived class 

1.7.10 Object Hierarchy

So far, properties or variables that are internal to classes have always been defined as containers of simple data types. In reality, both variables and properties may refer to objects, meaning instances of other classes, or collection of objects. Therefore, it is possible to create object hierarchies. For example, should an evolution of the customer class be needed, it could be possible to create in it the PurchasedProducts property, consisting of a collection of the Product object (a new class that contains data related to a product). For an example, see the next paragraph. Objects at a lower hierarchical level (i.e. those contained in the first object) may contain other objects, and so on. It is sufficient to think, for example, to what happens in the Excel object model: the Workbook object contains the Worksheet object, which contains the Range object.

Page 36: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

36

1.7.11 Collection Classes

Creating a collection is a simple operation as it is only necessary to instantiate the Collection class, which provides the structure for a container of generic objects. The Collection class has the following methods: Add, to add an item Count, to count elements Item to return the n-th element Remove, to delete an item

An example of the use of a Collection is shown in the figure below. The first part of the figure shows the product class, deliberately created in a very simple way. The second part contains a fragment of the clsCustCollGen class code (similar to clsCustomer class); in particular, in the last line of the fragment, the public variable of collection type is declared and instantiated. In this case, the choice not to use the Get and Let Properties is due to a practical reason: exposing the collection in this way, methods become immediately available, with no need to write additional code in the class. The third part of the figure contains few lines of code, which allow using the clsCustCollGen class and the collection it contains.

Figure 1.49 ‐ Using the Collection 

The Collection class is extremely useful, but, as it is able to accept any object, it may not always be the ideal choice. It is advisable to avoid using generic containers (Object or Variant), due to issues related to execution performance, and for improving code strength and cleanup: for example, what would happen if a customer object were inserted into a generic Products collection? To avoid problems it is preferable to create collections specialized on the type of object to contain. This requires a short piece of code to make the For Each loop work on the elements of the collection. The ability to enumerate the items in the collection is not reproducible in VBA (Visual Basic 6, on the other hand, allows this operation); it is therefore necessary to expose an additional property (for example Items), which returns the generic collection. In Figure 1.50 the code for the specialized collection is shown, while Figure 1.51 shows an example of use.

Page 37: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

37

Figure 1.50 ‐ Creation of specialized collection clsProductCollection 

Figure 1.51 ‐ Using the specialized collection 

 

 

Page 38: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

38

1.8 EVENTS

1.8.1 What are Events?

Events provide objects with a means to notify to other objects the occurrence of certain situations. The use of events is embodied in three actions: The declaration, which specifies the existence of the event in a class The implementation of the event, which is the action through which the evet is sparked The handling of the event, which is the code executed when the event occurs

It is possible to add events to the classes created, or just handle the events that Excel’s objects provide. 1.8.2 Adding Events to a Class

Here is a simple example of event handling, in which the customer class is enriched with an event that notifies when a certain threshold of purchased products is reached. The reason may lie in the attribution of a loyalty bonus to the customer, or simply sending a thank you email. In the example, the clsCustomer class will be used as a starting point. The first operation consists in declaring the event using the keywords Public Event. The event NotifyPurchaseThreshold exposes the parameter qt, which represents the total quantity purchased by the customer. In the method Buy, the event is raised if it reaches the threshold of 50 units purchased. All this is shown in the following figure.

Figure 1.52 ‐ Declaring and raising of the event 

Event handling is only possible in a class module, in a UserForm type module, or in a module related to Excel’s object (in VBA Project there is one for the Workbook and one for each Worksheet). To test this, the module of the Workbook will be used. The code is included in the following figure. Note that the c variable, which is designed to contain the instance of clsCustomerEvent class, is declared with the keyword WithEvents. This allows VBA to expose events in the drop-down boxes placed above the code window, and the programmer to implement the handling code.

Page 39: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

39

Figure 1.53 ‐ Event handling 

1.8.3 Application Events

Now, the main events made available by the Excel objects will be examined, starting from the Application object, which represents the application itself. Application provides numerous events, which can be exploited by creating a variable WithEvents in a class module and choosing in the dropdown boxes the event of interest. In the example in the figure below, the event SheetChange is implemented to notify the change of the active sheet. Also in this case, an academic example is shown, from which it is easy to understand the potential of events: it is possible to react to any action taken by the user! It can easily be noted that the events Class_Initialize and Class_Terminate have been implemented, with the purpose of assigning the Application object (the running Excel) to the App variable, and eliminating such a reference when the class is destroyed, respectively.

Figure 1.54 ‐ Application events in clsExcelApp class 

The example cannot work without the creation of a Sub that instantiates the new class clsExcelApp, keeping it in a global variable (see the following Figure). Once the Sub TestApplicationEvents is performed, if the user changes the active sheet, the Application object raises the App_SheetActivate event, displaying a message.

Page 40: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

40

Figure 1.55 – Use of clsExcelApp class 

It is worth mentioning the use of the OnTime event. This event is set by specifying a time expressed as a fraction of a day or through the TimeValue function (for example, the number 0.625 (i.e. 15/24) corresponds to TimeValue (“15:00:00 pm”)), and the procedure to be performed at that scheduled time. For example, the following line of code launches the procedure Alarm at seven in the morning: Application.OnTime Timevalue ("7:00:00 am"), "Alarm" The Alarm procedure is a normal sub that contains the code to be launched at the pre-set time. Two other ways of specifying the time of execution of the event OnTime consist in specifying a time from the current date and time (e.g.: in 10 minutes), or to specify, through the DateValue function, a date and a time. The two following lines of code show the different syntax: Application.OnTime Now + TimeValue("00:10:00"), "Alarm" Application.OnTime DateValue ("05/31/2017 8:00 am"), "Alarm" In conclusion, the OnTime event can be disabled by passing the same parameters with which it was set and an additional parameter (Schedule) valued at False. Alternatively, a parameter exists, LatestTime, which indicates the maximum time beyond which it is no longer possible to execute the event. The two alternatives are shown in the lines of code below: Application.OnTime Timevalue("7:00:00 am"), "Alarm", , False Application.OnTime Timevalue ("7:00:00 am"), "Alarm", DateValue( "05/31/2017 7:00 am") 1.8.4 Workbook Events

It could be possible to act on all elements of the Excel object model in the same way as on Application. However, as far as Workbook and Worksheets are concerned, some predefined object modules are needed, which will only require the definition of the event handler. To access these modules, it will be sufficient to double-click on the items corresponding to the sheets (Sheet1, Sheet2, ...) or file (This_Workbook), in the Microsoft Excel Objects folder, under VBA Project, in the project view. Among the many events, the example shows the occurrence of the Workbook_Open event, which is raised when opening the file, and Workbook_BeforeClose, which is executed just before closing the file. Workbook_Open is useful for setting initial settings, before the user acts on the sheet. Some examples of actions to be performed at the opening of the file are: updating data from external sources, setting the method of calculation (e.g. manual calculation), inputting predefined values in some cells, and others. With the same mechanism, also in Workbook_BeforeClose it is possible to execute code that, however, must be aimed at developing clean-up operations, or resetting some settings to their initial values.

Page 41: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

41

In the example below, at the opening of the Workbook an update of all data sources, recalculation, and reset of the manual calculation setting occur. Before closing, the automatic calculation is restored, the spreadsheet saved and a backup copy created, with the addition of the date in the file name.

Figure 1.56 ‐ Workbook Events 

1.8.5 Worksheet Events

Among the great number of events of the Worksheet object, the Worksheet_Change event is particularly interesting. Such event is activated when a change in any Range of the sheet occurs. In the example in the figure below, the property Application.EnableEvents is used to disable the event handling temporarily, in order to avoid a new call to the event, while the event handler itself is modifying the value of the Range.

Figure 1.57 ‐ Worksheet_Change event 

Other events that may be useful are: WorkSheet_BeforeDoubleClick: this event is generated by the double click of the mouse. The

event is activated before the double click produces its effect. Inside the event handler, setting the Cancel parameter to True, the effect of the double click is disabled.

Worksheet_BeforeRightClick: this event is generated by the click of the right button on the mouse and, similarly to the previous event, is activated before the click produces its effect. Also in this case, the event can be disabled by setting the Cancel parameter to True.

Page 42: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

42

Worksheet_Activate: occurs when a worksheet is activated (i.e., when the user decides to switch from one sheet to another).

Worksheet_Deactivate: this event mirrors the previous one; it is generated when the user leaves the current sheet to select another.

1.9 ERROR HANDLING

1.9.1 Programming Errors and Debugging

The programming activity involves, for its own nature and complexity, making mistakes. Without adequate tools to search, identify and correct them, the life of the programmer would be extremely complicated. Fortunately, the VBA environment provides debugging functions, that means removal of errors, also called bugs. There are two major error categories: errors that become evident from the interruption of the program, which is no longer able to continue, and logical errors, related to the algorithm and the intended result. In this section, the most evident errors will be analyzed, including both syntax errors, identifiable before running a program (or even immediately after typing the wrong instructions), and all other anomalous situations (called exception), which only occur at runtime. Some examples: in mathematical formulas, a typical error is the division by zero. Such an error is generated when there is no control on the denominator before performing the division; as long as the denominator is different from zero, the operation works. However, if it is equal to zero, perhaps after the input of incorrect data by the user, an exception is generated. Therefore, it is clear that some errors may be generated in a subtle way and they can be difficult to identify. Other examples regard the use of non-instantiated object variables, or the call of invalid methods on objects passed with the late binding technique. In the next two paragraphs the techniques to handle errors will be examined: in the first paragraph, focus will be on error search, while in the second on how to handle, directly in the code, potentially ‘dangerous’ situations. The ability of the programmer to predict error situations remains essential, who carries out checks on data and applies programming techniques correctly. 1.9.2 Debugging Functions

Debugging functions are instruments that can be useful to understand the reason for exceptions or unexpected results generated by the program. The instruments made available to the VBA programmer are: Automatic error message, with End and Debug buttons Watch expressions Immediate Window Debug toolbar Breakpoints

Automatic Error Message, with End and Debug Buttons

When the program generates an unmanaged exception, VBA displays a dialog box with the number and the message error, asking the programmer either to continue (if possible: it depends on the type of exception), or end, or start debugging (figure below). Choosing the Debug option, VBA highlights in yellow the line that generated the error, displaying the code editor. At this point, the programmer can check the variables status immediately, simply pausing the mouse over them and reading the tooltip that is shown (Figure 1.59).

Page 43: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

43

Figure 1.58 Error Message 

Figure 1.59 ‐ Tooltip with the contents of a variable 

Watch Expressions

Watch expressions can be activated from the menu View, or by right-clicking anywhere on the editor and choosing Add Watch Expression. If the programmer clicks on a variable or a piece of code that can return a result, these elements are inserted directly in the watch expression; otherwise the programmer must type the expression manually (see below). The purpose of the watch expression is to allow the contents of a variable or, in general, of a code fragment to be displayed as the user moves within the program using the commands of the debug bar (or using the function keys). It should be noted that it is possible to use a logical condition as watch expression (for example, divisor = 0) and force the program to stop when the condition occurs. It is also possible to require the program to stop running if the value of an expression changes.

Figure 1.60 Watch Expressions 

Page 44: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

44

Immediate Window

In this window it is possible to write VBA code that is executed as soon as the Enter key is pressed. Typically, it is used to display complex variables and expressions. The question mark, followed by the expression to evaluate, displays the result.

Figure 1.61 Immediate Window 

Debug Toolbar

The debug toolbar can be activated with a right-click of the mouse in the area above the editor. It contains three buttons, which allow the programmer to move within the code by executing step by step instructions. This makes it possible to assess the impact of each line of code on the values of variables. The three buttons, starting from the one on the left, allow users to execute, respectively, a single line, a single procedure and the code within the current procedure, stopping at the end of the current line of code before the subsequent one (this happens when a procedure calls another one).

Figure 1.62 ‐ Debug Toolbar 

Breakpoints

Breakpoints are used when the programmer wants to stop the execution of a program and enter the debug mode, without waiting for an exception to occur. In the VBA editor, simply it will be necessary to click on the gray border on the left, to see a breakpoint in the form of a red dot appear (also the corresponding line of code is highlighted in red). When execution reaches the row affected by the breakpoint, the execution pauses and the programmer can proceed to error correction with the tools described in the previous paragraphs.

Page 45: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

45

 Figure 1.63 Breakpoint 

 

1.9.3 Error Handling with OnError

When writing procedures, errors are likely to occur. In these cases, VBA provides the users with all the necessary tools to manage a possible exception. Below, the keywords that VBA provides for this task are listed: On Error GoTo ErrorHandler. The occurrence of an error does not stop running the program, but

the execution is passed to the portion identified by the label ErrorHandler. It can be imagined as a marker that identifies a point inside the Sub or Function code. The label is simply a name followed by a column. The code for error handling is placed between the label and the end of the procedure or the instruction Exit Sub (or Exit Function)

On Error Resume Next. With this variant of the OnError keyword, errors are ignored, and the program is forced to continue executing the statement subsequent to the one that generated the exception

On Error GoTo 0. In this case, the instruction resets the normal error handling by VBA, that is the error message used by Excel to ask whether to end the process or debug

Err Object. With the property Number the programmer can figure out what type of error has occurred, returning a number that can be compared with the table on MSDN7 website. The Err object also owns the Description property, which gives a technical description of the exception

The On Error statement must be placed before the lines of code at risk, and becomes effective from that point onwards, until another On Error statement is used. The portions of code for handling errors, identified by labels, may be more than one, thus making a specific management possible for every situation. The code portions will have to be separated from each other and from the main procedure by the instruction Exit Sub (or Exit Function, if in a function); in this way, they will be isolated from each other and carried out only if an exception occurs.

                                                            7 https://msdn.microsoft.com/en-us/library/ms234761%28v=vs.90%29.aspx.

Page 46: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

46

Figure 1.64 Error Handling 

In the part of code devoted to error handling, it is possible to use the keywords Resume and Resume Next. The first takes the execution of the program back to the line that contained the error (of course the anomalous situation must be corrected before); the second takes the execution to the line following the one that generated the error. 1.9.4 Return an Error in a Controlled Manner

Sometimes it can be useful to undertake an operation that is different from those seen in the previous section. In some cases, the programmer may want to return an error explicitly as a result of a function, or write a specific error code (e.g. #N/A) in one or more cells through a Sub. With this scope the object XlCVError exists, which acts as a collector of all error codes of Excel, in numerical format. For example, when the input parameters are attributed wrong values, rather than returning a result that would not make sense, the output value could be set as CVErr(XlCVError.xlErrNA), or CVErr(XlCVError.xlErrValue), which respectively produce the error #N/A and #VALUE. The CVErr function converts the numerical code into a real error. An example of use of the object XlCvError and CVErr function is shown below.

Figure 1.65 ‐ Using XlCVError and CVErr 

Page 47: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

47

1.10 CONTROLS AND ACTIVEX TECHNOLOGY

1.10.1 Associating a Sub to a Control

Already in Chapter 9, it was explained how it is possible to associate a macro to a graphic object. The topic is resumed now, with the addition of few details on the type of graphic objects that can be used. It has already been described how, after drawing a shape in an Excel spreadsheet, with a right click on the mouse and the Assign Macro option it is possible to assign the object a Sub that runs when the user clicks on the shape. In addition to shapes and images, Subs may also be associated with controls, which are present in the Development tab under the Insert heading.

Figure 1.66 ‐ Tools Menu 

Even in this case, the association takes place with the right click on the mouse, after positioning a control, and selecting the item Assign Macro. The dialog box proposes the creation of a new macro, or alternatively, the assignment of an existing macro.

Figure 1.67 ‐ Assigning a macro to a control 

1.10.2 Types of Controls

The Tools menu contains two categories of controls, the Form Controls and ActiveX Controls. Form Controls are simple and offer few configuration properties. They can be used when the user wants to launch a macro without writing additional VBA code. Conversely, ActiveX Controls are more comprehensive as far as configuration possibilities are concerned, but require writing VBA code to perform actions. ActiveX (Active eXtension) is the name of a technology developed by Microsoft and intended for developers, created to extend the potentialities and functions of an application. ActiveX is not a programming language. It is indeed an extension, integrated into an application designed to use this technology, which allows programmers to add new functions, commands, graphics objects. In the

Page 48: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

48

context in which programmers operate, ActiveX controls extend the functionality of Excel, providing them with the possibility to create graphical interfaces to communicate with the user.

1.11 USE OF CONTROLS IN THE EXCEL SPREADSHEET

1.11.1 Using Form Controls

Form Controls are not particularly complex to use, and their interaction with VBA is limited to macro assignment. Some controls also provide for the definition of a cell in which to save their final value. For example, control boxes (or checkboxes) have, among their properties, a linked cell. When set, the checkbox will write in that cell the value TRUE or FALSE depending on the presence of the check mark. This value can then be used to generate events, or simply determine the result of a formula.

Figure 1.68 ‐ Checkbox control 

1.11.2 Using ActiveX Controls

ActiveX controls, once inserted into an Excel spreadsheet, display a series of events, which can be called and implemented in the VBA editor (see Figure 1.70). The properties of a control, such as the description (or Caption), can be edited in the Design Mode, activated or deactivated using the button of the same name (see Figure 1.2). In Design Mode it is possible to access, with a click on the right mouse button, the item Property, which opens a window containing a long list of properties.

Figure 1.69 ‐ Properties window, visible in the Design Mode 

Page 49: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

49

Figure 1.70 ‐ Events of an ActiveX button (CommandButton object) 

The events are in the form corresponding to the sheet where the control is. To exploit a control’s functionalities, it will be necessary to write the VBA code in a event handling procedure or more. For example, the code written within the Click event will be executed when the user clicks on the left mouse button. In addition to Click, the most common events are: DblClick. It corresponds to the double click on the left mouse button KeyPress. This event occurs when any key that corresponds to an ASCII character is pressed on

the keyboard. Through the KeyAscii parameter it is possible to obtain the code of the pressed key and eventually turn it into a character, using the function Chr

KeyDown and KeyUp. These events report the exact state of the keyboard, representing two parameters. The first event represents a key that is pressed down, the second a key that is released (KeyUp). Both parameters are in the form of VBA internal code and can be represented by a group of constants whose names begin with vbKey (vbKeyA, vbKeyB, and so on for each key). The other parameter is Shift, which indicates the pressure of the SHIFT key, together with the character

MouseDown, MouseUp, MouseMove. They correspond to the pressure on or the release of a mouse button, and moving the mouse itself. The parameter Button indicates which button is pressed, while X and Y are the coordinates on the monitor. Furthermore, the parameter Shift informs the programmer if one of the SHIFT, CTRL or ALT buttons are pressed at the same time

GotFocus, LostFocus. These properties allow programmers to intercept the moment when the control becomes active, thanks to a mouse click, or due to the Tab key being pressed

Change. It corresponds to a change in the control state. For example, a TextBox control raises the Change event when the text it contains is edited

Below an example is shown, in which Label, TextBox, and Button controls were added to a Worksheet. The Label has a merely descriptive purpose, while the Button is linked to the Click event, in which the square root of the number entered in the TextBox is computed. To make sure that a number is always entered in the TextBox, in the Change event a control code has been written to prevent the input of non-numeric values.

Figure 1.71 ‐ Example of ActiveX controls 

Page 50: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

50

1.12 CREATING USER INTERFACES WITH FORMS (USERFORM)

1.12.1 Forms

So far, when interaction with the user was needed, the MsgBox and InputBox functions have been used, which are nothing but a very simplified form (or UserForm). The two functions provide a shortcut to form creation, but, of course, have limitations: they allow the programmer to change the title, the message and, only in the case of MsgBox, modify the display buttons. The creation of a complex user interface must then be different, and include the following steps: Inserting a UserForm in the VBA project Adding controls to the UserForm Setting properties of the UserForm and controls, and writing VBA code for event handling Writing code to display the form

1.12.2 Creating a Form and Adding Controls

The creation of a form is easy: by clicking on the right mouse button in the VBA project (i.e. in the Editor window), it is possible to select Insert, then UserForm. The result of this action consists in the appearance, in the project, of the Forms folder, within which the UserForm1 object lies. Simultaneously, the form is opened in design mode in the editor. In this mode, controls can be added to the UserForm. To activate or deactivate the design mode, the button of the same name on the toolbar can be used.

Figure 1.72 ‐ Adding a form 

In the property window (View tab), several elements to configure the aspect of the UserForm are listed. For example, the Caption property has been set to ‘Compute Square Root’, thus modifying the title of the form.

Figure 1.73 ‐ UserForm Properties 

Page 51: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

51

Controls, useful to replicate the example proposed in paragraph 1.11.2 on the calculation of the square root of a number entered by the user, may be added to such form. From the Tools menu (accessible through the button on the Standard toolbar), Label, TextBox and CommandButton can be selected. Properties may be configured as follows: UserForm, Name property =frmComputeSquareRoot Label1, Name property: lblInsert Label1, Caption property: ‘Insert a number’ Label1, Font property: Size 14 Label1, TextAlign property: Center Alignment (2 - frmTextAlignCenter) TextBox, Name property: txtNumber CommandButton, Name property: cmdCalculate CommandButton, Caption property: Calculate Label2, Name property: lblResult Label2, Caption property: empty

Controls were assigned a name that reminds their practical function. The name is preceded by a prefix. It is recommended that names of controls are short (here three letters were used), and suggest the type of control. The following figure shows the complete UserForm, the toolbar, and the Properties window for the first Label.

Figure 1.74 ‐ Form with controls 

1.12.3 Implementing Events

Using the same example, it is now possible to enter the code for the execution of the calculation and for the control of the values entered in the TextBox, which must be numeric. To enter the code, it is possible to make a double click on the button, or use the menu that opens by clicking on the right button of the

Page 52: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

52

mouse on the UserForm in the VBA project, and choosing the View code option. Choosing Show object, instead, the design mode would be displayed once again. The code is entered in the Click event of the cmdCalculate button and in the Change event of the TextBox (see figure below).

Figure 1.75 ‐ Form code 

1.12.4 Previewing the Form

The UserForm is now functioning and can be run with the button for Sub execution (or with the F5 key). However, this mode of execution is not particularly convenient for the user, who should access the VBA editor, identify the correct form, and then execute it. Instead, the launch of the form should be developed with a more accessible system, such as a button inside a WorkSheet, or a custom menu item, or a button on the Quick Access Toolbar. In any case, it will be necessary to write a Sub to show the UserForm. The code of the event Click on the button and the running UserForm are shown in the following figure.

Figure 1.76 ‐ Execution of the form using a button 

The Show method of the form has an optional parameter to which the constant vbModal was passed. In this way, the window of the form was made ‘modal’, which causes the impossibility of interaction with the underlying application (Excel) until the window itself is not closed. 1.12.5 Example

Below, a more detailed example is shown, in which the use of events, the UserForm, and the interaction between form and worksheet are analyzed. The objective of the small application that is exemplified is

Page 53: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

53

to simulate the data validation feature, which allows the insertion of data in a cell by drawing from a list of values. In a sheet, a list of values is prepared and the entire range is renamed as ‘list’. A range of cells is then identified and colored gray, where the values will be inputted. These cells will be used to define the area in which the list of values among which to choose will be activated. The display of the list will depend on the color of the cells.

Figure 1.77 ‐ Preparation of the spreadsheet 

First, a new UserForm must be created, which contains only one type of ListBox control.

Figure 1.78 ‐ UserForm with ListBox 

Afterwards, a write-only property (called targetRange) must be added, which will pass the cell to be modified to the UserForm. The UserForm code handles the event Initialize, in which the elements of the list, taken from the range named ‘list’, are loaded. Furthermore, the event DblClick of the ListBox is handled with the aim of writing the selected value within the Range contained in the property targetRange. Always in the DblClick event, the form with the instruction Me.Hide is closed.

Page 54: Addendum. VBA Language · 2017-02-27 · option is not disabled, when creating a module, VBA is automatically going to insert a line with the Option Explicit instruction, which forces

Computer skills handbook for economics - VBA Addendum

54

Figure 1.79 ‐ The code of the UserForm 

Finally, among the events of the WorkSheet, the event BeforeDblClick is handled, which allows the programmer to intercept any double-click on any cell and intervene before they take effect. In the event, it is checked whether the cell on which the double-click occurred is colored gray, and, if so, an instance of the UserForm is created, and the property targetRange set, passing the selected cell and showing the form.

Figure 1.80 ‐ The Worksheet_Change event code  

Figure 1.81 ‐ The example working