Monday

Lesson 4 : Variables And Data Types

In Lesson, we will learn…

Types of variable

Prompting for user input

Arrays

Interacting With Users



As Excel programming focuses on a spreadsheet application, it’s only natural that I begin the subject of 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 Bold in style or red in color. It can also be formatted as currency or as a percentage. Other than that text entered can be automatically converted to a date or time. And etc...


1) Declaring Variables

Declaring a variable is to tell the computer to reserve space in memory for later use. As a result your VBA code run much more efficiently. To declare a variable use a Dim (short for Dimension) statement.

Dim myVar As Integer

The name of the variable is myVar. As you can see myVar begin with an alphabetic character and cannot exceed 255 characters or contain any spaces. Do not use punctuation marks or other unusual characters in the variable name, as many of them are not allowed.

The use of underscore character is allowed and works well for separating multiple words contained within a single variable name (for example, Car_Type).

Do not use VBA reserved keywords and don’t repeat variable names within the same scope (discussed later in this Part). As a convention, the variable name should be descriptive of the value it will hold. For example, if you use a variable to hold a type of car, then a good name for that variable might be carType or CarType. 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. Try to keep the length to a minimum so that it is more readable.

It is advisable to follow the naming conventions as they don’t contradict rules established by VBA. To ensure that variables are always properly declared, use the Option Explicit statement as the first statement in a module before you type any procedure code. This is shown in Figure 4.1.

Fig 4.1 - Click for larger image



2) Variable Scope

A variable scope which can be declared as Private or Public 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 unacessable—essentially invisible to the program.

A variable declared within the code block of a procedure (such as the Activate() event procedure of the Worsheet), 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 4.2, the variable myVar4 is only visible to the program while the code in the Activate() event procedure of the worksheet executes.

Fig 4.2 - Click for larger image


What happen is that when program execute i.e. 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.

In this procedure the variable myVar4 will increment its value by one with each call to the procedure.

The two variables are declared with the Dim, Private, and Public keywords (see Figure 4.2). The Private and Public keywords are only allowed for variable declaration in the general declarations section of a module. The variable myVar5 are visible to any procedure within this module whereas myVar4 is only accessable from the Worksheet Activate() procedure. Variables declared in the general declarations section of a module (object or standard) with the Public keyword are commonly referred to as global.

Therefore, 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.



3) Data Types

When a data type is declared it means that you have define the kind of value that may be stored within the memory allocated for a variable. There are many data types; the most common are shown in Table 4.1 below.

For example,

Dim myInt As Integer

Here, you intend for the variable (myInt) to contain only integer values.


a) Numerical Data Types

The numerical data types listed in Table 4.1 below are integer, long, single, and double. If you declre a variable as an integer or long data type, it only can hold whole numbers or non-fractional values within the specified ranges. It cannot hold fractional or “floating point” values. For fractional or “floating point” values use a single or double data type. Pay attention to the value of the number that you declare within the variable. If the value gets too large for the data type, your program will crash.

For example, the following code will generate an overflow error because the value 60000 is outside the allowed range for an integer data type:

Dim myInt As Integer

myInt = 60000

Fig 4.3 - Click for larger image


You need be careful when mixing numerical data types because you may not get the desired result. The code below will execute without errors, but the variable answer will hold the value 11 after execution, not 10.8 as you might want as the value stored in answer is rounded to the nearest whole integer.

Dim answer As Integer

Dim num1 As Single

Dim num2 As Integer

num1 = 2.7

num2 = 4

answer = num1 * num2

To correct this eror, change the variable answer to a single data type like below.

Dim answer As Single

Dim num1 As Single

Dim num2 As Integer

num1 = 2.7

num2 = 4

answer = num1 * num2

You can perform many types of mathematical calculations within your macros. You can add, subtract, multiply, and divide variables; you can square and cube numerical variables or raise them to any desired power. See Table 4.2 for a list of the operators used for common mathematical operations in VBA.


i) Common Math Operators Used In VBA

Fig 4.4 - Click for larger image


You can be performed any mathematical operation on a numerical variable. The following are a few examples:

Dim num1 As Integer

Dim num2 As Integer

Dim answer As Integer

num1 = 4

num2 = 2

answer = num1 + num2 ‘ answer Holds 6

answer = num1 - num2 ‘ answer Holds 2

answer = num1 * num2 ‘ answer Holds 8

answer = num1 / num2 ‘ answer Holds 2

answer = num1 ^ 2 ‘ answer Holds 16

answer = 2 ^ num2 ‘ answer Holds 4

I believe, you frequently encounter this type of mathematical calculation in source code for all programming language.


b) String Data Types

To hold characters as text, the variables are declared as string data types . A string data type can hold 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 do this, use the String keyword like the example below.

Dim myName As String

myName = “Peter Anderson”

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 above). Following is an example of a declaration for a fixed length string:

You can declare a string variable to hold a fixed length as well like the code below.

Dim myString As String * 10

myString = “ABCDEFGHIJKL”

Here, the string variable myString can hold a maximum of ten characters.

When you run the code, only the first ten characters in this example will be stored in the variable i.e. “ABCDEFGHIJ”. Fixed length strings are often used as a part of a user-defined data type. In most cases, it is advisable that you use the variable length type as you will not know the length of the string to be stored in a variable.

When declaring a fixed-length string, do not use a comma in the number that specifies the string size. In fact, never use commas when entering a numeric value in VBA.


c) Dates As Data Types

What do you do if you need to calculate the numbers of days between two dates? Well. You declares the variables as date data type. If you declare a string variable to store dates, you are unable to do the calculation.

