Professional Documents
Culture Documents
The following table shows the supported data types, including storage sizes and ranges.
Range 0 to 255 True or False -32,768 to 32,767 -2,147,483,648 to 2,147,483,647 -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values -922,337,203,685,477.5808 to 922,337,203,685,477.5807 +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001 January 1, 100 to December 31, 9999 Any Object reference 0 to approximately 2 billion 1 to approximately 65,400 Any numeric value up to the range of a Double Same range as for variable-length String The range of each element is the same as the range of its data type.
Single (single-precision floating- 4 bytes point) Double (double-precision floating-point) Currency (scaled integer) Decimal Date Object String (variable-length) String (fixed-length) Variant (with numbers) Variant (with characters) User-defined (using Type) Note 8 bytes 8 bytes
14 bytes 8 bytes 4 bytes 10 bytes + string length Length of string 16 bytes 22 bytes + string length Number required by elements
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 Use the StrConv function to convert one type of string data to another.
Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.Boolean variables display as either
True
or
False
(when Print is used) or
#TRUE#
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.
#January 1, 1993#
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.
Note
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.
Note
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.
Type MyType MyName As String ' String variable stores a name. MyBirthDate As Date ' Date variable stores a birthdate. MySex As Integer ' Integer variable stores sex (0 for End Type ' female, 1 for male).
Excel 2007 Developer Reference > Visual Basic for Applications Language Reference > Visual Basic Language Reference > Data Types
MyVar
contains a numeric representation the actual value
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
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.
newBook. Next,
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
Note The index order can change if you move, add, or delete sheets.
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
Some ways to reference cells How to: How to: How to: How to: How to: How to: How to: How to: How to: Refer Refer Refer Refer Refer Refer Refer Refer Refer to to to to to to to to to All the Cells on the Worksheet Cells and Ranges by Using A1 Notation Rows and Columns Cells by Using Index Numbers Cells by Using Shortcut Notation Cells Relative to Other Cells Cells by Using a Range Object Named Ranges Multiple Ranges
Reference
Range("A1") Range("A1:B5") Range("C5:D9,G9:H16") Range("A:A") Range("1:1") Range("A:C") Range("1:5") Range("1:1,3:3,8:8") Range("A:A,C:C,F:F")
Meaning Cell A1 Cells A1 through B5 A multiple-area selection Column A Row 1 Columns A through C Rows 1 through 5 Rows 1, 3, and 8 Columns A, C, and F
Rows(1)
Reference
Rows(1) Rows Columns(1) Columns("A") Columns
Meaning Row one All the rows on the worksheet Column one Column one 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
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 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
Sub ClearRange() Worksheets("Sheet1").[A1:B5].ClearContents End Sub Sub SetValue() [MyRange].Value = 30 End Sub
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
myRange and then assigns the variable to range A1:D5 on Sheet1 in the active workbook. Subsequent statements modify properties of the range by
Sub Random() Dim myRange As Range Set myRange = Worksheets("Sheet1").Range("A1:D5") myRange.Formula = "=RAND()" myRange.Font.Bold = True End Sub
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
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
Sub FindMultiple() If Selection.Areas.Count > 1 Then MsgBox "Cannot do this to a multiple selection." End If End Sub
Rows(1)
End Sub
The following table illustrates some row and column references using the Rows and Columns properties.
Reference
Rows(1) Rows Columns(1) Columns("A") Columns
Meaning Row one All the rows on the worksheet Column one Column one 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
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.
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
Sub Macro1()
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
Note You can work with the active cell only when the worksheet that it is on is the active sheet.
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.
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.
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
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:
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.
4.
Apply properties and methods to the object contained in the variable. For example, the following instruction creates a new Word document.
5.
appWd.Quit
When you are done working with the other application, use the Quit method to close it, as shown in the following example.
myRange is declared as a Range object, and then it is set to range 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 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.
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.
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")