Docsity

Kite Runner Film Analysis, Study Guides, Projects, Research of History of film

Toggle sidebar
bg1
MINE 325 – Mine Planning and Design VBA
Compiled by: Hooman Askari Chapter 1-1
Chapter 1 - VBA
1.1 Introduction ............................................................................................................................. 1-2
1.2 Visual Basic for Applications with Excel ............................................................................... 1-2
1.2.1 The VBA Integrated Development Environment (IDE) .................................................. 1-2
1.2.2 Programming Components within Excel ......................................................................... 1-5
1.2.3 Getting Help with VBA ................................................................................................... 1-9
1.2.4 Constructing the Colorful Stats Program ....................................................................... 1-10
1.3 Beginning Programs with VBA ............................................................................................ 1-13
1.3.1 Variables, Data Types, and Constants ........................................................................... 1-13
1.3.2 Simple Input and Output with VBA .............................................................................. 1-21
1.4 Procedures and Conditions ................................................................................................... 1-23
1.4.1 VBA Procedures ............................................................................................................ 1-24
1.4.2 Manipulating Strings with VBA Functions ................................................................... 1-28
1.5 Procedures and Conditions ................................................................................................... 1-31
1.5.1 VBA Procedures ............................................................................................................ 1-31
1.6 Loops and Arrays .................................................................................................................. 1-46
1.6.1 Looping with VBA ........................................................................................................ 1-46
1.6.2 ARRAYS ....................................................................................................................... 1-51
1.6.3 Programming Formulas into Worksheet Cells ............................................................... 1-58
1.6.4 R1C1-Style References .................................................................................................. 1-60
1.7 Basic Excel Objects .............................................................................................................. 1-60
1.7.1 VBA and Object-Oriented Programming ...................................................................... 1-61
1.7.2 VBA Collection Objects ................................................................................................ 1-61
1.7.3 EXCEL OBJECTS ......................................................................................................... 1-63
1.7.4 The Worksheet Object ................................................................................................... 1-63
1.7.5 The Range Object .......................................................................................................... 1-64
1.7.6 Working with Objects .................................................................................................... 1-66
1.8 Basic File I/O & Debugging ................................................................................................. 1-68
1.8.1 Debugging ...................................................................................................................... 1-68
1.8.2 File Input and Output (I/O) ............................................................................................ 1-71
1.8.3 More on File Handling ................................................................................................... 1-79
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52

Partial preview of the text

Download Kite Runner Film Analysis and more Study Guides, Projects, Research History of film in PDF only on Docsity!

Chapter 1 - VBA

  • 1.1 Introduction 1-
  • 1.2 Visual Basic for Applications with Excel 1-
    • 1.2.1 The VBA Integrated Development Environment (IDE) 1-
    • 1.2.2 Programming Components within Excel 1-
    • 1.2.3 Getting Help with VBA 1-
    • 1.2.4 Constructing the Colorful Stats Program 1-
  • 1.3 Beginning Programs with VBA 1-
    • 1.3.1 Variables, Data Types, and Constants 1-
    • 1.3.2 Simple Input and Output with VBA 1-
  • 1.4 Procedures and Conditions 1-
    • 1.4.1 VBA Procedures 1-
    • 1.4.2 Manipulating Strings with VBA Functions 1-
  • 1.5 Procedures and Conditions 1-
    • 1.5.1 VBA Procedures 1-
  • 1.6 Loops and Arrays 1-
    • 1.6.1 Looping with VBA 1-
    • 1.6.2 ARRAYS 1-
    • 1.6.3 Programming Formulas into Worksheet Cells 1-
    • 1.6.4 R1C1-Style References 1-
  • 1.7 Basic Excel Objects 1-
    • 1.7.1 VBA and Object-Oriented Programming 1-
    • 1.7.2 VBA Collection Objects 1-
    • 1.7.3 EXCEL OBJECTS 1-
    • 1.7.4 The Worksheet Object 1-
    • 1.7.5 The Range Object 1-
    • 1.7.6 Working with Objects 1-
  • 1.8 Basic File I/O & Debugging 1-
    • 1.8.1 Debugging 1-
    • 1.8.2 File Input and Output (I/O) 1-
    • 1.8.3 More on File Handling 1-