Dim Today as Date

Dim LastTime As Date = # 6/6/2007# ‘here the variable is a fix date

Dim NumDay As Integer

Today = Now

NumDay = Today – LastTime

When you run the code, NumDay will stored the numbers of days that have elapsed since he 6/6/07. Thus, the date data type gives your routines greater flexibility.

In VBA, place dates and times between two hash marks, as shown in the above examples.

Date variables display dates according to your system’s short date format, and display times according to your system’s time format (either 12- or 24-hour) so it depends on the settings for the system on which the application is running.


d) Variant Data Types

Variant data types are comparable to the General category in the number format of a spreadsheet cell in the Excel application. They are declared like this,

Dim myUnknown

Dim myUnknown2 As Variant

You can use Variant type variables to hold any type of data except a fixed length string. This way Variant data types give the programmer more flexibility; but if overused, they can be dangerous and slow down program execution. It is not advisable to use them due to reason given above. For example,

Dim myVar As Integer

myVar = 5

myVar = “Five”

The will create a type mismatch error because an attempt is made to enter the string “Five” into an integer variable. To solve this problem, you change the variable myVar to a variant, the code will execute and myVar will hold the string value “Five” when all is complete. The following code will run without error.

Dim myVar

myVar = 5

myVar = “Five”

These code enable the variable myVar to hold the integer value 5 (albeit briefly) before being assigned the string value “Five”.

With the example code above, a potential problem exist and will crash the program.

If the variable is wrongly initialize to store “Five” instead of the numerical value 5, a mathematical operation cannot be done and will taint the result of your program or even worst the program will crash.

Using the variant data type will also make your program difficult to debug. Although it may be tempting to use variants as a way to prevent errors that crash your program (like the example above), in actuality the use of variants make your code “loose,” and may cause logic errors that are difficult to find.


e) Boolean Data Type

The Boolean data type is simple. It holds the value true or false. It can also be represented true as a 1 and false as a 0. You usually use it when dealing with programming structures that use conditions. (I will explain this in another Lesson). Declare and initialize a Boolean variable as follows:

Dim condition As Boolean

condition = False


f) Constants Data Type

You may sometime have variables that do not change its value when you execute procedures. In which case it is good practice to declare it as a constant. It makes the code easier to read and it is easier to change its value later if needed. Compare this like using named ranges in your spreadsheet formulas.

Const PI As Double = 3.14159

Dim circumference As Single

Dim diameter As Single

diameter = 9.33

circumference = PI* diameter



4) Arrays

An array is a collection of variables that have a common name. For example, we refer a specific variable in the array by using the array name and an index number.

For example, you may define an array of 7 string variables to hold the number of days in a week. If you name the array NumDays, you can refer to the first element of the array as NumDays(1), the second element as NumDays(2), and so on.


a) Declaring arrays

Before you can use an array, you must declare it like a variable in VBA with a Dim or a Public statement. By default, VBA takes 0 as the lower index. You need to specify the number of elements in the array by specifying the first index number and the last index number. The following example shows how to declare the number of days in a week.

Dim NumDays(1 to 7) As Integer

When you declare an array, you can choose to specify only the upper index.

As VBA assumes that 0 is the lower index, the following code both declare the same 100 element array:

Dim MyArray(0 to 99) As Integer

Dim MyArray(99) As Integer

If you want VBA to assume that 1 is the lower index for your arrays, your need to add the following code in the Declarations section of your module:

Option Base 1

We assume the the lower index is 1 from now. The array code above, will now represent a 99 element array


b) Assigning values to elements in an array

Suppose we have an one-dimensional array called MyArray and we wish to assign the value 5 to the 3rd index slot, use the following

MyArray(3) = 5


c) Multidimensional arrays

We have look at one-dimensional arrays. Incredibly, VBA allow you to have as many as 60 dimensions. The following example declares a 50-integer array with two dimensions:

Dim MyArray(1 to 5, 1 to 5) As Integer

You can think of this array as occupying a 5-x-5 matrix. If we want to assign the value 5 to the entry in the 2nd row and 5th column of the array, use

MyArray(2, 5) = 5

In other word, the integer value 5 is stored in (row 2, column 5) of the matrix MyArray

For a three-dimensional array, think of it as a cube. Visualizing an array of more than three dimensions is more difficult. Well you don’t worry about the fourth dimension and beyond as I bet you’ll never use it.


d) Dynamic arrays

So far, we have been declaring arrays with a fixed number of elements. If you wish to declare an array without specifying its size, use

Dim MyArray() As Integer

This is how to create dynamic arrays. Notice a dynamic array has a blank set of parentheses:

To resize the array, you must use the ReDim statement to tell VBA how many elements the array has. Most of the time, the number of elements in the array is determined while your code is running. The ReDim statement can be used any number of times, to change the array’s size as often as you need.

For example if you need to resize MyArray to a 10 x 10 matrix then you

ReDim MyArray(10,10) As Integer

Now you have change the number of elements in a dynamic array. When you redimension an array by using ReDim, you clear all the values currently stored in the array elements.

I’ll discuss on arrays again in Lesson 6.



5) Simple Input and Output with VBA

You already know how to get input from the user through the use of the Value property of a spreadsheet cell. Apart from that, you can also generate output for the user through the spreadsheet. However there may be times when you want something more dynamic and dramatic way to interact with the user than using a spreadsheet cell. The most common method for gathering input from the user and sending output back is the InputBox() and MsgBox() functions.


