You are on page 1of 13

Data Type Summary

The following table shows the supported data types, including storage sizes and ranges.

Data type

Storage size

Range

Byte

1

byte

  • 0 to 255

 

Boolean

2

bytes

True or False

 

Integer

2

bytes

-32,768 to 32,767

Long

4

bytes

-2,147,483,648 to 2,147,483,647

(long integer)

Single

 

-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for

(single-precision floating-

4

bytes

point)

 

positive values

Double

 

-1.79769313486231E308 to

(double-precision

8

bytes

-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to

floating-point)

 

1.79769313486232E308 for positive values

Currency

8

bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807

(scaled integer)

   

+/-79,228,162,514,264,337,593,543,950,335 with no decimal point;

 

Decimal

 

14

bytes

+/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is

   

+/-0.0000000000000000000000000001

Date

8

bytes

January 1, 100 to December 31, 9999

Object

4

bytes

Any Object reference

String

 

10

bytes + string

  • 0 to approximately 2 billion

(variable-length)

length

String

Length of string

  • 1 to approximately 65,400

(fixed-length)

Variant

   

(with numbers)

 

16

bytes

Any numeric value up to the range of a Double

Variant

 

22

bytes + string

Same range as for variable-length String

(with characters)

length

User-defined

Number required by

 

(using Type)

elements

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

Note

Note

Arrays of any data type require 20 bytes of memory plus 4 bytes for each array dimension plus the number of bytes occupied by the data itself. The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element. For example, the data in a single-dimension array consisting of 4 Integer data elements of 2 bytes each occupies 8 bytes. The 8 bytes required for the data plus the 24 bytes of overhead brings the total memory requirement for the array to 32 bytes.

A Variant containing an array requires 12 bytes more than the array alone.

Note

Note

Use the StrConv function to convert one type of string data to another.

Boolean Data Type

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.Boolean variables display as either

True
True
or False
or
False

(when Print is used) or

#TRUE#
#TRUE#
or #FALSE#
or
#FALSE#