CHAPTER 1 - (VBA)

Visual Basic for Applications

1.1 Introduction

Visual Basic for Applications (VBA for short) is a programming environment designed to work with Microsoft's Office applications (Word, Excel, Access, and PowerPoint). Components in each application (for example, worksheets or documents) are exposed as objects to the programmer to use and manipulate to a desired end. Almost anything you can do through the normal use of the Office application can also be automated through programming. VBA is a complete programming language, but you can't use it outside the application in which it is integrated. This does not mean VBA can be integrated only with Office programs. Any software vendor that decides to implement VBA can include it with their application.

VBA is relatively easy to learn, but to use it in a new application, you must first become familiar with the object model of the application. For example, the Document and Dictionary objects are specific to the Word object model, whereas the Workbook, Worksheet, and Range objects are specific to the Excel object model. As we proceed, you will see that the Excel object model is fairly extensive; however, if you are familiar with Excel, you will find that using these objects is generally straightforward.

1.2 Visual Basic for Applications with Excel

In this section we introduce you to the programming tools available in Excel. These tools include the VBA IDE (Integrated Development Environment), controls and functions available through the main Excel application, and VBA on-line help. After your introduction to the VBA programming environment, I take you through a very short and simple program that calculates some basic statistics from a sample data set. Specifically this section will cover:

 The VBA IDE and components within  Programming tools within Excel  Using VBA on-line help

1.2.1 The VBA Integrated Development Environment (IDE)

Before learning how to program in VBA, you have to learn how to use the software required for creating your projects. The VBA development software is included with each component of the Microsoft Office suite of programs, including Excel. Starting the VBA development software places you in the VBA programming environment IDE, which provides you with a number of tools for use in the development of your project.

1.2.1.1 Getting to the IDE from Excel

Before you begin creating projects with VBA you must know your way around the IDE. You can access the IDE from Excel in a couple of different ways. In Excel: select Tools, Macro, Visual Basic Editor (as shown in Figure 1.1); or use the keystroke Alt + F11.

Figure 1.3 - Accessing the Project Explorer and Properties windows.

Once the Project Explorer window is displayed, find the project that represents the workbook you opened while in Excel (probably Book1 or Book2). If the components of the workbook you opened in Excel are not displayed, click the + sign next to the Microsoft Excel Objects folder directly underneath the project name. Next, find the object labeled Sheet1, select it with your mouse and then turn your attention to the Properties window. Scroll down the Properties window until you come to the Name property (the one without the parentheses around it). Delete the text entered to the right of the Name property and enter MySheet. Figure 1.5 illustrates how to find the Name property.

Toggle back to Excel by pressing Alt+F11, or select it from the taskbar in Windows. You will note that the name of Sheet1 has now been replaced with MySheet in your Excel workbook, as shown in Figure 1.4. See how easy it is to alter the properties of a worksheet in Excel using VBA? As VBA developers, however, we will seldom, if ever, alter the properties of a workbook or worksheet at design time.

Figure 1.4 - An edited worksheet name in Excel.

Figure 1.5 - Accessing the Name property of a worksheet.

The bulk of the work affecting workbooks and worksheets will occur at run time; however, we will alter properties of ActiveX controls at design time.

HINT

Design time refers to project development and the manipulation of object properties using the VBA IDE prior to running any code. Conversely run time will refer to the manipulation of object properties using a program; thus, the properties of the object do not change until the code is executed.

Finally, I will show you one more component of the VBA IDE. If you look back at Figure 1.3 you will also see a standard code window. Windows such as these are used as containers for your program(s). This is where you type in the code for your program, so these windows are essentially text editors very similar to Notepad. You must be aware that there are pre-defined code windows for specific Excel objects, namely the workbook (for example, ThisWorkbook) and the worksheets (for example, Sheet1). The code window displayed in Figure 1.3 represents Sheet1 contained within the workbook Book1.