a) Collecting User Input with InputBox()

The InputBox() function can be used to prompt and sometime to force a response from the user. What happened is that, it will sends to the screen a dialog box that must be addressed by the user before program execution continues.

Figure 4.5 below shows the dialog box.

Fig 4.5 - Click for larger image

And the code is this,

Sub GetName()
Dim MyInput

MyInput = InputBox("Enter your name")

MsgBox ("Hello ") & MyInput

End Sub

The InputBox() function example above returns the data entered by the user as a string if the OK button is clicked or the Enter key is pressed on the keyboard. If the user clicks the Cancel button, then a zero-length string is returned (“”). The syntax required for creating an InputBox()(parameters in brackets are optional). It is rare that you will need to use [, xpos] [, ypos] or [, helpfile, context]. See Excel help for details on these.

InputBox(prompt [,title] [,default] [,xpos] [,ypos] [,helpfile, context], type)

Typically, the prompt, title, and sometimes the default are used. However, it is the last argument "Type" that allows us to specify the type of data we are going to collect. These are as shown below;

Type:=0 A formula
Type:=1 A number
Type:=2 Text (a string)
Type:=4 A logical value (True or False)
Type:=8 A cell reference, as a Range object
Type:=16 An error value, such as #N/A
Type:=64 An array of values

To look at another InputBox example that return number

Sub GetAge()
Dim MyInput As Integer

MyInput = Application.InputBox(Prompt:="How old are you ? " , Title:="ENTER _

AGE: ", Type:=1)
MsgBox ("You’re ") & MyInput

End Sub

As a rule, the prompt and title must be strings and enclosed in double quotation marks. The title parameter is displayed in the title bar of the dialog box. The default parameter is displayed in the text box of the dialog box.


b) Output with MsgBox()

By using the MsgBox() function, a message box like the one shown in Figure 4.3, outputs a message to the user or ask a question that require a yes / no answer.

This is also useful as a way to inform the user about some type of problem. The syntax for the MsgBox() function is as follow…

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

Fig 4.6 - Click for larger image


You can see that I have use a string for the prompt, a vbOKOnly button and also a string title. The example below was used to generate the message box in Figure 4.3 above:

Msg = MsgBox(“How Are You”, vbOKOnly, “Message”)

The prompt must be a string or string variable and is used as the message you want the user to read. The buttons parameter requires a numeric expression (either an integer or constant) and tells VBA what buttons and/or icons are to be placed on the message box.

If you do not specify a button constant, the MsgBox() function uses the default vbOKOnly that displays only the OK button. For a complete list of button choices, look at Figure 4.4).

You can choose to display an icon (warnings or information type), a help button, and add some additional formatting with your choice of buttons.

Fig 4.7 - Click for larger image


The MsgBox() function returns an integer between 1 and 7 depending on the button selected.

Obviously this is only useful when there is more than one button. The return value should then be used to select a course of action in your program.

Don’t put too many message boxes in your program as it is extremely annoying and a disturbance to have to answer a message box when it’s not really necessary.



6) Summary

On this Part, I've discussed some important basics of programming; including variables, data types, and constants. We also look at programming modules in VBA and their effect on the scope of a variable. Also, I show to you several functions used to manipulate values of type string and date.



Lesson 3 : Excel Collection Objects And Objects

In this Lesson, you will learn about:

Objects

VBA Collection Objects

The Application Object

Workbook and Window Objects

The Worksheet Object

The Range Object


1) What is object?

It really is a pretty simple thing to understand. You can think of objects as separate computer programs with specific (and often common) functions that are available for repeated use in your programs.

Objects are dynamic in that they can be easily manipulated in code with the various parameters used to define them.

For example, consider a car. A car can be described by its size, color, and brand (among other things). For example, it might be a SUV, sports car, convertible and etc. The color, size, and brand are all adjectives that describe the car. Thus, they are all properties of the car.

A car can also perform various actions like move straight or turn. Moving and turning are action verbs that tell you what tasks the car can do. Moving and turning are methods of the car. Finally, the car is built out of other objects such as a frame, wheels, steering, and tyres.

These objects, in turn, have their own properties and methods. For example, a car wheel is of a certain diameter, is built out of aluminum or titanium alloys, and it turns or rolls. The diameter and type of material are properties of the wheel object, and to turn or roll would be two of its methods. So you see, there is sort of a hierarchy to the objects in your car and the car object itself sits at the top of the hierarchy.

I could take it further. For example, a wheel is built from a tyre, rim, and spoke objects. The tyres are built from organic polymers, and so on, and so on. The description continues until eventually you will get to the objects at the very bottom of the hierarchy.

In Excel, I bet that you’re already familiar with many of its objects. For example, there are Workbook objects, Worksheet objects, Range objects, Chart objects, and many more. These objects are the building blocks to construct a program with VBA.

The rest of this Part C, I will show you how to use a few of Excel’s objects, and in particular, some of its top-level objects.


a) VBA Collection Objects

To understand what is collection objects in VBA, just think of a collection of cars. The car objects in your car collection can be different sizes, colors, and brand, but they are all cars. So, VBA collection objects means that it is a group or collection of the same object types

For example, any Workbook object belongs to a Workbooks collection object. The Workbooks collection object contains all open Workbook objects. The Excel window shown in Figure 3.1 contains three open Workbook objects (Book1, Book2, and Book3).

Collection objects enable you to work with objects as a group rather than just working with a single object.

Fig 3.1 - Click for larger image


The hierarchy of Excel Objects

Fig 3.2 - Click for larger image