(when Write # is used). Use the keywords True and False to assign one of the two states to Boolean variables.

When other numeric types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to other data types, False becomes 0 and True becomes

-1.

Integer Data Type

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767. The type-declaration character for Integer is the percent sign (%).

You can also use Integer variables to represent enumerated values. An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used. Enumerated values provide a convenient way to select among a known number of choices, for example, black = 0, white = 1, and so on. It is good programming practice to define constants using the Const statement for each enumerated value.

Double Data Type

Double (double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floating-point numbers ranging in value from -1.79769313486231E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The type-declaration character for Double is the number sign (#).

Date Data Type

Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Date literals must be enclosed within number signs (#), for example,

#January 1, 1993#
#January 1, 1993#
or #1 Jan 93#
or
#1 Jan 93#

.

Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.

When other numeric types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is 0.5. Negative whole numbers represent dates before 30 December 1899.

Long Data Type

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for Long is the ampersand (&).

Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects. Using the Set statement, a variable declared as an Object can have any object reference assigned to it.

Although a variable declared with Object type is flexible enough to contain a reference to any object, binding to the object referenced by that variable is always late (run-time binding). To force early binding (compile-time binding), assign the object reference to a variable declared with a specific class name.

String Data Type

There are two kinds of strings: variable-length and fixed-length strings.

A variable-length string can contain up to approximately 2 billion (2^31) characters.

A fixed-length string can contain 1 to approximately 64K (2^16) characters.

Note

Note

A Public fixed-length string can't be used in a class module.

The codes for String characters range from 0–255. The first 128 characters (0–127) of the character set correspond to the letters and symbols on a standard U.S. keyboard. These first 128 characters are the same as those defined by the ASCII character set. The second 128 characters (128–255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions. The type-declaration character for String is the dollar sign ($).

User-Defined Data Type

Any data type you define using the Type statement. User-defined data types can contain one or more elements of a data type, an array, or a previously defined user-defined type. For example:

Type MyType MyName As String MyBirthDate As Date MySex As Integer End Type

' String variable stores a name. ' Date variable stores a birthdate. ' Integer variable stores sex (0 for ' female, 1 for male).

Single Data Type

Single (single-precision floating-point) variables are stored as IEEE 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values. The type-declaration character for Single is the exclamation point (!).

Variant Data Type

The Variant data type is the data type for all variables that are not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static). The Variant data type has no type- declaration character.

A Variant is a special data type that can contain any kind of data except fixed-length String data. (Variant types now support user-defined types.) A Variant can also contain the special values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated using the VarType function or TypeName function.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. Generally, numeric Variant data is maintained in its original data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as an Integer. However, if an arithmetic operation is performed on a Variant containing a Byte, an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. A Byte is promoted to an Integer, an Integer is promoted to a Long, and a Long and a Single are promoted to a Double. An error occurs when Variant variables containing Currency, Decimal, and Double values exceed their respective ranges.

You can use the Variant data type in place of any data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context. For example:

Dim MyVar As Variant MyVar = 98052
Dim MyVar As Variant
MyVar = 98052

In the preceding example,

98052
98052

. Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers. If you use the + operator to add

MyVar
MyVar

to another Variant containing a number or to a variable of a numeric type, the result is an arithmetic sum.

The value Empty denotes a Variant variable that hasn't been initialized (assigned an initial value). A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string ("") if it is used in a string context.

Don't confuse Empty with Null.Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows you, or the application itself, to take some alternative action based on the error value. Error values are created by converting real numbers to error values using the CVErr function.

Excel Developer Reference

How to: Create a Workbook

To create a workbook in Visual Basic, use the Add method. The following procedure creates a workbook. Microsoft Excel automatically names the workbook BookN, where N is the next available number. The new workbook becomes the active workbook.

Sub AddOne() Workbooks.Add End Sub
Sub AddOne()
Workbooks.Add
End Sub

A better way to create a workbook is to assign it to an object variable. In the following example, the Workbook object returned by the Add method is assigned to an object variable, newBook. Next,

several properties of newBook are set. You can easily control the new workbook by using the object variable.

Sub AddNew() Set NewBook = Workbooks.Add With NewBook .Title = "All Sales" .Subject = "Sales" .SaveAs Filename:="Allsales.xls" End With End Sub

Excel Developer Reference

How to: Refer to More Than One Sheet

Use the Array function to identify a group of sheets. The following example selects three sheets in the active workbook.

Sub Several() Worksheets(Array("Sheet1", "Sheet2", "Sheet4")).Select End Sub

Excel Developer Reference

How to: Refer to Sheets by Index Number

An index number is a sequential number assigned to a sheet, based on the position of its sheet tab (counting from the left) among sheets of the same type. The following procedure uses the Worksheets property to activate worksheet one in the active workbook.

Sub FirstOne() Worksheets(1).Activate End Sub
Sub FirstOne()
Worksheets(1).Activate
End Sub

If you want to work with all types of sheets (worksheets, charts, modules, and dialog sheets), use the Sheets property. The following procedure activates sheet four in the workbook.

 

Sub FourthOne()

Sheets(4).Activate

End Sub

Note

Note

The index order can change if you move, add, or delete sheets.

Excel Developer Reference

How to: Refer to Sheets by Name

You can identify sheets by name using the Worksheets and Charts properties. The following statements activate various sheets in the active workbook.

Worksheets("Sheet1").Activate

Charts("Chart1").Activate

DialogSheets("Dialog1").Activate

You can use the Sheets property to return a worksheet, chart, module, or dialog sheet; the Sheets collection contains all of these. The following example activates the sheet named "Chart1" in the active workbook.

 

Sub ActivateChart()

Sheets("Chart1").Activate

End Sub

Note

Note

Charts embedded in a worksheet are members of the ChartObjects collection, whereas charts that exist on their own sheets belong to the Charts collection.

Excel Developer Reference

How to: Reference Cells and Ranges

A common task when using Visual Basic is to specify a cell or range of cells and then do something with it, such as enter a formula or change the format. You can usually do this in one statement that identifies the range and also changes a property or applies a method.

A Range object in Visual Basic can be either a single cell or a range of cells. The following topics show the most common ways to identify and work with Range objects.

Some ways to reference cells

How to: Refer to All the Cells on the Worksheet

When you apply the Cells property to a worksheet without specifying an index number, the method returns a Range object that represents all the cells on the worksheet. The following Sub procedure clears the contents from all the cells on Sheet1 in the active workbook.

Sub ClearSheet()

Worksheets("Sheet1").Cells.ClearContents

End Sub

How to: Refer to Cells and Ranges by Using A1 Notation

You can refer to a cell or range of cells in the A1 reference style by using the Range property. The following subroutine changes the format of cells A1:D5 to bold.

Sub FormatRange() Workbooks("Book1").Sheets("Sheet1").Range("A1:D5") _ .Font.Bold = True

End Sub

The following table illustrates some A1-style references using the Range property.

Reference

Meaning

Range("A1")

Cell A1

Range("A1:B5")

Cells A1 through B5

Range("C5:D9,G9:H16")

A multiple-area selection

Range("A:A")

Column A

Range("1:1")

Row 1

Range("A:C")

Columns A through C

Range("1:5")

Rows 1 through 5

Range("1:1,3:3,8:8")

Rows 1, 3, and 8

Range("A:A,C:C,F:F")

Columns A, C, and F

Excel Developer Reference

How to: Refer to Rows and Columns

Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.

Sub RowBold() Worksheets("Sheet1").Rows(1).Font.Bold = True End Sub

The following table illustrates some row and column references using the Rows and Columns properties.

Reference

Meaning

Rows(1)

Row one

Rows

All the rows on the worksheet

Columns(1)

Column one

Columns("A")

Column one

Columns

All the columns on the worksheet

To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns property. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.

Sub SeveralRows()

Worksheets("Sheet1").Activate

Dim myUnion As Range Set myUnion = Union(Rows(1), Rows(3), Rows(5)) myUnion.Font.Bold = True End Sub

Excel Developer Reference

How to: Refer to Cells by Using Index Numbers

You can use the Cells property to refer to a single cell by using row and column index numbers. This property returns a Range object that represents a single cell. In the following example, Cells(6,1) returns cell A6 on Sheet1. The Value property is then set to 10.

Sub EnterValue() Worksheets("Sheet1").Cells(6, 1).Value = 10 End Sub

The Cells property works well for looping through a range of cells, because you can substitute variables for the index numbers, as shown in the following example.

Sub CycleThrough() Dim Counter As Integer For Counter = 1 To 20 Worksheets("Sheet1").Cells(Counter, 3).Value = Counter Next Counter End Sub

Note

Note

If you want to change the properties of (or apply a method to) a range of cells all at once, use the Range property. For more information, see Refer to Cells and Ranges by Using A1 Notation.

Excel Developer Reference

How to: Refer to Cells by Using Shortcut Notation

You can use either the A1 reference style or a named range within brackets as a shortcut for the Range property. You do not have to type the word "Range" or use quotation marks, as shown in the following examples.

Sub ClearRange()

Worksheets("Sheet1").[A1:B5].ClearContents

End Sub

Sub SetValue() [MyRange].Value = 30 End Sub

How to: Refer to Cells Relative to Other Cells

A common way to work with a cell relative to another cell is to use the Offset property. In the following example, the contents of the cell that is one row down and three columns over from the active cell on the active worksheet are formatted as double-underlined.

Sub Underline() ActiveCell.Offset(1, 3).Font.Underline = xlDouble End Sub

Note

Note

You can record macros that use the Offset property instead of absolute references. On the Tools menu, point to Macro, click Record New Macro, click OK, and then click the Relative Reference button on the Record Macro toolbar.

To loop through a range of cells, use a variable with the Cells property in a loop. The following example fills the first 20 cells in the third column with values between 5 and 100, incremented by 5. The variable counter is used as the row index for the Cells property.

Sub CycleThrough() Dim counter As Integer For counter = 1 To 20 Worksheets("Sheet1").Cells(counter, 3).Value = counter * 5 Next counter End Sub

Excel Developer Reference

How to: Refer to Cells by Using a Range Object

If you set an object variable to a Range object, you can easily manipulate the range by using the variable name.

The following procedure creates the object variable myRange and then assigns the variable to range A1:D5 on Sheet1 in the active workbook. Subsequent statements modify properties of the range by substituting the variable name for the Range object.

Sub Random() Dim myRange As Range Set myRange = Worksheets("Sheet1").Range("A1:D5") myRange.Formula = "=RAND()" myRange.Font.Bold = True End Sub

Excel Developer Reference

How to: Refer to Named Ranges

Ranges are easier to identify by name than by A1 notation. To name a selected range, click the name box at the left end of the formula bar, type a name, and then press ENTER.

Referring to a Named Range

The following example refers to the range named "MyRange" in the workbook named "MyBook.xls."

Sub FormatRange() Range("MyBook.xls!MyRange").Font.Italic = True End Sub

The following example refers to the worksheet-specific range named "Sheet1!Sales" in the workbook named "Report.xls."

Sub FormatSales() Range("[Report.xls]Sheet1!Sales").BorderAround Weight:=xlthin End Sub

To select a named range, use the GoTo method, which activates the workbook and the worksheet and then selects the range.

Sub ClearRange() Application.Goto Reference:="MyBook.xls!MyRange" Selection.ClearContents End Sub

The following example shows how the same procedure would be written for the active workbook.

Sub ClearRange() Application.Goto Reference:="MyRange" Selection.ClearContents End Sub

Looping Through Cells in a Named Range

The following example loops through each cell in a named range by using a For Each

...

Next

loop. If the value of any cell in the range exceeds the value of limit, the cell color is changed to yellow.

Sub ApplyColor() Const Limit As Integer = 25 For Each c In Range("MyRange") If c.Value > Limit Then c.Interior.ColorIndex = 27 End If Next c End Sub

Excel Developer Reference

How to: Refer to Multiple Ranges

Using the appropriate method, you can easily refer to multiple ranges. Use the Range and Union methods to refer to any group of ranges; use the Areas property to refer to the group of ranges selected on a worksheet.

Using the Range Property

You can refer to multiple ranges with the Range property by inserting commas between two or more references. The following example clears the contents of three ranges on Sheet1.

Sub ClearRanges()

 

_

ClearContents

End Sub

Named ranges make it easier to use the Range property to work with multiple ranges. The following example works when all three named ranges are on the same sheet.

Sub ClearNamed() Range("MyRange, YourRange, HisRange").ClearContents End Sub

Using the Union Method

You can combine multiple ranges into one Range object by using the Union method. The following example creates a Range object called myMultipleRange, defines it as the ranges A1:B2 and C3:D4, and then formats the combined ranges as bold.

Sub MultipleRange() Dim r1, r2, myMultipleRange As Range Set r1 = Sheets("Sheet1").Range("A1:B2") Set r2 = Sheets("Sheet1").Range("C3:D4") Set myMultipleRange = Union(r1, r2) myMultipleRange.Font.Bold = True End Sub

Using the Areas Property

You can use the Areas property to refer to the selected range or to the collection of ranges in a multiple-area selection. The following procedure counts the areas in the selection. If there is more than one area, a warning message is displayed.

Sub FindMultiple() If Selection.Areas.Count > 1 Then MsgBox "Cannot do this to a multiple selection." End If End Sub

Excel Developer Reference

How to: Refer to Rows and Columns

Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.

End Sub
End Sub

The following table illustrates some row and column references using the Rows and Columns properties.

Reference

Meaning

Rows(1)

Row one

Rows

All the rows on the worksheet

Columns(1)

Column one

Columns("A")

Column one

Columns

All the columns on the worksheet

To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns property. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.

Sub SeveralRows()

Worksheets("Sheet1").Activate

Dim myUnion As Range Set myUnion = Union(Rows(1), Rows(3), Rows(5)) myUnion.Font.Bold = True End Sub

Looping Through a Range of Cells

When using Visual Basic, you often need to run the same block of statements on each cell in a range of cells. To do this, you combine a looping statement and one or more methods to identify each cell, one at a time, and run the operation.

One way to loop through a range is to use the For

... In the following example, the variable counter is substituted for the row index. The procedure loops through the range C1:C20, setting to 0 (zero) any number whose absolute value is less than 0.01.

Next

loop with the Cells property. Using the Cells property, you can substitute the loop counter (or other variables or expressions) for the cell index numbers.

Sub RoundToZero1() For Counter = 1 To 20 Set curCell = Worksheets("Sheet1").Cells(Counter, 3) If Abs(curCell.Value) < 0.01 Then curCell.Value = 0 Next Counter End Sub

Another easy way to loop through a range is to use a For Each

...

Next

loop with the collection of cells specified in the Range property. Visual Basic automatically sets an object variable for the next cell each time

the loop runs. The following procedure loops through the range A1:D10, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero2() For Each c In Worksheets("Sheet1").Range("A1:D10").Cells If Abs(c.Value) < 0.01 Then c.Value = 0

Next

End Sub

If you do not know the boundaries of the range you want to loop through, you can use the CurrentRegion property to return the range that surrounds the active cell. For example, the following procedure, when run from a worksheet, loops through the range that surrounds the active cell, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero3() For Each c In ActiveCell.CurrentRegion.Cells If Abs(c.Value) < 0.01 Then c.Value = 0

Next

End Sub

Selecting and Activating Cells

When you work with Microsoft Excel, you usually select a cell or cells and then perform an action, such as formatting the cells or entering values in them. In Visual Basic, it is usually not necessary to select cells before modifying them.

For example, if you want to enter a formula in cell D6 using Visual Basic, you do not need to select the range D6. You just need to return the Range object and then set the Formula property to the formula you want, as shown in the following example.

Sub EnterFormula() Worksheets("Sheet1").Range("D6").Formula = "=SUM(D2:D5)" End Sub

For examples of using other methods to control cells without selecting them, see How to: Reference Cells and Ranges.

Using the Select Method and the Selection Property

The Select method activates sheets and objects on sheets; the Selection property returns an object that represents the current selection on the active sheet in the active workbook. Before you can use the Selection property successfully, you must activate a workbook, activate or select a sheet, and then select a range (or other object) using the Select method.

The macro recorder will often create a macro that uses the Select method and the Selection property. The following Sub procedure was created using the macro recorder, and it illustrates how Select and Selection work together.

Sheets("Sheet1").Select

Range("A1").Select

ActiveCell.FormulaR1C1 = "Name"

Range("B1").Select

ActiveCell.FormulaR1C1 = "Address"

Range("A1:B1").Select

Selection.Font.Bold = True End Sub

The following example accomplishes the same task without activating or selecting the worksheet or cells.

Sub Labels() With Worksheets("Sheet1") .Range("A1") = "Name" .Range("B1") = "Address" .Range("A1:B1").Font.Bold = True End With End Sub

Selecting Cells on the Active Worksheet

If you use the Select method to select cells, be aware that Select works only on the active worksheet. If you run your Sub procedure from the module, the Select method will fail unless your procedure activates the worksheet before using the Select method on a range of cells. For example, the following procedure copies a row from Sheet1 to Sheet2 in the active workbook.

Sub CopyRow()

Worksheets("Sheet1").Rows(1).Copy

Worksheets("Sheet2").Select

Worksheets("Sheet2").Rows(1).Select

Worksheets("Sheet2").Paste

End Sub

Activating a Cell Within a Selection

You can use the Activate method to activate a cell within a selection. There can be only one active cell, even when a range of cells is selected. The following procedure selects a range and then activates a cell within the range without changing the selection.

Sub MakeActive() Worksheets("Sheet1").Activate Range("A1:D4").Select Range("B2").Activate End Sub
Sub MakeActive()
Worksheets("Sheet1").Activate
Range("A1:D4").Select
Range("B2").Activate
End Sub

Working with the Active Cell

The ActiveCell property returns a Range object that represents the cell that is active. You can apply any of the properties or methods of a Range object to the active cell, as in the following example.

 

Sub SetValue()

Worksheets("Sheet1").Activate

ActiveCell.Value = 35 End Sub

Note

Note

You can work with the active cell only when the worksheet that it is on is the active sheet.

Moving the Active Cell

You can use the Activate method to designate which cell is the active cell. For example, the following procedure makes B5 the active cell and then formats it as bold.

 

Sub SetActive()

Worksheets("Sheet1").Activate

Worksheets("Sheet1").Range("B5").Activate

ActiveCell.Font.Bold = True End Sub

Note

Note

To select a range of cells, use the Select method. To make a single cell the active cell, use the Activate method.

You can use the Offset property to move the active cell. The following procedure inserts text into the active cell in the selected range and then moves the active cell one cell to the right without changing the selection.

Range("A1:D10").Select ActiveCell.Value = "Monthly Totals" ActiveCell.Offset(0, 1).Activate End Sub
Range("A1:D10").Select
ActiveCell.Value = "Monthly Totals"
ActiveCell.Offset(0, 1).Activate
End Sub

Selecting the Cells Surrounding the Active Cell

The CurrentRegion property returns a range of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells adjoining the active cell that contain data. This range is then formatted with the Currency style.

Sub Region()

Worksheets("Sheet1").Activate

ActiveCell.CurrentRegion.Select Selection.Style = "Currency" End Sub

Working with 3-D Ranges

If you are working with the same range on more than one sheet, use the Array function to specify two or more sheets to select. The following example formats the border of a 3-D range of cells.

Sub FormatSheets() Sheets(Array("Sheet2", "Sheet3", "Sheet5")).Select

Range("A1:H1").Select

Selection.Borders(xlBottom).LineStyle = xlDouble End Sub

The following example applies the FillAcrossSheets method to transfer the formats and any data from the range on Sheet2 to the corresponding ranges on all the worksheets in the active workbook.

Sub FillAll() Worksheets("Sheet2").Range("A1:H1") _ .Borders(xlBottom).LineStyle = xlDouble Worksheets.FillAcrossSheets (Worksheets("Sheet2") _

.Range("A1:H1"))

End Sub

Opening a Workbook

When you open a workbook using the Open method, it becomes a member of the Workbooks collection. The following procedure opens a workbook named MyBook.xls located in the folder named MyFolder on drive C.

Sub OpenUp() Workbooks.Open("C:\MyFolder\MyBook.xls") End Sub

Returning an Object from a Collection

Range("A1:D10").Select ActiveCell.Value = "Monthly Totals" ActiveCell.Offset(0, 1).Activate End Sub Selecting the Cells Surrounding the ActiveCurrentRegion property returns a range of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells adjoining the active cell that contain data. This range is then formatted with the Currency style. Sub Region() Worksheets("Sheet1").Activate ActiveCell.CurrentRegion.Select Selection.Style = "Currency" End Sub Working with 3-D Ranges If you are working with the same range on more than one sheet, use the Array function to specify two or more sheets to select. The following example formats the border of a 3-D range of cells. Sub FormatSheets() Sheets(Array("Sheet2", "Sheet3", "Sheet5")).Select Range("A1:H1").Select Selection.Borders(xlBottom).LineStyle = xlDouble End Sub The following example applies the FillAcrossSheets method to transfer the formats and any data from the range on Sheet2 to the corresponding ranges on all the worksheets in the active workbook. Sub FillAll() Worksheets("Sheet2").Range("A1:H1") _ .Borders(xlBottom).LineStyle = xlDouble Worksheets.FillAcrossSheets (Worksheets("Sheet2") _ .Range("A1:H1")) End Sub Opening a Workbook When you open a workbook using the Open method, it becomes a member of the Workbooks collection. The following procedure opens a workbook named MyBook.xls located in the folder named MyFolder on drive C. Sub OpenUp() Workbooks.Open("C:\MyFolder\MyBook.xls") End Sub Returning an Object from a Collection Show All The Item property returns a single object from a collection. The following example sets the firstBook variable to a Workbook object that represents workbook one. Set FirstBook = Workbooks.Item(1) The Item property is the default property for most collections, so you can write the same statement more concisely by omitting the Item keyword. Set FirstBook = Workbooks(1) For more information about a specific collection, see the Help topic for that collection or the Item property for the collection. Named Objects Although you can usually specify an integer value with the Item property, it may be more convenient to return an object by name. Before you can use a name with the Item property, you must name the object. Most often, this is done by setting the object's Name property. The following example creates a named worksheet in the active workbook and then refers to the worksheet by name. ActiveWorkbook.Worksheets.Add.Name = "A New Sheet" With Worksheets("A New Sheet") .Range("A5:A10").Formula = "=RAND()" End With " id="pdf-obj-10-60" src="pdf-obj-10-60.jpg">

The Item property returns a single object from a collection. The following example sets the firstBook variable to a Workbook object that represents workbook one.

Set FirstBook = Workbooks.Item(1)

The Item property is the default property for most collections, so you can write the same statement more concisely by omitting the Item keyword.

Set FirstBook = Workbooks(1)

For more information about a specific collection, see the Help topic for that collection or the Item property for the collection.

Named Objects

Although you can usually specify an integer value with the Item property, it may be more convenient to return an object by name. Before you can use a name with the Item property, you must name the object. Most often, this is done by setting the object's Name property. The following example creates a named worksheet in the active workbook and then refers to the worksheet by name.

Predefined Index Values

Some collections have predefined index values you can use to return single objects. Each predefined index value is represented by a constant. For example, you specify an XlBordersIndex constant with the Item property of the Borders collection to return a single border.

The following example sets the bottom border of cells A1:G1 on Sheet1 to a double line.

Worksheets("Sheet1").Range("A1:A1").

_ Borders.Item(xlEdgeBottom).LineStyle = xlDouble

Controlling One Microsoft Office Application from Another

If you want to run code in one Microsoft Office application that works with the objects in another application, follow these steps.

  • 1. Set a reference to the other application's type library in the References dialog box (Tools menu). After you have done this, the objects, properties, and methods will show up in

the Object Browser and the syntax will be checked at compile time. You can also get context-sensitive Help on them.

  • 2. Declare object variables that will refer to the objects in the other application as specific types. Make sure you qualify each type with the name of the application that is supplying

the object. For example, the following statement declares a variable that points to a Microsoft Word document and another that refers to a Microsoft Excel workbook:

Dim appWD As Word.Application, wbXL As Excel.Workbook

Note

Note

You must follow the preceding steps if you want your code to be early bound.

  • 3. Use the CreateObject function with the OLE Programmatic Identifiers of the object you want to work with in the other application, as shown in the following example. If you want

to see the session of the other application, set the Visible property to True.

Dim appWD As Word.Application

Set appWD = CreateObject("Word.Application") appWd.Visible = True

  • 4. Apply properties and methods to the object contained in the variable. For example, the following instruction creates a new Word document.

Dim appWD As Word.Application

Set appWD = CreateObject("Word.Application") appWD.Documents.Add

  • 5. When you are done working with the other application, use the Quit method to close it, as shown in the following example.

appWd.Quit
appWd.Quit

Calling a Worksheet Function from Visual Basic

In Visual Basic, the Excel worksheet functions are available through the WorksheetFunction object.

The following Sub procedure uses the Min worksheet function to determine the smallest value in a range of cells. First, the variable myRange is declared as a Range object, and then it is set to range

A1:C10 on Sheet1. Another variable, answer, is assigned the result of applying the Min function to myRange. Finally, the value of answer is displayed in a message box.

Sub UseFunction() Dim myRange As Range Set myRange = Worksheets("Sheet1").Range("A1:C10") answer = Application.WorksheetFunction.Min(myRange) MsgBox answer End Sub

If you use a worksheet function that requires a range reference as an argument, you must specify a Range object. For example, you can use the Match worksheet function to search a range of cells. In a worksheet cell, you would enter a formula such as =MATCH(9,A1:A10,0). However, in a Visual Basic procedure, you would specify a Range object to get the same result.

Sub FindFirst() myVar = Application.WorksheetFunction _ .Match(9, Worksheets(1).Range("A1:A10"), 0) MsgBox myVar End Sub

Note

Note

Visual Basic functions do not use the WorksheetFunction qualifier. A function may have the same name as a Microsoft Excel function and yet work differently. For example, Application.WorksheetFunction.Log and Log will return different values.

Inserting a Worksheet Function into a Cell

To insert a worksheet function into a cell, you specify the function as the value of the Formula property of the corresponding Range object. In the following example, the RAND worksheet function (which generates a random number) is assigned to the Formula property of range A1:B3 on Sheet1 in the active workbook.

Sub InsertFormula() Worksheets("Sheet1").Range("A1:B3").Formula = "=RAND()" End Sub

Example

This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Notice that this example uses the InputBox method instead of the InputBox function so that the method can perform type checking. The Static statements cause Visual Basic to retain the values of the three variables; these are displayed as default values the next time you run the program.

Static loanAmt Static loanInt Static loanTerm loanAmt = Application.InputBox _ (Prompt:="Loan amount (100,000 for example)", _ Default:=loanAmt, Type:=1) loanInt = Application.InputBox _ (Prompt:="Annual interest rate (8.75 for example)", _ Default:=loanInt, Type:=1) loanTerm = Application.InputBox _ (Prompt:="Term in years (30 for example)", _ Default:=loanTerm, Type:=1) payment = Application.WorksheetFunction _ .Pmt(loanInt / 1200, loanTerm * 12, loanAmt) MsgBox "Monthly payment is " & Format(payment, "Currency")