You will also be able to add components to your project and they will have their own code windows. I will explain how to use code windows more thoroughly as we proceed. For now, know that you can open a code window by double clicking on any object listed in the Project Explorer. You can also select the object in the Project Explorer and click on the View Code icon at the top left of the window (refer to Figure 1.5), select Code from the tools menu, or press F7 (refer to Figure 1.3). Note that you can also view the selected object in Excel by selecting the appropriate item from these same locations (refer to Figure 1.4 and Figure 1.5). There are, of course, more components to the VBA IDE, but I've shown you enough to get you started for now. As the need arises, I will introduce more tools from the IDE that will aid in the development of various projects.

1.2.2 Programming Components within Excel

Not everything of interest to the VBA programmer can be found in the VBA IDE. There are a few programming-related components that you can access from the Excel application. The components I am referring to are the Macro items found under the Tools menu, and three of the available toolbars—Visual Basic, Control Toolbox, and Forms—found in the View menu in Excel.

1.2.2.1 Macro Selection

Now that you've had an introduction to the VBA IDE, it's time to look at development tools accessed directly from Excel. To begin, take a closer look at the Macro selection from the Tools menu, shown in Figure 1.1. Notice two other items displayed in Figure 1.1 that I have not yet discussed: Macros and Record New Macro. Essentially the Record Macro tool will allow you to create a VBA program by simply selecting various tasks in Excel through the normal interface. The Macros menu item will simply display a dialog box with a list of some or all of the currently loaded VBA programs.

Figure 1.6 - The Macro dialog box displaying the available VBA programs

the VBA IDE will appear. The Properties window lists all the attributes or properties used to describe the Command Button control. Figure 1.8 shows the Properties window.

Figure 1.8 - The Properties window of the Command Button control.

In the Properties window of the Command Button control change the Caption property to Click Me and then notice how the new caption is displayed on the control. You should also change the Name property to something like cmdColorChange. The prefix cmd references the type of control (Command Button) and the rest of the name refers to the function of the program that is triggered when the button is pressed. You can also play with some of the other properties such as Font, ForeColor, BackColor, Width, and Height to change the appearance of the control. You can even display a picture within the Command Button control through the Picture property, and then select an image file from your computer.

TRICK

The Name property is an important property of any ActiveX control. The value of the Name property should be changed to something meaningful as soon as the control is added to the worksheet. Typically, an abbreviated word telling us the type of control (the cmd at the beginning of the name above denotes a Command Button) and its function in the program will work well. The Name property of an ActiveX control should be changed if you refer to it in your program. A meaningful name will help you remember it, as well as make the code more readable.

Once the appearance of your Command Button control is to your liking, select the View Code icon from the Control Toolbox, or double click on the Command Button control to access the code window. You will be taken immediately to the VBA IDE. Now it's time to make the Command Button control functional, and you can only do that by adding code to its code window. Figure 1. shows the code window for the Command Button control.

The title bar tells us the object to which this code window belongs. In this case, the code window belongs to the worksheet named Sheet1 in the workbook named Book1. This is because I placed the Command Button control on Sheet1 of Book1 in the Excel application. You may recall that I changed the name of the worksheet in Excel to MySheet, but the name of the worksheet as it will have to be referenced in code is still Sheet1. In the upper left corner of the code window is a

dropdown list box containing the names of all objects contained within the selected worksheet. The name of the Command Button control is displayed because the cursor in the editor is within an event procedure of this Command Button control.

Figure 1.9 - The VBA IDE showing the code window for the worksheet named Sheet1.

HINT

Event procedures are self-contained blocks of code that require some type of stimulus in order to run. The stimulus often comes directly from the user (for example, a mouse click), but may also result from another piece of code.

Event procedures are predefined for ActiveX controls and other Excel objects, such as workbooks and worksheets. All event procedures for the selected object are listed in the upper right corner of the code window in a dropdown list box. The Click() event is a very common event procedure that is built into most ActiveX controls. Any code placed within the predefined procedure will trigger when the user clicks once on the object—in this case, the Command Button control named cmdColorChange. The procedure is defined as listed in Figure 1.9 with the following two lines of code:

Private Sub cmdColorChange_Click() End Sub

The name of the procedure will always be the name of the object with an underscore followed by the name of the event. You cannot change the name of a predefined event procedure without changing the Name property of the object. If you do change the name of the event procedure, the code within the procedure will not run when you want it to. The keyword Sub is required and is used as the defining opening of any procedure—event-type or programmer-defined. Private is an optional keyword; The second line End Sub is always used to close a procedure. Now type the following lines of code within the Click() event procedure of the Command Button control named cmdColorChange.