There are too many objects in Excel to cover them all. So in this Part, I’ll only explain to you the objects shown in the Figure above. My goal is to get you comfortable navigating through the object model and learning how to use the objects on your own.


b) The Application Object

At the top of the hierarchy is Application object. It represents the entirety of the Excel application. As the top-level object it is unique and thus, seldom needs to be addressed in code.

However, there are a few occasions when you must use the Application object’s qualifier in code.

For example, the Width and Height properties used to set the size of the application window must be reference explicitly in the VBA code. Other example will be the DisplayFormulaBar property used to show or hide the formula bar.

Application.Width = 800

Application.Height = 550

Application.DisplayFormulaBar = False

You need to use the Application object qualifier, most of the time, to set properties pertaining to the appearance of the Excel window, such as shown above, or the overall behavior of Excel as shown below.

Application.Calculation = xlManual

Application.EditDirectlyInCell = False

Application.DefaultFilePath = “D:\My Documents”

You need to use the Application object qualifier with the very helpful ScreenUpdating property.

Application.ScreenUpdating = False

Another one will be the WorksheetFunction property.

Range(“C3”) = Application.WorksheetFunction.Sum(Range(“B1:B10”))

However if you just need to set properties of lower-level objects, then the Application object qualifier is not needed.

ActiveCell.Formula = “=SUM(B1:B10)”


c) The Workbook and Window Objects

You may be unfamiliar with the Window object. Window objects refer to instances of windows within either the same workbook, or the application. Within the Excel application, the Windows collection object contains all Window objects currently opened; this includes all Workbook objects and copies of any Workbook objects. The Window objects are indexed according to their layering. For example, in Figure 3.1, you could retrieve Book2 with the following code:

Application.Windows(2).Activate

because Book2 is the center window in a total of three Window objects. After Book2 is retrieved and thus brought to the top layer its index would change to 1 when using the Windows collection object. This is different from accessing Book2 using the Workbooks collection object.

Let’s take a closer look at the Workbooks collection Object via an example. There are only a few properties and methods of the Workbooks collection object and their functions are straightforward. Add the following procedure to a standard module in a workbook.

Public Sub exampleWorkbooks()

Dim j As Integer

For j = 1 To 3

Workbooks.Add ‘add a new workbook

Next j

Workbooks(Workbooks.Count).Activate ‘activate book3

End Sub

In you execute this procedure by selecting exampleWorkbooks from the Macro menu in Excel, you will immediately see three new workbooks opened in Excel. After that it will activate Book3

They are relatively straightforward to use, and you have already seen a couple of them (the Add() method, Count property and the Activate() method). You may find the Open() and Close() methods and Item property useful as well. Some of these members will be addressed later, albeit with different objects. You will find that many of the collection objects share the same properties and methods. This is not unusual, but be aware that depending on the object you use, the parameters that are either available or required for these members may vary.

Consider the following VBA procedure illustrating the use of the Close() method of the Workbook object. The code can be placed in a standard or object module.

Public Sub CloseWorkbooks()

Workbooks(Workbooks.Count).Close SaveChanges:=False

Workbooks(1).Close SaveChanges:=False

End Sub

This procedure will close the first and last workbooks opened in Excel without prompting the user to save changes.

In the example above, the Close() method of the Workbook object is used, not the Close() method of the Workbooks collection object. If you want to close all workbooks simultaneously, then use the Close() method of the Workbooks collection object.

The code below will close the Workbooks collection object.

Workbooks.Close

In this case, there are no optional arguments allowed, so the user will be prompted to save the currently selected workbook.


d) The Worksheet Object

The Worksheet object falls just under the Workbook object in Excel’s object hierarchy. To investigate some of the events of the Worksheet object, the following code has been added to the SelectionChange() event procedure of Sheet1 in a workbook. (Figure 3.3)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim msgOut As String

msgOut = “The name of this worksheet is “ & Worksheets(1).name

MsgBox (msgOut)

Worksheets(2).Select

End Sub

Fig 3.3 - Click for larger image


The SelectionChange() event procedure was is found in the object module of a worksheet. The SelectionChange() event procedure is triggered whenever the user changes the current selection in the worksheet. The Target argument passed to the SelectionChange() event procedure is a range that represents the cells selected by the user. I will discuss the Range object shortly; for right now, ignore it because the current example does not use the passed argument.

The code in the SelectionChange() event procedure is straightforward. First, a string variable is created and assigned a value (“The name of this worksheet is”) that is then concatenated with the name of the worksheet obtained from the Name property of the Worksheet object. The full object path is not used to return the name of the worksheet, as this code will only be executed when the user changes the selection in the first worksheet of the Worksheets collection object (Sheet1). Therefore, the object path travels through the current Workbook object.

This is why index numbers can be used with the Worksheets property of the Workbook object without having to worry about returning the wrong sheet. After displaying the concatenated string in a message box, the Select() method of the Worksheet object is used to select the second worksheet in the Worksheets collection object.

Next, code is added to the Worksheet_Activate() event procedure of Sheet2. The Worksheet Activate() event procedure is triggered when a worksheet is first selected by the user or, in this case, by selecting the worksheet using program code (Worksheets(2).Select). The code is essentially the same as the previous example.

Private Sub Worksheet_Activate()

Dim msgOutput As String

msgOutput = “This worksheet is “ & Worksheets(2).Name

MsgBox (msgOutput)

End Sub

The Worksheet_Activate() event procedure is not triggered when a workbook is first opened, so it is not a good place for initialization routines intended to run as soon as a workbook is opened. These procedures should be placed in the Workbook_Open() event procedure.

The Sheets collection object is nearly identical to the Worksheets collection object and the two objects can often be used interchangeably (as is the case in the previous two examples). The difference between these two objects is that the Sheets collection object will also contain any chart sheets open in the active workbook. So, if you expect chart sheets to be open in the workbook of interest, you should access worksheets using the Sheets collection object; otherwise, either collection object will suffice.


i) Methods and Properties of the Worksheet

Select a sheet in the VBA Project window (Figure 3.3) and you can see 11 properties of the worksheet in the Properties window of the VBE, properties for which you can set a default value to begin with and that you can modify through the VBA procedure whenever you wish.

There are 3 properties of a worksheet that you will use frequently:

· the name (name within parentheses),

· the name (without parentheses) like the caption appearing on the sheet's tab in Excel

· the visible property

To change the caption you can either do it in the property window of the VBE or in Excel by right clicking on the tab then selecting "Rename". Programmatically you can change the caption of a sheet with the following code:

Worksheets("Sheet1").Name= "Good"

The "Visible" property can take 3 different values. The first two are True or False meaning the a certain sheet is or is nor visible that it is either hidden or not.

Worksheets("Good ").Visible= True
Worksheets("Good 1").Visible= False

Remember that formulas in cells are calculated even if the sheet is hidden but before you can do anything programmatically on the sheet you must unhide it:

Worksheets("Good ").Visible = True
Worksheets("Good "). Select

Range(“A1”).Value = 10

The third value that the property "Visible" can take is very interesting. A sheet can be very hidden " Worksheets("Good ").Visible = xlVeryHidden". In this state not only the sheet is hidden but you can't see its name when in Excel you go to "Format/Sheets/Unhide". The value xlVeryHidden can only be changed programmatically. That means that only users that have access to the VBA code can unhide this sheet. If your code is protected by a password only users with the password can access the code and modify the "xlVeryHidden" value. You can use this value of the property "Visible" to hide confidential information like credit card details and personal info or to hide parameters that you don't want modified by the user.

Worksheets("Good ").Visible = True
Worksheets("Good "). Select

Range(“A1”).Value = 10

And hide it again…

Worksheets("Good ").Visible = xlVeryHidden

Remember also that formulas on other sheets referring to cells of a hidden or very hidden sheet work even if the sheet is hidden or very hidden.

You might want to delete sheets. Here is the code to do so:

Worksheets("Good ").Delete

You might also want to add one sheet. If you use the following code VBA will add a new sheet before the active worksheet.

WorkSheets.Add

If you want to be more precise as to the where and the how many you will use either of the following procedures:

Inserting one sheet after the sheet which caption is "Good" the code is like this

Sub exercise2()
Sheets.Add before:=Sheets("Good")
End Sub

Inserting three sheets after the sheet which caption is "Good":

Sub exercise2()
Sheets.Add after:=Sheets("Good "), Count:=3
End Sub

Inserting one sheet at the beginning of the workbook. Notice the absence of double quotes when using the rank of the sheet:

Sub exercise2 ()
Sheets.Add after:=Sheets(1)
End Sub

And if you want to add a new sheet at the end of the workbook you need to count the sheets with Sheets.Count and use this value as the rank of the sheet after which you want to add the new sheet:

Sub exercise2 ()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub


e) The Range Object

You can use the Range object represents a group of one or more contiguous cells in an Excel worksheet. It is extremely useful, as it allows us to manipulate the properties of an individual cell or collection of cells in a worksheet. You will probably find yourself using the Range object in every program you write using VBA for the Excel application.

Consider the following code examples that use properties of the Range object.

Range(“B1”).Value=”Column B”

Range(“B1:G1”).Columns.AutoFit

Range(“B1:C1”, “E1:F1”).Font.Bold = True

The Range object is one example of a VBA collection object that does not use the plural form of an existing object for its name. The Range object is a collection object in the sense that it represents a collection of cells in a worksheet, even if the collection represents only one cell.

First, note that a long object path is omitted from the examples above; thus, these lines of code will operate on the currently selected worksheet. The first line inserts the text Column A into cell B1 by setting its Value property. The Range property was used to return a Range object representing a single cell (B1) in this example. You have already seen several examples of the Value property previously. Although the Value property exists for several objects, it is the Range object for which it is most commonly used.

When you use the AutoFit() method of the Range object to adjust the width of columns B through G such that the contents of row 1 will just fit into their corresponding cells without overlapping into adjacent columns. This is equivalent to the user selecting Format, Column, AutoFit Selection from the Excel application menu.

The third and last example demonstrates setting the Bold property of the Font object to true for two distinct ranges in the active worksheet. The two ranges are B1:C1 and E1:F1. You are only allowed to return a maximum of two ranges, so adding a third range to the arguments in the parentheses would generate a run-time error.

The examples above demonstrate just a couple of formatting methods and properties belonging to the Range object (AutoFit(), Columns, and Font). If you are a regular user of Excel, then you have probably surmised that there are numerous other properties and methods related to formatting spreadsheet cells.

Recording a macro is a quick and easy way to generate the code you need without having to search the documentation for descriptions of the desired objects, properties and methods. After you have recorded the macro in a separate module, you can clean up the recorded code and then cut and paste into your program as needed.

You may have noticed that the range arguments used in the examples above (B1, B1:G1, etc.) are of the same form used with cell references in the Excel application. This identical syntax is highly convenient because of its familiarity.


i) Using the Cells Property