Range("A1").Select Cells.Interior.ColorIndex = Int(Rnd * 56) + 1

These two lines will select cell A1 on the worksheet and set the fill color of all cells in the worksheet to one of fifty-six possible colors. This is the equivalent of a user first selecting all the cells in a worksheet and then changing the fill color from the formatting toolbar in the Excel application. The color of the cells is chosen randomly and will change with each click of the

1.2.4 Constructing the Colorful Stats Program

When starting a project, programmers often compile a list of specific requirements, then refer to this list while designing the algorithm(s) that will be followed when writing the program. The advantage you have when compiling a requirement list is that the source document can be used to build a protocol for testing the program.

Requirements of the Colorful Stats Program

The purpose for the Colorful Stats program (as it relates to this book) is to give you a demonstration of ActiveX controls, event procedures, and using VBA to interact with an Excel worksheet. The practical purpose of the Colorful Stats program is to allow a user to immediately calculate basic statistics for a selected set of data. I've defined a few specific requirements for the Colorful Stats program and they are listed as follows:

  1. The program shall calculate the following statistics for a selected data set—the number of data elements selected by the user, the minimum value, the maximum value, the sum total, the average value, and the standard deviation.
  2. The program shall use Excel worksheet formulas to calculate the statistical parameters listed in Requirement 1.
  3. The program shall write the formulas for the statistical parameters to the worksheet cells D through D7. Corresponding labels shall be written to cells C2 through C7.
  4. The program shall change the interior color of cells C2 through D7 to green.
  5. The program shall change the border color of cells C2 through D7 to red.
  6. The program shall format the font of cells C2 through D7 to Arial, 16 pt, bold, and blue.
  7. The program shall be initiated from a mouse click of a Command Button control placed on the worksheet.

Designing the Colorful Stats Program

When designing a program, I consider the user interface, program inputs and outputs, the location of the code (for example, event procedures of ActiveX controls), and the use and configuration of other programming components that I have not yet discussed. I start by making the very simple user interface for the Colorful Stats program.

Figure 1.11- The user interface for the Colorful Stats program.

The interface will use a single Command Button control placed on a worksheet to activate the program. I'm assuming that the data will be entered in column A of the worksheet (although this is not required) so I will place the Command Button control in columns C and D, close enough to the top of the worksheet so it is likely to be seen by the user when opened, but below row 7 to avoid masking the statistical values (refer to Figure 1.11). Note that I have altered the Name, Caption, and Font properties of the Command Button control.

All program inputs and outputs are from, and to, the current active worksheet. The data used in the calculation of the statistical values must come from the cells that are selected by the user. I will write the program to output cell formulas to the desired worksheet cells so that Excel calculates the statistical values. I must also output labels to the cells adjacent to the statistical values for clarity. I will also format all output as described in the requirements. Finally, the program is to be initiated from a user's click of the Command Button control, so I will enter all programming statements in the Click() event procedure of the Command Button control.

TRICK

Ideally, the Colorful Stats program would be activated from an interface independent of the worksheet that contains the data (i.e., using an ActiveX control on the worksheet containing the data is not the best solution). The program should also write the statistics to a new worksheet rather than risk overwriting data in the active worksheet. However, this requires a little more programming than I should show you right now. At this point in the book, the only tool I've shown you for running a loaded macro that may be independent of the selected worksheet is the Macro dialog box (refer to Figure 1.6). As you proceed through this book you will learn other methods for initiating macros and how to create new worksheets

Coding the Colorful Stats Program

All of the code is to be placed in the Click() event procedure of the Command Button control. The code window can be accessed via the VBA IDE by double clicking on the Command Button control while in Design Mode. You can also select the appropriate object (cmdCalculate) from the object dropdown list in the code window for the worksheet on which the ActiveX control was placed (refer to Figure 1.12).

Figure 1.12 - VBA IDE showing the code window for the worksheet