The Excel Object Model does not contain a Cells object. In order to reference a specific cells you use either the Cells property or the Range property. The Cells property returns a Range object containing all (no indices used) or one (row and column indices are specified) of the cells in the active worksheet. When returning all of the cells in a worksheet, you should only use the Cells property with the Application and Worksheet objects. For example,

Cells(2,2).Select

Here you’ve selected the cell B2 in the worksheet.

To return a single cell from a Worksheet object you must specify an index. The index can be a single value beginning with the left uppermost cell in the worksheet (for example, Cells(5) returns cell E1) or the index can contain a reference to the row and column index (recommended) as shown below.

Cells(1, 4).Value=5

Cells(1, ”D”).Value =5

This is the familiar notation used throughout this book. Both lines of code will enter the value 5 into cell D1 of the active worksheet. You can either use numerical or string values for the column reference. You should note that the column reference comes second in both examples and is separated from the row reference by a comma. I recommend using the second example above, as there is no ambiguity in the cell reference—though on occasion it’s convenient to use a numerical reference for the column index. Now consider some examples using the Cells property of the Range object.

Range(“C5:E7”).Cells(2, 2).Value = 100

Range(“C5:E7”).Cells(2, “A”).Value = 100

This code may confuse you because they appear to be trying to return two different ranges within the same line of code; however, that is not the case, but you can use these examples to more carefully illustrate how the Cells property works.

Before reading on, guess in what worksheet cell each of these lines places the value 100. If you guessed cells B2 and A2, respectively, you’re wrong. Instead, the value 100 is entered in cells D6 and A6, respectively, when using the above lines of code. Why? It’s because the Cells property uses references relative to the selected range. Without the reference to the Range object in each statement (Range(“C5:E7”)), the current range is the entire worksheet, thus Cells(2,2) returns the range B2; however, when the selected range is C5:E7, Cells(2,2) will return the second row from this range (row 6) and the second column (column D). Using a string in the Cells property to index the column forces the selection of that column regardless of the range selected. The row index is still relative; therefore, the second example above returns the range A6.


ii) Method and Properties Range (Cells, Rows and Columns)

Here is some code to move around and work with the Range object.

Selection and ActiveCell

The object Selection comprises what is selected. It can be a single cell, many cells, a column, a row or many of these.

For example:

Range("A1:A50").Select
Selection.ClearContents

will remove the content (values or formulas) of the cells A1 to A50..

The ActiveCell is a very important concept that you will need to remember as you start developing more complex procedures.

Range, Select

To select a cell you will write:
Range("B1").Select

To select a set of contiguous cells you will write:
Range("A1:A5").Select

To select a set of non contiguous cells you will write:
Range("C1,E5,F6").Select

Columns, Rows, Select, EntireRow, EntireColumn

To select a column you will write:
Columns("A").Select

To select a set of contiguous columns you will write:
Columns("A:B").Select

To select a set of non contiguous columns you will write:
Range("A:A,C:C,F:F").Select

To select a row you will write:
Rows("1").Select

You can also select the column or the row with this:
ActiveCell.EntireColumn.Select
ActiveCell.EntireRow.Select
Range("B1").EntireColumn.Select
Range("B1").EntireRow.Select

If more than one cell is selected the following code will select all rows and columns covered by the selection:
Selection.EntireColumn.Select
Selection.EntireRow.Select

Cells, CurrentRegion

To select all cells then
Cells.Select

Offset

The commonly use Offset method allows you to move right, left, up and down.

For example if you want to move 2 cells to the right, you will write:
Activecell.Offset(0,2).Select

If you want to move 2 cells to the left,
Activecell.Offset(0,-2).Select

If you want to move two cells down:
Activecell.Offset(2,0).Select

If you want to move two cells up:
Activecell.Offset(-2,0).Select

If you want to select one cell and three more down:
Range(Activecell,Activecell.Offset(3,0)).Select
Range("A1",Range("A1").Offset(3,0)).Select

Column, Row, Columns, Rows, Count

For the following lines of code notice that you need to send the result into a variable.

myvar = Activecell.Column 'will return the column number

myvar = Activecell.Row 'will return the row number

myvar = Selection.Columns.Count 'will return the number of columns in the selection

myvar = Selection.Rows.Count will return the number of rows in the selection

myvar = Selection.CurrentRegion.Rows.Count 'will return the number of rows in the current region of the selection

Value

When you want to enter a numerical value in a cell you will write:
Range("C1").Select
Selection.Value = 56

Note that you don't need to select a cell to enter a value in it, from anywhere on the sheet you can write:
Range("C1").Value = 56

You can even change the value of cells on another sheet with:
Worksheets("Good").Range("C1").Value = 56

You can also enter the same value in many cells with:
Range("A1:B33").Value = 56

If you want to enter a text in a cell you need to use the double quotes like:
Range("C1").Value = "Nancy"

If you want to enter a text within double quotes in a cell you need to triple the double quotes like:
Range("C1").Value = """Peter"""

Formula

To enter a formula in a cell you enter this code
Range("A1").Select
Selection.Formula = "=B8+C8"

Note the two equal signs (=) including the one within the double quotes like if you were entering it manually. Again you don't need to select a cell to enter a formula in it, from anywhere on the sheet you can write:

Range("A1").Formula = "=B8+C8"

If you write the following:
Range("A1:A8").Formula = "=C8+C9"

The formula in A1 will be =C8+C9, the formula in A2 will be =C9+C10 and so on. If you want to have the exact formula =C8+C9 in all the cells, you need to write:

Range("A1:A8").Formula = "=$C$8+$C$9"



2) Simplifying object references

Application.Workbooks(“Book1.xls”).Worksheets(1).Range(“A1”).Value

You don’t need to fully qualify every object reference you make, like the above. Excel provides you with some shortcuts that can improve the readability (and save you some typing). For starters, the Application object is always assumed. Omitting the Application object reference shortens the example from the previous section to

Workbooks(“Book1.xls”).Worksheets(1).Range(“A1”).Value

If Book1.xls is the active workbook, you can omit that reference too. This bring us down to

Worksheets(1).Range(“A1”).Value

Futher, if the first worksheet is the currently active worksheet, then Excel will assume that reference and allow us to just type

Range(“A1”).Value


a) Working with Objects

You learn in numerous examples of objects on how to set their properties and invoke their methods and events. There are a few more tools that can be very useful when working with objects i.e.the With/End With code structure.

This code structure works well to simplify code; and the object data type, which allows you to reference existing objects or even create new objects. We’ll look at an example below.


The With/End With Structure

I always recommend the use of this structure because it makes your programs more readable. Also you will often see the With/End With structure in recorded macros. Consider the following code:

Range(“A1:D1”).Select

Range(“A1:D1”).Value = 100

With Selection.Font

.Bold = True

.Name = “Times New Roman”

.Size = 16

End With

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

End With

When executed, this code selects the range A1:D1 of the active worksheet using the Select() method of the Range object.

In this case, the Selection property of the Window object is used to return a Range object from which the Font property returns a Font object associated with the selected range. The statement could have just as easily been written without the Select() method and Selection property and entered using the Range property to return the desired Range object (for example, With Range(“A1:D1”).Font).

Once inside the structure, any property of the object can be set without having to qualify the object in each line of code. Subordinate objects and their properties can also be accessed. Each line within the structure must begin with the dot operator followed by the property or object name, then the method or assignment.

After all desired properties and/or methods have been invoked for the given object, the structure closes with End With.

You will note that a second With/End With structure is used to set the horizontal and vertical alignment of the selected range. This way your code look clean and readable.

The With/End With structure is straightforward and particularly useful when a large number of properties or methods of one object are to be addressed sequentially in a program.



3) The Object Data Type

Lastly, the subject on Excel objects would not be complete without a discussion of the object data type. If you find multiple instances of the same object in your program, then you can use an object variable to handle the reference rather than constantly retyping the qualifiers. Also, variables can be assigned meaningful names, making the program easier to interpret. Object variable are similar to other VBA data types in that they must be declared in code. For example,

Dim myObject as Object

declares an object variable named myObject; however, assigning a value to an object variable differs from assignments to more common data types. The Set keyword must be used to assign an object reference to a variable.

Set myObject = Range(“B1:C15”)

This will assign the Range object representing cells A1 through A15 to the variable myObject. Properties of the object can then be initialized in the usual way.

myObject.Font.Bold = False

This sets the values in cells B1 through C15 to be displayed in bold-face type. Or, using the Range object, the above example can be rewritten more efficiently as follow

Dim myRange as Excel.Range

Set myRange=Range(“B1:C15”)

myRange.Font.Bold = True

To be more efficient you can also include the library (Excel) in your declaration. Here the Range object type will be referenced at compile time and VBA will have no trouble working out references to the properties and methods of the object, as the type of object and the library to which it belongs have been explicitly declared. You will see more examples of object variable types in the as we go along.



4) Summary

When you do Excel programming, its all about manupulating the Excel objects. There are so many things we can do with these object and you can be as creative as you want. Like the neural network based forecasting addin develop by my company.




Lesson 2 : Making A Macro Do Simple Task


In this Lesson, you’ll learn to…

record a macro

automate a task


1) Recording Your First Macro

You can use Excel build-in macro recorder to translates your actions into VBA macro commands. After you recorded the macro, you will be able to see the VBA code in the Module window. Before you record a macro, plan the steps and commands that you want the macro to perform. Every action that you take during the recording of the macro will be recorded - including the correction that you made.

In this example, we will record a macro that sets the cell background color to light yellow. To record the macro, follow the steps below;

a) Select a Range on a Worksheet and then select Record New Macro...under Tools...Macro (shown in Fig 2.1)

Fig 2.1 - Click for larger image


b) In the Record Macro dialog box, type "SetBackgroundColor" in the Macro Name textbox to set the macro name. Leave all other option by default then click the Ok button. This will start the macro recording. (see Fig 2.2)

Fig 2.2 - Click for larger image


c) In the Background Color Panel, select the Light Yellow color box. This action will set the background of the current selected Range in light yellow color.

Fig 2.3 - Click for larger image


d) To stop the macro recording, click the Stop button (the navy blue rectangle) on the Macro Recorder toolbar.

Fig 2.4 - Click for larger image


You have recorded a macro that set cell background to light yellow.
Now the recorded macro is ready for use. Before we run the macro, let's look into the syntax.

* Press [Alt] and [F11] at the same time to load the Visual Basic Editor. The Visual Basic Editor comes up.
* Expand the Modules folder in the Project Explorer by clicking on the plus (+) sign.
* Double click the Module1 folder to see the sub routine (macro). (Fig 2.5)

(Remember? You learn to do this in Lesson 1)

Fig 2.5 - Click for larger image


As the figure shows, the name of the sub routine is "SetBackgroundColor". The color index for the light yellow is 36. The background pattern is solid.

(Note: The characters in Green with apostrophe in front are just comments and will be ignored by VBA. You can always insert comments in your code by doing so.)