I will discuss code structures, Excel objects, and object syntax in subsequent Sections. If you are even somewhat familiar with Excel, however, you probably have a pretty good idea as to what's happening in the above code. First, the cell formulas are written to the indicated cells (D2 through D7) using the range selected by the user as the parameter for each worksheet function. Next, the statistical labels are written to the corresponding cells in the adjacent columns (C2 through C7). The last part of the program formats the font, border, and color of cells C2 through D7 before selecting cell A1. Another example of the worksheet after some arbitrary data has been entered in column A and the program run is shown in Figure 1.13. That's all there is to it! This code will run once each time the Command Button control is clicked (don't forget to exit Design Mode and select some data first).

Figure 1.13 - The Colorful Stats program after running.

1.3 Beginning Programs with VBA

Now that you know your way around the VBA IDE for Excel, it's time to introduce some basic programming concepts common to all languages. The next three sections are devoted to these basic programming structures that, although they may not be that exciting, are essential for developing VBA projects.

Specifically, in this section we look at:

 Variables and data types  Constants  Simple input and output  String functions

1.3.1 Variables, Data Types, and Constants

Since we focus on spreadsheet applications, it's only natural that I introduce variables by asking you to think about the following: what types of values can be entered into a spreadsheet cell and how

you might use them? You know that you can enter numbers and text in any spreadsheet cell in Excel. Also, you may or may not know that the format of a spreadsheet cell can be changed to one of several possibilities. For example, a number can be formatted such that the value is displayed with or without digits to the right of the decimal point. Numbers can also be formatted as currency or as a percentage (along with a few other options). Text can be displayed as entered or be automatically converted to a date or time. The content or value of a spreadsheet cell can be changed or deleted at any time.

HINT

From this point forward, the contents of a spreadsheet cell (text or numbers) in Excel will be referred to as its value.

In essence, spreadsheet cells are temporary storage containers for numbers and text that can be displayed and used in a number of different formats. This also describes a variable in any programming language. You can use variables in programs for temporary storage of data. For example, any data input by a user (possibly from a Text Box Control), can be stored in a variable and used later in the program. In the Colorful Stats project from section 1.2.4, the following line of code acts a lot like a variable.

.range("C6").Value = "Average:"

Here the text "Average" is copied to spreadsheet cell C6. I could have just as easily copied the text into a program variable first and then copied the contents of the variable to the cell C6. I didn't use an additional program variable because I wanted to save a couple of steps and because, as discussed earlier, spreadsheet cells already act a lot like variables. To accomplish this same task using a program variable, use the following:

Dim myString as String myString = "Average:" .range("C6").Value = myString

The variable myString is first declared assigned the string literal "Average:". The value of spreadsheet cell C6 is then assigned the value stored in the variable myString.

1.3.1.1 Declaring Variables

To declare a variable is to tell the computer to reserve space in memory for later use. To declare a variable use a Dim (short for Dimension) statement.

Dim myVar As Integer

The name of the variable is myVar. The name must begin with an alphabetic character and cannot exceed 255 characters or contain any spaces. You should avoid the use of punctuation marks or other unusual characters in the variable name, as many of them are not allowed; however, the underscore character is allowed and works well for separating multiple words contained within a single variable name (for example, First_Name). Avoid using reserved VBA keywords and don't repeat variable names within the same scope (discussed later in this chapter). As a convention, the variable name should be descriptive of the value it will hold. For example, if you use a variable to hold someone's first name, then a good name for that variable might be firstName or FirstName. My preference is to begin a variable name with a lowercase letter and then capitalize the first letter of any subsequent words appearing in the name. I try to keep the length to a minimum (fewer than 12 characters) only because I don't like typing long names. Of course, you can adopt your own conventions as long as they don't contradict rules established by VBA.

1.3.1.2 Object and Standard Modules

Modules refer to a related set of declarations and procedures. Each module will have a separate window in the VBA IDE and, depending on the origination of the module, it will have different behavior with regard to variable declarations. I will refer to the module window shown in Figure 1.14 as an object module because it is associated with an object (the Worksheet object in this example).

This module will automatically contain all event procedures associated with the worksheet Sheet1, and any ActiveX controls added to this worksheet. Object modules may also contain programmer- defined procedures. Each worksheet will have a separate code window as will the workbook. A standard module must be added to the project via the Insert menu of the VBA IDE, as shown in Figure 1.15. Standard modules are contained within a separate folder in the Project Explorer and may be renamed in the Properties window (see Figure 1.15). Standard modules contain variable declarations and programmer-defined procedures.

1.3.1.3 Variable Scope

Scope , in the context of variables, refers to the time when a variable is visible or available to the program. When a variable is in its scope, it can be accessed and/or manipulated. When a variable is out of scope, it is unavailable—essentially invisible to the program.

A variable declared within the code block of a procedure (such as the Click() event procedure of the Command Button control), is a procedural level variable. Procedural level variables are only available while program execution occurs within the procedure that the variable was declared. In Figure 1.14, the variable myVar4 is only visible to the program while the code in the Activate() event procedure of the worksheet executes. When program execution is triggered by the Activate() event, the variable myVar4 is dimensioned in memory. Program execution proceeds through the event procedure until reaching the End Sub line of code, after which the variable is released from memory and is no longer available. Each time the procedure executes, the variable is created and destroyed. Thus, myVar4 will not retain its value between calls to the procedure. If necessary, the Static keyword can be used to tell VBA to remember the value of the variable between calls to a procedure. Consider the following example:

Private Sub Worksheet_Activate() Static myVar4 As Integer myVar4 = myVar4 + 1 End Sub

In this procedure the variable myVar4 will increment its value by one with each call to the procedure. If you replace the Static keyword with Dim, myVar4 will never exceed a value of 1.

TRICK

Integer variables are initialized to a value of 0 at declaration.

Declaring a variable outside of a procedure with a Dim statement makes it a module level variable. The scope of a module level variable depends on the keyword used in the declaration. For example in Figure 1.14 the variables myVar, myVar2, and myVar3 are declared outside all procedures.

HINT

The area outside of any defined procedure is known as the general declarations section of a module (object or standard). This area can only be used for declarations.

These three variables are declared with the Dim, Private, and Public keywords. The Private and Public keywords are only allowed for variable declaration in the general declarations section of a module. Each of the three variables, myVar, myVar2, and myVar3 are visible to any procedure within this module. In addition, the variable myVar3 is visible to any procedure in any module of this project. Variables declared in the general declarations section of a module (object or standard) with the Public keyword are commonly referred to as global.

TRICK

When declaring a variable with the Public keyword in the general declarations section of an object module, it must be referenced in other modules of the project by first identifying the name of the object module. For example, to reference and assign a value to the variable myVar in Figure 1.14 in any other module in that project, you must use code similar to the following: Sheet1.myVar3 = 5 You do not have to reference the name of the module for variables declared with the Public keyword in the general declarations section of a standard module.

To summarize: the keywords Dim and Private have the same function in variable declarations when used in the general declarations section of any module; the Public keyword can be used to declare global variables in a standard or object module.

1.3.1.4 Data Types

Data types define the kind of value that may be stored within the memory allocated for a variable. As with spreadsheet cells, there are numerous data types; the most common are defined in Table 1.1.

Table 1.1 - Common VBA Data Types

DATA TYPE STORAGE SIZE RANGE Boolean 2 bytes True or False Integer 2 bytes -32,768 to 32, Long 4 bytes -2,147,483,648 to 2,147,483, Single (floating-point) 4 bytes -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values Double (floating-point) 8 bytes -1.79E308 to - 4.94E- for negative values; 4.94E-324 to 1.79e for positive values Date 8 bytes January 1, 100 to December 31, 9999 Object 4 bytes Any Object reference String (variable-length) 10 bytes + string length 0 to approximately 2 billion String (fixed-length) Length of string 1 to approximately 65, Variant (with numbers) 16 bytes Any numeric value up to the range of a Double Variant (with characters) 22 bytes + string length Same range as for variable-length String User-defined (using Type)

Number required by elements

The range of each element is the same as the range of its data type.

After declaring the variables num1, num2, and answer, a few mathematical operations are carried out over several lines of code. The result of each line is given as a comment within the same line of code. In the code above, the equal sign (=) does not designate equality; instead it works as an assignment operator. For example, the variable answer gets the result of adding the two variables num1 and num2.

TRICK

Although it is not required, it is a good idea to place all variable declarations for a procedure at the start of your code. With variable declarations at the beginning of your code, you will be able to find them quickly when you need to debug.

1.3.1.6 String Data Types

Variables with string data types are used to hold characters as text. The characters can be numbers, letters, or special symbols (for example, punctuation marks). Basically, just about anything you can type on your keyboard can be held within a string variable. To declare a variable with the string data type, use the String keyword. To initialize a string variable, place the string value within double quotation marks.

Dim myText As String myText = "VBA is fun"

There are two types of string variables, variable length and fixed length. The example above is that of a variable length string because myText can hold just about any length of text (see Table 1.1). Following is an example of a declaration for a fixed length string:

Dim myString As String * 8 myString = "ABCDEFGHIJKL"

In the example above, the string variable myString can hold a maximum of eight characters. You can try to initialize the variable with more characters (as was done above), but only the first eight characters in this example will be stored in the variable. The value of myString is then "ABCDEFGH". Fixed length strings are more commonly used as a part of a user-defined data type discussed in a later chapter. In most cases, you will not know the length of the string to be stored in a variable so you should use the variable length type.

1.3.1.7 Variant Data Types

Variant data types are analogous to the General category in the number format of a spreadsheet cell in the Excel application. Variables are declared as variants by using the keyword Variant, or by not specifying a data type.

Dim myVar Dim myVar2 As Variant

Variant type variables can hold any type of data except a fixed length string. Variant data types relax the restrictions on the value a particular variable can hold and thus give the programmer more flexibility; however, variant data types can also be dangerous if overused—they can slow down program execution—and programs with a large number of variant data types can be very difficult to debug. So while I don't recommend using them, I do recognize that many programmers do use variants, and the on-line help is filled with examples using variants, so I will offer a brief example here:

Dim myVar As Integer myVar = 10

myVar = "Testing"

The example above will generate a type mismatch error because an attempt is made to enter the string "Testing" into an integer variable; however, if you change the variable myVar to a variant, the code will execute and myVar will hold the string value "Testing" when all is complete. The following code will run without error.

Dim myVar myVar = 10 myVar = "Testing"

Using variants allows you to use the same variable to hold multiple data types (one at a time). The variable myVar holds the integer value 10 (albeit briefly) before being assigned the string value "Testing". You are probably starting to see the danger of using variant data types. Imagine a large program with numerous procedures and variables. Within this program are two variables of type variant that initially hold numerical values and will need to be used within the same mathematical operation before the program is finished executing. If one variable is mistakenly reinitialized with a string before the mathematical operation, an error will result and may crash the program (or at least taint the result). Debugging this program may present problems that depend on how hard it is to find the string initialization of the variant variable, and additional problems associated with the string variant. So even though it may be tempting to use variants as a way to prevent errors that crash your program (as in the example above), in actuality the use of variants make your code "loose," and may result in logic errors that are difficult to find.

HINT

Logic errors are the result of a mistake in a programming algorithm. They may or may not cause your program to crash, depending on the specific nature of the error. Trying to multiply variables of a string and integer data type would crash program execution, making the error relatively easy to find. Adding when you should have multiplied is a type of logic error that will not crash a program, but will certainly taint the result. Logic errors can be very serious because you may never find them or even know they exist.

1.3.1.8 Other Data Types

There are just a couple more data types that need to be mentioned. You will see them in action in subsequent chapters. The Boolean data type holds the value true or false. You can also represent true as a 1 and false as a 0. Boolean variables will be very useful when dealing with programming structures that use conditions. Declare and initialize a Boolean variable as follows:

Dim rollDice As Boolean rollDice = False

You can also specify variables of type date. Variables of type date are actually stored as floating point numbers with the integer portion representing a date between 1 January, 100 and 31 December 9999, and the decimal portion representing a time between 0:00:00 to 23:59:59. The date data type is mostly a convenience when you need to work with dates or times. There are a handful of VBA functions that use variables of type date that add to this convenience. You will see a couple of examples of date functions in the chapter project.

Constants

Constants allow you to assign a meaningful name to a number or string that will make your code easier to read. This is analogous to using named ranges in your spreadsheet formulas. There are numerous mathematical constants for which it makes sense to use constant data types. A constant