2) Run the Recorded Macro


We can run the macro within the Visual Basic Editor. This time we will run the recorded macro in the worksheet.

a) On any worksheet, select a range. (Fig 2.6)

Fig 2.6 - Click for larger image


b) Run the recorded macro by select Tools...Macro...Macros... or press [Alt] and [F8] at the same time. (Fig 2.7)

Fig 2.7 - Click for larger image


c) The Macro dialog box displayed (Fig 2.8). Since there is only one macro in the module, by default the only macro, SetBackgroundColor is selected. Click the Run button to run the macro.

Fig 2.8 - Click for larger image


d) Cells will now have light yellow background color.

Fig 2.9 - Click for larger image


e) You can edit the macro. In this example we change the :ColorIndex = 3. When we run the macro, range selected will now have red background color.

f) We can add a macro to a toolbar as well. (i) we create a command button by selecting View – Toolbars – Control Toolbox . Figure 2.10 display the control Toolbox. Select the Command Button and embed it on the worksheet. (ii) After that right click on the button and and edit. Type Click Me. (Fig 2.11)

Fig 2.10 - Click for larger image

Fig 2.11 - Click for larger image


g) Right click on the command button and select view Code and this will bring up the VBE. In the Code window, type Module1.SetBackgroundColor

Fig 2.12 - Click for larger image


h) Go back to the worksheet and click on exit design mode (the highlighted icon shown in Fig 2.13). This will add the macro to the commandbutton. When you click on the button, it will run the macro “Module1.SetBackgroundColor”

Fig 2.13 - Click for larger image


You can use the macro execute a repetitive by adding a line of code as …ActiveCell.Offset(1,0).Select… shown below.

Fig 2.14 - Click for larger image

When you click on the button, it will go down a row and set the cell color to light yellow.


3) Summary

This is how you record a macro, assign a macro to a command button and execute a repetitive task.

Saturday

Lesson 1 : Introduction To Excel VBA


In this Lesson, you will learn …

why use Excel VBA

the Visual Basic Editor







The purpose of this course is to show Excel users how to use the Visual Basic For Application programming language that comes free with MS Excel. This tool will help you to significantly enhance the power of the world’s most popular spreadsheet. Using VBA, however, involves programming, simple but very powerful.

Nowadays computer programming has become much easier, and even so-called normal people now engage in this activity. Programming simply means developing instructions that the computer automatically carries out.

Excel programming means that you can instruct Excel to automatically do things that you normally do manually — saving you lots of time resources.

Since you’re reading this, it’s a safe bet that you need to become an Excel programmer. This could be something you initiated or you want to make yourself more marketable. In this online course, we will learn about Excel programming so that by the time you finish this course, you can honestly say, “Oh, Excel programming is so easy.”

At the end of this course, we will also learn develop a few simple applications with Excel VBA.

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) What is Visual Basic Editor?

You have use workbooks, formulas, charts, and other Excel goodies most of the time. Now it’s time to expand your horizons and explore an entirely new aspect of Excel: the Visual Basic Editor (VBE). In this chapter, you find out how to work with the VBE, and get down to the task of writing some VBA code.

The Visual Basic Editor is a separate application where you write and edit your VBA macros. It works seamlessly with Excel. You can activate the VBE by pressing Alt+F11 when Excel is active or by using the Tool-Macro-Visual Basic Editor command.(Fig-1.1)

To return to Excel, press Alt+F11 again.


(Fig 1.1- click for larger image)

(a) Menu Bar

Just like any other program menu bar that you have used, the VBE menu bar contains various commands and components. You can use this commands and components in the VBE to do things. Many of the menu commands have shortcut keys associated with them.


Fig 1.2 - Click for larger image

Figure 1.2 is the VBE program window. There are a few components on this window.


(b) Project Explorer


Fig 1.3 - Click for larger image


The Project Explorer window displays a tree diagram that shows every workbook currently open in Excel (including add-ins and hidden workbooks). When you’re working in the VBE, each Excel workbook and add-in that’s open is a project. You can think of a project as a collection of objects arranged as an outline. Click on the plus sign (+) at the left of the project’s name in the Project Explorer window to expand a project.


(c) Code Window

The VBA code is contains in the Code window (Figure 1.4, sometimes known as a Module window). Every object in a project has an associated Code window. Double-click the object in the Project Explorer window to bring up the Code Window. For example, to view the Code window for the Sheet1 object, double-click Sheet1 in the Project Explorer window. Unless you’ve added some VBA code, the Code window will be empty.


Fig 1.4 - Click for larger image


(d) Object Browser

The VBE includes another tool, known as the Object Browser (Figure 1.5). This tool allows you browse through the objects available to you. To access the Object Browser, press F2 when the VBE is active (or choose View ➪ Object Browser). You see a window like the one shown in Figure 1.5.

The drop-down list at the top contains a list of all currently available object libraries. Figure 1.5 shows All Libraries. If you want to browse through Excel’s objects, select Excel from the drop-down list.


Fig 1.5 - Click for larger image



(e) Properties Window


Fig 1.6 - Click for larger image


Figure 1.6 show the Properties window of the CommandButton1.For example when you change the Caption property to of CommandButton1 to “Click Me” and then notice how the new caption is displayed on the control. You can also play with some of the other properties such as Font, Height, BackColor, Width, and Height to change the appearance of CommandButton1.



2) Summary:

I hope that in this lesson, you did get a basic introduction to the VBA programming environment. So, you’ve learn how to access the VBA IDE and how to view and use some of its major components.