0% found this document useful (0 votes)
3K views1,081 pages

Microsoft Office VBA Language Reference

The document summarizes the - (subtraction) operator and & (string concatenation) operator in Visual Basic for Applications. It provides the syntax, descriptions of parts, and remarks for each operator. Examples are also given to demonstrate their use.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views1,081 pages

Microsoft Office VBA Language Reference

The document summarizes the - (subtraction) operator and & (string concatenation) operator in Visual Basic for Applications. It provides the syntax, descriptions of parts, and remarks for each operator. Examples are also given to demonstrate their use.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1081

Microsoft Visual Basic for Applications Language Reference

Page 1 of 1081

Microsoft Visual Basic for Applications Language Reference


Operator
Description Used to find the difference between two numbers or to indicate the negative value of a numeric expression. Syntax 1 result = number1number2 Syntax 2 number The operator syntax has these parts Part Description

result

Required; any numeric variable.

number

Required; any numeric expression.

number1

Required; any numeric expression.

number2

Required; any numeric expression.

Remarks In Syntax 1, the operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the operator is used as the unary negation operator to indicate the negative value of an expression. The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency, and Decimal. The following are exceptions to this order

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 2 of 1081

If

Then result is

Subtraction involves a Single and a Long,

converted to a Double.

The data type of result is a Long, Single, or Date variant that overflows its legal range,

converted to a Variant containing a Double.

The data type of result is a Byte variant that overflows its legal range,

converted to an Integer variant.

The data type of result is an Integer variant that overflows its legal range,

converted to a Long variant.

Subtraction involves a Date and any other data type,

a Date.

Subtraction involves two Date expressions,

a Double.

One or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as 0. Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication. See Also Operator precedence. Example This example uses the operator to calculate the difference between two numbers.
Dim MyResult MyResult = 4 - 2 MyResult = 459.35 - 334.90 ' Returns 2. ' Returns 124.45.

#Const Directive
file://C:\temporary\~hhE561.htm 3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 3 of 1081

Description Used to define conditional compiler constants for Visual Basic. Syntax #Const constname = expression The #Const compiler directive syntax has these parts Part Description

constname

Required; Variant (String). Name of the constant; follows standard variable naming conventions.

expression

Required. Literal, other conditional compiler constant, or any combination that includes any or all arithmetic or logical operators except Is.

Remarks Conditional compiler constants are always Private to the module in which they appear. It is not possible to create Public compiler constants using the #Const directive. Public compiler constants can only be created in the user interface. Only conditional compiler constants and literals can be used in expression. Using a standard constant defined with Const, or using a constant that is undefined, causes an error to occur. Conversely, constants defined using the #Const keyword can only be used for conditional compilation. Conditional compiler constants are always evaluated at the module level, regardless of their placement in code. See Also #If...Then...#Else directive, Const statement. Specifics (Microsoft Access) In Microsoft Access, you can define a public conditional compiler constant in the Declarations section of a module. A public compiler constant is applicable to all modules in the current database, but not in any other database. You can also declare a public compiler constant by clicking Options on the Tools menu, then clicking the Advanced tab. Enter the constant in the Conditional Compilation Arguments box.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 4 of 1081

For example, you might enter the following expression into the Conditional Compilation Arguments box.
conDebug = 1

You can use a public compiler constant in code in any module. For example, you can create an #If...Then...#Else construct to optionally run debug code.
#If conDebug = 1 Then . ' Run debug code. . . #Else . ' Run streamlined code. . . #End If

To create multiple public conditional compilation constants, declare them on separate lines in the Declaration section. In the Conditional Compilation Arguments box, separate them with colons. For example, you can enter the following conditional compilation constants in the Conditional Compilation Arguments box.
conActiveLanguage = 1 : conDebug = 1

You can use a logical operator to include both constants in an #If...Then...#Else construct. In the following example, the first segment of code runs only if both constants are currently equal to 1, so that the expression containing the constants is true.
#If (conActiveLanguage = 1 And conDebug = 1) Then . ' Run debug code for the active language version. . . #Else . ' Run another code segment. . . #End If

If either or both constants have a different value, then the code in the #Else portion of the construct runs. To change which block of code runs, you can simply change the values of the constants. Notes A conditional compilation constant is always evaluated with a text-based string comparison method. This evaluation is equivalent to having an Option Compare Text statement in the module and occurs even if the module contains an Option Compare Database statement. When writing code for conditional compilation, it may be less confusing to view one procedure at a time rather than all procedures in the module. To change how you view your code, click Options on the Tools menu, then click the Module tab. Under Code View, clear the Full Module View check box. Example This example uses the #Const directive to declare conditional compiler constants for use in #If...#Else...#End If constructs.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 5 of 1081

#Const DebugVersion = 1

' Will evaluate true in #If block.

#If...Then...#Else Directive
Description Conditionally compiles selected blocks of Visual Basic code. Syntax #If expression Then statements [#ElseIf expression-n Then [elseifstatements]] [#Else [elsestatements]] #End If The #If...Then...#Else directive syntax has these parts Part Description

expression

Required. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.

statements

Required. Visual Basic program lines or compiler directives that are evaluated if the associated expression is True.

expression-n

Optional. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 6 of 1081

elseifstatements

Optional. One or more program lines or compiler directives that are evaluated if expression-n is True.

elsestatements

Optional. One or more program lines or compiler directives that are evaluated if no previous expression or expression-n is True.

Remarks The behavior of the #If...Then...#Else directive is the same as the If...Then...Else statement, except that there is no single-line form of the #If, #Else, #ElseIf, and #End If directives; that is, no other code can appear on the same line as any of the directives. Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted from the final executable file, so it has no size or performance effect. Regardless of the outcome of any evaluation, all expressions are evaluated. Therefore, all constants used in expressions must be defined any undefined constant evaluates as Empty. Note The Option Compare statement does not affect expressions in #If and #ElseIf statements. Expressions in a conditional-compiler directive are always evaluated with Option Compare Text. See Also #Const directive, If...Then...Else statement. Example This example references conditional compiler constants in an #If...Then...#Else construct to determine whether to compile certain statements.
' If Mac evaluates as true, do the statements following the #If. #If Mac Then '. Place exclusively Mac statements here. '. '. ' Otherwise, if it is a 32-bit Windows program, do this: #ElseIf Win32 Then '. Place exclusively 32-bit Windows statements here. '. '. ' Otherwise, if it is neither, do this: #Else '. Place other platform statements here. '. '. #End If

& Operator
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 7 of 1081

Used to force string concatenation of two expressions. Syntax result = expression1 & expression2 The & operator syntax has these parts Part Description

result

Required; any String or Variant variable.

expression1

Required; any expression.

expression2

Required; any expression.

Remarks If an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are string expressions; otherwise, result is a String variant. If both expressions are Null, result is Null. However, if only one expression is Null, that expression is treated as a zero-length string (" ") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string. See Also Operator precedence. Example This example uses the & operator to force string concatenation.
Dim MyStr MyStr = "Hello" & " World" MyStr = "Check " & 123 & " Check" ' Returns "Hello World". ' Returns "Check 123 Check".

* Operator
Description Used to multiply two numbers. Syntax result = number1*number2

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 8 of 1081

The * operator syntax has these parts Part Description

result

Required; any numeric variable.

number1

Required; any numeric expression.

number2

Required; any numeric expression.

Remarks The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Currency, Double, and Decimal. The following are exceptions to this order If Then result is

Multiplication involves a Single and a Long,

converted to a Double.

The data type of result is a Long, Single, or Date variant that overflows its legal range,

converted to a Variant containing a Double.

The data type of result is a Byte variant that overflows its legal range,

converted to an Integer variant.

the data type of result is an Integer variant that overflows its legal range,

converted to a Long variant.

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as 0. Note The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 9 of 1081

Operator precedence. Example This example uses the * operator to multiply two numbers.
Dim MyValue MyValue = 2 * 2 MyValue = 459.35 * 334.90 ' Returns 4. ' Returns 153836.315.

/ Operator
Description Used to divide two numbers and return a floating-point result. Syntax result = number1/number2 The / operator syntax has these parts Part Description

result

Required; any numeric variable.

number1

Required; any numeric expression.

number2

Required; any numeric expression.

Remarks The data type of result is usually a Double or a Double variant. The following are exceptions to this rule If Then result is

Both expressions are Byte, Integer, or Single expressions,

a Single unless it overflows its legal range; in which case, an error occurs.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 10 of 1081

Both expressions are Byte, Integer, or Single variants,

a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.

Division involves a Decimal and any other data type,

a Decimal data type.

One or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0. See Also Operator precedence. Example This example uses the / operator to perform floating-point division.
Dim MyValue MyValue = 10 / 4 MyValue = 10 / 3 ' Returns 2.5. ' Returns 3.333333.

\ Operator
Description Used to divide two numbers and return an integer result. Syntax result = number1\number2 The \ operator syntax has these parts Part Description

result

Required; any numeric variable.

number1

Required; any numeric expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 11 of 1081

number2

Required; any numeric expression.

Remarks Before division is performed, the numeric expressions are rounded to Byte, Integer, or Long expressions. Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Long variant, regardless of whether result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is Null. Any expression that is Empty is treated as 0. See Also Operator precedence. Example This example uses the \ operator to perform integer division.
Dim MyValue MyValue = 11 \ 4 MyValue = 9 \ 3 MyValue = 100 \ 3 ' Returns 2. ' Returns 3. ' Returns 33.

^ Operator
Description Used to raise a number to the power of an exponent. Syntax result = number^exponent The ^ operator syntax has these parts Part Description

result

Required; any numeric variable.

number

Required; any numeric expression.

exponent

Required; any numeric expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 12 of 1081

Remarks A number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right. Usually, the data type of result is a Double or a Variant containing a Double. However, if either number or exponent is a Null expression, result is Null. See Also Operator precedence. Example This example uses the ^ operator to raise a number to the power of an exponent.
Dim MyValue MyValue = 2 ^ 2 MyValue = 3 ^ 3 ^ 3 MyValue = (-5) ^ 3 ' Returns 4. ' Returns 19683. ' Returns -125.

+ Operator
Description Used to sum two numbers. Syntax result = expression1+expression2 The + operator syntax has these parts Part Description

result

Required; any numeric variable.

expression1

Required; any expression.

expression2

Required; any expression.

Remarks When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 13 of 1081

provide self-documenting code. If at least one expression is not a Variant, the following rules apply If Then

Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, Currency, or Decimal),

Add.

Both expressions are String,

Concatenate.

One expression is a numeric data type and the other is any Variant except Null,

Add.

One expression is a String and the other is any Variant except Null,

Concatenate.

One expression is an Empty Variant,

Return the remaining expression unchanged as result.

One expression is a numeric data type and the other is a String,

A Type mismatch error occurs.

Either expression is Null,

result is Null.

If both expressions are Variant expressions, the following rules apply If Then

Both Variant expressions are numeric,

Add.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 14 of 1081

Both Variant expressions are strings,

Concatenate.

One Variant expression is numeric and the other is a string,

Add.

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency, and Decimal. The following are exceptions to this order If Then result is

A Single and a Long are added,

a Double.

The data type of result is a Long, Single, or Date variant that overflows its legal range,

converted to a Double variant.

(continued) The data type of result is a Byte variant that overflows its legal range, converted to an Integer variant.

The data type of result is an Integer variant that overflows its legal range,

converted to a Long variant.

A Date is added to any data type,

a Date.

If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result. Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 15 of 1081

See Also Operator precedence. Example This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings. However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.
Dim MyNumber, Var1, Var2 MyNumber = 2 + 2 ' Returns 4. MyNumber = 4257.04 + 98112 Var1 = "34": Var2 = 6 MyNumber = Var1 + Var2 Var1 = "34": Var2 = "6" MyNumber = Var1 + Var2

' Returns 102369.04. ' Initialize mixed variables. ' Returns 40. ' Initialize variables with strings. ' Returns "346" (string concatenation).

Abs Function
Description Returns a value of the same type that is passed to it specifying the absolute value of a number. Syntax Abs(number) The required number argument can be any valid numeric expression. If number contains Null, Null is returned; if it is an uninitialized variable, zero is returned. Remarks The absolute value of a number is its unsigned magnitude. For example, ABS(-1) and ABS(1) both return 1. See Also Sgn function. Example This example uses the Abs function to compute the absolute value of a number.
Dim MyNumber MyNumber = Abs(50.3) MyNumber = Abs(-50.3) ' Returns 50.3. ' Returns 50.3.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 16 of 1081

Activate, Deactivate Events


Applies To UserForm object. Description The Activate event occurs when an object becomes the active window. The Deactivate event occurs when an object is no longer the active window. Syntax Private Sub object_Activate( ) Private Sub object_Deactivate( ) The object placeholder represents an object expression that evaluates to an object in the Applies To list. Remarks An object can become active by using the Show method in code. The Activate event can occur only when an object is visible. A UserForm loaded with Load isn't visible unless you use the Show method. The Activate and Deactivate events occur only when you move the focus within an application. Moving the focus to or from an object in another application doesn't trigger either event. The Deactivate event doesn't occur when unloading an object. Example The following code uses two UserForm objects: UserForm1 and UserForm2. Copy these procedures into the UserForm1 module, then add UserForm2. UserForm1's caption is created in its Activate event procedure. When the user clicks the client area of UserForm1, UserForm2 is loaded, and shown, triggering UserForm1's Deactivate event, changing their captions.
' Activate event for UserForm1. Private Sub UserForm_Activate() UserForm1.Caption = "Click my client area" End Sub ' Click event for UserForm1. Private Sub UserForm_Click() Load UserForm2 UserForm2.StartUpPosition = 3 UserForm2.Show End Sub ' Deactivate event for UserForm1. Private Sub UserForm_Deactivate() UserForm1.Caption = "I just lost the focus!" UserForm2.Caption = "Focus just left UserForm1 and came to me" End Sub

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 17 of 1081

Add Method
Applies To Collection object. Description Adds a member to a Collection object. Syntax object.Add item, key, before, after The Add method syntax has the following object qualifier and named arguments Part Description

object

Required. An object expression that evaluates to an object in the Applies To list.

item

Required. An expression of any type that specifies the member to add to the collection.

key

Optional. A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.

before

Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the before argument. If a numeric expression, before must be a number from 1 to the value of the collection's Count property. If a string expression, before must correspond to the key specified when the member being referred to was added to the collection. You can specify a before position or an after position, but not both.

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 18 of 1081

Part

Description

after

Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the after argument. If numeric, after must be a number from 1 to the value of the collection's Count property. If a string, after must correspond to the key specified when the member referred to was added to the collection. You can specify a before position or an after position, but not both.

Remarks Whether the before or after argument is a string expression or numeric expression, it must refer to an existing member of the collection, or an error occurs. An error also occurs if a specified key duplicates the key for an existing member of the collection. See Also Item method, Remove method. Specifics (Microsoft Access) Items added to a user-defined collection are automatically indexed. You can refer to an individual item by this index. For example, if you have a collection colThings that contains four objects, you can refer to the third item in the collection with the expression colThings(3). Note When you add items to a Collection object, they are automatically indexed beginning with the number 1. Therefore, when you enumerate a Collection object, keep in mind that the index begins at 1. This may be different from built-in collections, which usually are indexed beginning with 0. When you add an object to a user-defined collection, you can also specify a custom key for that object in addition to the automatic index. In subsequent references to the object, you can refer to the custom key. For example, you can add an object objMine with the following key.
colThings.Add Item := objMine, key := ("A")

Subsequently you can refer to this particular object in the collection either as colThings(A), or by its numeric index. Example This example uses the Add method to add Inst objects (instances of a class called Class1

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 19 of 1081

containing a Public variable InstanceName) to a collection called MyClasses. To see how this works, insert a class module and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the Form_Load event procedure of a form module.
Dim Dim Dim Dim Do MyClasses As New Collection Num As Integer Msg TheName ' Create a Collection object. ' Counter for individualizing keys. ' Holder for names user enters.

Dim Inst As New Class1 ' Create a new instance of Class1. Num = Num + 1 ' Increment Num, then get a name. Msg = "Please enter a name for this object." & Chr(13) _ & "Press Cancel to see names in collection." TheName = InputBox(Msg, "Name the Collection Items") Inst.InstanceName = TheName ' Put name in object instance. ' If user entered name, add it to the collection. If Inst.InstanceName <> "" Then ' Add the named object to the collection. MyClasses.Add item := Inst, key := CStr(Num) End If ' Clear the current reference in preparation for next one. Set Inst = Nothing Loop Until TheName = "" For Each x In MyClasses MsgBox x.instancename, , "Instance Name" Next

Example (Extensibility Object Model) The following example uses the Add method to add one standard module to the VBComponents collection.
Application.VBE.VBProjects(1).VBComponents.Add(vbext_ct_StdModule)

And Operator
Description Used to perform a logical conjunction on two expressions. Syntax result = expression1 And expression2 The And operator syntax has these parts Part Description

result

Required; any numeric variable.

expression1

Required; any expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 20 of 1081

expression2

Required; any expression.

Remarks If both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined If expression1 is And expression2 is The result is

True

True

True

(continued) If expression1 is And expression2 is The result is

True

False

False

True

Null

Null

False

True

False

False

False

False

False

Null

False

Null

True

Null

Null

False

False

Null

Null

Null

The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 21 of 1081

If bit in expression1 is

And bit in expression2 is

The result is

See Also Operator precedence. Example This example uses the And operator to perform a logical conjunction on two expressions.
Dim A, B, A = 10: B MyCheck = MyCheck = MyCheck = MyCheck = C, D, MyCheck = 8: C = 6: D A > B And B > B > A And B > A > B And B > A And B = Null C C D ' Initialize variables. ' Returns True. ' Returns False. ' Returns Null. ' Returns 8 (bitwise comparison).

AppActivate Statement
Description Activates an application window. Syntax AppActivate title[, wait] The AppActivate statement syntax has these named arguments Part Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 22 of 1081

title

Required. String expression specifying the title in the title bar of the application window you want to activate. The task ID returned by the Shell function can be used in place of title to activate an application.

wait

Optional. Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, then activates the specified application.

Remarks The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style. In determining which application to activate, title is compared to the title string of each running application. If there is no exact match, any application whose title string begins with title is activated. If there is more than one instance of the application named by title, one instance is arbitrarily activated. See Also SendKeys statement, Shell function. Example This example illustrates various uses of the AppActivate statement to activate an application window. The Shell statements assume the applications are in the paths specified. On the Macintosh, you can use the MacID function to specify the application's signature instead of the application's name. The AppActivate statement is available with Macintosh System 7.0 or later.
Dim MyAppID, ReturnValue ' In Microsoft Windows: AppActivate "Microsoft Word"

' Activate Microsoft ' Word.

' AppActivate can also use the return value of the Shell function. MyAppID = Shell("C:\WORD\WINWORD.EXE", 1) ' Run Microsoft Word. AppActivate MyAppID ' Activate Microsoft ' Word. ' You can also use the return value of the Shell function. ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1) ' Run Microsoft Excel. AppActivate ReturnValue ' Activate Microsoft ' Excel.

Array Function
file://C:\temporary\~hhE561.htm 3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 23 of 1081

Description Returns a Variant containing an array. Syntax Array(arglist) The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Variant. If no arguments are specified, an array of zero length is created. Remarks The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable named A as a Variant. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable.
Dim A As Variant A = Array(10,20,30) B = A(2)

The lower bound of an array created using the Array function is always zero. Unlike other types of arrays, it is not affected by the lower bound specified with the Option Base statement. Note A Variant that is not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types. Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the array elements are accessed in the same way. See Also Deftype statements, Dim statement, Let statement, Option Base statement, Variant data type. Example This example uses the Array function to return a Variant containing an array.
Dim MyWeek, MyDay MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") ' Return values assume lower bound set to 1 (using Option Base ' statement). MyDay = MyWeek(2) ' MyDay contains "Tue". MyDay = MyWeek(4) ' MyDay contains "Thu".

Example (Microsoft Excel) This example fills the range A1:C5 on Sheet1, Sheet5, and Sheet7 with the contents of the same range on Sheet1.
x = Array("Sheet1", "Sheet5", "Sheet7") Sheets(x).FillAcrossSheets _ Worksheets("Sheet1").Range("A1:C5")

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 24 of 1081

This example consolidates data from Sheet2 and Sheet3 onto Sheet1, using the SUM function.
Worksheets("Sheet1").Range("A1").Consolidate _ sources:=Array("Sheet2!R1C1:R37C6", "Sheet3!R1C1:R37C6"), _ Function:=xlSum

This example adds an array of strings as a custom list.


Application.AddCustomList Array("cogs", "sprockets", _ "widgets", "gizmos")

This example hides Chart1, Chart3, and Chart5. Note that in this example, the Charts property returns a Sheets object instead of a Charts object.
Charts(Array("Chart1", "Chart3", "Chart5")).Visible = False

This example sets the entries in list box one on Dialog1.


DialogSheets("Dialog1").ListBoxes(1).List = _ Array("cogs", "widgets", "sprockets", "gizmos")

This example creates a group that includes drawing objects one, three, and five on Sheet1.
Set myGroup = Worksheets("Sheet1").DrawingObjects(Array(1, 3, 5)).Group Worksheets("Sheet1").Activate myGroup.Select

Asc Function
Description Returns an Integer representing the character code corresponding to the first letter in a string. Syntax Asc(string) The required string argument is any valid string expression. If the string contains no characters, a run-time error occurs. Remarks The range for returns is 0 255 on non-DBCS systems, but 32768 32767 on DBCS systems. Note The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. The AscW function returns the Unicode character code except on platforms where Unicode is not supported, in which case, the behavior is identical to the Asc function. See Also Chr function, Type conversion functions.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 25 of 1081

Example This example uses the Asc function to return a character code corresponding to the first letter in the string.
Dim MyNumber MyNumber = Asc("A") MyNumber = Asc("a") MyNumber = Asc("Apple") ' Returns 65. ' Returns 97. ' Returns 65.

Atn Function
Description Returns a Double specifying the arctangent of a number. Syntax Atn(number) The required number argument is a Double or any valid numeric expression. Remarks The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle. The range of the result is pi/2 to pi/2 radians. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. Note Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent). See Also Cos function, Sin function, Tan function. Example This example uses the Atn function to calculate the value of pi.
Dim pi pi = 4 * Atn(1) ' Calculate the value of pi.

Beep Statement

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 26 of 1081

Description Sounds a tone through the computer's speaker. Syntax Beep Remarks The frequency and duration of the beep depend on your hardware and system software, and vary among computers. Example This example uses the Beep statement to sound three consecutive tones through the computer's speaker.
Dim I For I = 1 To 3 Beep Next I ' Loop 3 times. ' Sound a tone.

Boolean Data Type


Description 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. See Also Data type summary, Deftype statements, Integer data type.

Byte Data Type


Description Byte variables are stored as single, unsigned, 8-bit (1-byte) numbers ranging in value from 0 to 255. The Byte data type is useful for containing binary data.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 27 of 1081

See Also Data type summary, Deftype statements, Integer data type.

Calendar Property
Description Returns or sets a value specifying the type of calendar to use with your project. You can use one of two settings for Calendar Setting Value Description

vbCalGreg

Use Gregorian calendar (default).

vbCalHijri

Use Hijri calendar.

Remarks You can only set the Calendar property programmatically. For example, to use the Hijri calendar, use:
Calendar = vbCalHijri

Call Statement
Description Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL) procedure. Syntax [Call] name [argumentlist] The Call statement syntax has these parts

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 28 of 1081

Part

Description

Call

Optional; keyword. If specified, you must enclose argumentlist in parentheses. For example:

Call MyProc(0)

name

Required. Name of the procedure to call.

argumentlist

Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are treated by the called procedure. However, ByVal and ByRef can be used with Call only when calling a DLL procedure.

Remarks You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded. To pass a whole array to a procedure, use the array name followed by empty parentheses. See Also Declare statement, Function statement, Sub statement. Specifics (Macintosh) ByVal and ByRef can be used with Call when making a call to a Macintosh code resource. Example This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, a dynamic-link library (DLL) procedure, and a procedure in a Macintosh code resource.
' Call a Sub procedure. Call PrintToDebugWindow("Hello World") ' The above statement causes control to be passed to the following

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 29 of 1081

' Sub procedure. Sub PrintToDebugWindow(AnyString) Debug.Print AnyString End Sub

' Print to Debug window.

' Call an intrinsic function. The return value of the function is ' discarded. Call Shell(AppName, 1) ' AppName contains the path of the ' executable file. ' Call a Microsoft Windows DLL procedure. The Declare statement must be ' Private in a Class Module, but not in a standard Module. Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer) Sub CallMyDll() Call MessageBeep(0) ' Call Windows DLL procedure. MessageBeep 0 ' Call again without Call keyword. End Sub ' Call a Macintosh code resource. Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _ As Integer) Sub CallMyCodeResource() Call MessageAlert(0) ' Call Macintosh code resource. MessageAlert 0 ' Call again without Call keyword. End Sub

ChDir Statement
Description Changes the current directory or folder. Syntax ChDir path The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive. Remarks The ChDir statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:
ChDir "D:\TMP"

See Also ChDrive statement, CurDir function, Dir function, MkDir statement, RmDir statement. Specifics (Macintosh) On the Power Macintosh, the default drive always changes to the drive specified in path. Full path specifications begin with the volume name, and relative paths begin with a colon ( :). ChDir resolves any aliases specified in the path:
ChDir "MacDrive:Tmp" ' On the Macintosh.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 30 of 1081

Note that when making relative directory changes, different symbols are used in Microsoft Windows and on the Macintosh:
ChDir ".." ChDir "::" ' Moves up one directory in Microsoft Windows. ' Moves up one directory on the Macintosh.

Example This example uses the ChDir statement to change the current directory or folder.
' Change current directory or folder to "MYDIR". ChDir "MYDIR" ' In Microsoft Windows: ' Assume "C:" is the current drive. The following statement changes ' the default directory on drive "D:". "C:" remains the current drive. ChDir "D:\WINDOWS\SYSTEM" ' On the Macintosh: ' Changes default folder and default drive. ChDir "HD:MY FOLDER"

ChDrive Statement
Description Changes the current drive. Syntax ChDrive drive The required drive argument is a string expression that specifies an existing drive. If you supply a zero-length string (" "), the current drive doesn't change. If the drive argument is a multiplecharacter string, ChDrive uses only the first letter. See Also ChDir statement, CurDir function, MkDir statement, RmDir statement. Specifics (Macintosh) On the Macintosh, ChDrive changes the current folder to the root folder of the specified drive. Example This example uses the ChDrive statement to change the current drive.
' In Microsoft Windows: ChDrive "D" ' Make "D" the current drive.

' On the Macintosh: ' Make "MY DRIVE" the current drive. ChDrive "MY DRIVE:" ' Make "MY DRIVE" the current drive and current folder because ' it's the root. ChDrive "MY DRIVE:MY FOLDER"

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 31 of 1081

Choose Function
Description Selects and returns a value from a list of arguments. Syntax Choose(index, choice-1[, choice-2, ... [, choice-n]]) The Choose function syntax has these parts Part Description

index

Required. Numeric expression or field that results in a value between 1 and the number of available choices.

choice

Required. Variant expression containing one of the possible choices.

Remarks Choose returns a value from the list of choices based on the value of index. If index is 1, Choose returns the first choice in the list; if index is 2, it returns the second choice, and so on. You can use Choose to look up a value in a list of possibilities. For example, if index evaluates to 3 and choice-1 = "one", choice-2 = "two", and choice-3 = "three", Choose returns "three". This capability is particularly useful if index represents the value in an option group. Choose evaluates every choice in the list, even though it returns only one. For this reason, you should watch for undesirable side effects. For example, if you use the MsgBox function as part of an expression in all the choices, a message box will be displayed for each choice as it is evaluated, even though Choose returns the value of only one of them. The Choose function returns a Null if index is less than 1 or greater than the number of choices listed. If index is not a whole number, it is rounded to the nearest whole number before being evaluated. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 32 of 1081

IIf function, Select Case statement, Switch function. Specifics (Microsoft Access) You can also use the Choose function in a calculated control on a Microsoft Access form or report. For example, you can use the Choose function to set the value of a control based on the value of another field. Set the ControlSource property of the control to an expression containing the Choose function. The expression in the following example can be used to set the ControlSource property of a control based on the value of a field called ShipVia in an Orders table.
=Choose([ShipVia], "Speedy", "United", "Federal")

In the preceding example, if ShipVia contains 1, the Choose function returns the first string, "Speedy." If it contains 2, the function returns the second string, "United," and so on. If ShipVia contains 0, the Choose function returns a Null. The next example shows how you can ensure that a string is returned even if the field contains 0.
=Choose([ShipVia] + 1, "none", "Speedy", "United", "Federal")

Note In a Visual Basic module, you can use the more full-featured Select Case statement to return a value from a set of several choices. Example This example uses the Choose function to display a name in response to an index passed into the procedure in the Ind parameter.
Function GetChoice(Ind As Integer) GetChoice = Choose(Ind, "Speedy", "United", "Federal") End Function

Example (Microsoft Access) You can use the Choose function to create a calculated control whose value is determined by the value of a field in a table in your database. For example, suppose you have a Shippers table that contains a field called ShipperID. You could create a calculated control on a form to display a text name for the shipper based on the value of the ShipperID field.
=Choose([ShipperID], "Speedy", "United", "Federal")

Chr Function
Description Returns a String containing the character associated with the specified character code. Syntax Chr(charcode)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 33 of 1081

The required charcode argument is a Long that identifies a character. Remarks Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr (10) returns a linefeed character. The normal range for charcode is 0 255. However, on DBCS systems, the actual range for charcode is 32768 to 65536. Note The ChrB function is used with byte data contained in a String. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. The ChrW function returns a String containing the Unicode character except on platforms where Unicode is not supported, in which case, the behavior is identical to the Chr function. See Also Asc function, Str function. Example This example uses the Chr function to return the character associated with the specified character code.
Dim MyChar MyChar = Chr(65) MyChar = Chr(97) MyChar = Chr(62) MyChar = Chr(37) ' ' ' ' Returns Returns Returns Returns A. a. >. %.

Example (Microsoft Excel) This example fills list box one on Dialog1 with the letters A through Z.
For i = 65 To 90 DialogSheets("Dialog1").ListBoxes(1).AddItem Text:=Chr(i) Next i

This example creates a line break in a message box by using the Chr function.
msgText = "The current folder is:" & Chr(13) & CurDir() MsgBox msgText

Clear Method
Applies To Err object. Description Clears all property settings of the Err object. Syntax

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 34 of 1081

object.Clear The object is always the Err object. Remarks Use Clear to explicitly clear the Err object after an error has been handled, for example, when you use deferred error handling with On Error Resume Next. The Clear method is called automatically whenever any of the following statements is executed: Any type of Resume statement. Exit Sub, Exit Function, Exit Property. Any On Error statement. Note The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source). See Also Description property, Err object, HelpContext property, HelpContextID property ("Extensibility Object Model Language Reference"), HelpFile property, LastDLLError property, Number property, On Error statement, Raise method, Source property. Example This example uses the Err objects Clear method to reset the numeric properties of the Err object to zero and its string properties to zero-length strings. If Clear were omitted from the following code, the error message dialog box would be displayed on every iteration of the loop (after an error occurs) whether or not a successive calculation generated an error. You can single-step through the code to see the effect.
Dim Result(10) As Integer ' Declare array whose elements ' will overflow easily.

Dim indx On Error Resume Next ' Defer error trapping. Do Until indx = 10 ' Generate an occasional error or store result if no error. Result(indx) = Rnd * indx * 20000 If Err.Number <> 0 Then MsgBox Err, , "Error Generated: ", Err.HelpFile, Err.HelpContext Err.Clear ' Clear Err object properties. End If indx = indx + 1 Loop

Close Statement
Description Concludes input/output (I/O) to a file opened using the Open statement.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 35 of 1081

Syntax Close [filenumberlist] The optional filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number: [[#]filenumber] [, [#]filenumber] . . . Remarks If you omit filenumberlist, all active files opened by the Open statement are closed. When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released. When the Close statement is executed, the association of a file with its file number ends. See Also End statement, Open statement, Reset statement, Stop statement. Example This example uses the Close statement to close all three files opened for Output.
Dim I, FileName For I = 1 To 3 FileName = "TEST" & I Open FileName For Output As #I Print #I, "This is a test." Next I Close ' Loop 3 times. ' Create file name. ' Open file. ' Write string to file. ' Close all 3 open files.

Collection Object
Description A Collection object is an ordered set of items that can be referred to as a unit. Remarks The Collection object provides a convenient way to refer to a related group of items as a single object. The items, or members, in a collection need only be related by the fact that they exist in the collection. Members of a collection don't have to share the same data type. A collection can be created the same way other objects are created. For example:
Dim X As New Collection

Once a collection is created, members can be added using the Add method and removed using

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 36 of 1081

the Remove method. Specific members can be returned from the collection using the Item method, while the entire collection can be iterated using the For Each...Next statement. Properties Count property. Methods Add method, Item method, Remove method. See Also Add method, For EachNext statement, Item method, Remove method. Specifics (Microsoft Access) In Microsoft Access, a Collection object can consist of a set of objects of any type. You can create a Collection object that consists of several objects of the same type or objects of different types. The collection defined by a Collection object can contain any combination of Microsoft Access objects, Data Access Objects (DAO), and objects from any other application that exposes its objects to Microsoft Access. You can also add a Collection object to a collection defined by a Collection object. The collection can also contain user-defined objects that you create in Microsoft Access. For example, you can create user-defined objects with custom methods and properties from a form module or report module. Then you can add these objects to a collection defined by a Collection object, and manipulate them as a set. Example This example creates a Collection object (MyClasses), and then creates a dialog box in which users can add objects to the collection. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the General section of another module, and then start it with the statement ClassNamer in another procedure. (This example only works with host applications that support classes.)
Sub ClassNamer() Dim MyClasses As New Collection ' Create a Collection object. Dim Num ' Counter for individualizing keys. Dim Msg As String ' Variable to hold prompt string. Dim TheName, MyObject, NameList ' Variants to hold information. Do Dim Inst As New Class1 ' Create a new instance of Class1. Num = Num + 1 ' Increment Num, then get a name. Msg = "Please enter a name for this object." & Chr(13) _ & "Press Cancel to see names in collection." TheName = InputBox(Msg, "Name the Collection Items") Inst.InstanceName = TheName ' Put name in object instance. ' If user entered name, add it to the collection. If Inst.InstanceName <> "" Then ' Add the named object to the collection. MyClasses.Add item := Inst, key := CStr(Num) End If ' Clear the current reference in preparation for next one. Set Inst = Nothing

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 37 of 1081

Loop Until TheName = "" For Each MyObject In MyClasses ' Create list of names. NameList = NameList & MyObject.InstanceName & Chr(13) Next MyObject ' Display the list of names in a message box. MsgBox NameList, , "Instance Names In MyClasses Collection" For Num = 1 To MyClasses.Count MyClasses.Remove 1 Next End Sub ' Remove name from the collection. ' Since collections are reindexed ' automatically, remove the first ' member on each iteration.

Command Function
Description Returns the argument portion of the command line used to launch Microsoft Visual Basic or an executable program developed with Visual Basic. Syntax Command Remarks When Visual Basic is launched from the command line, any portion of the command line that follows /cmd is passed to the program as the command-line argument. In the following example, cmdlineargs represents the argument information returned by the Command function.
VB /cmd cmdlineargs

For applications developed with Visual Basic and compiled to an .exe file, Command returns any arguments that appear after the name of the application on the command line. For example:
MyApp cmdlineargs

To find how command line arguments can be changed in the user interface of the application you're using, search Help for "command line arguments." Specifics (Microsoft Access) To change a command-line argument once a database has been opened, click Options on the Tools menu. On the Advanced tab of the Options dialog box, enter a new argument in the Command-Line Arguments box. The Command function will now return the new argument you've entered. When the Command function is used anywhere other than in Visual Basic code in a module, you must include empty parentheses after the function. For example, to use the Command function in a text box on a form, you would set the ControlSource property of the text box to an expression like the following:
=Command()

Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 38 of 1081

This example uses the Command function to get the command line arguments in a function that returns them in a Variant containing an array.
Function GetCommandLine(Optional MaxArgs) 'Declare variables. Dim C, CmdLine, CmdLnLen, InArg, I, NumArgs 'See if MaxArgs was provided. If IsMissing(MaxArgs) Then MaxArgs = 10 'Make array of the correct size. ReDim ArgArray(MaxArgs) NumArgs = 0: InArg = False 'Get command line arguments. CmdLine = Command() CmdLnLen = Len(CmdLine) 'Go thru command line one character 'at a time. For I = 1 To CmdLnLen C = Mid(CmdLine, I, 1) 'Test for space or tab. If (C <> " " And C <> vbTab) Then 'Neither space nor tab. 'Test if already in argument. If Not InArg Then 'New argument begins. 'Test for too many arguments. If NumArgs = MaxArgs Then Exit For NumArgs = NumArgs + 1 InArg = True End If 'Add character to current argument. ArgArray(NumArgs) = ArgArray(NumArgs) + C Else 'Found a space or tab. 'Set InArg flag to False. InArg = False End If Next I 'Resize array just enough to hold arguments. ReDim Preserve ArgArray(NumArgs) 'Return Array in Function name. GetCommandLine = ArgArray() End Function

Comparison Operators
Description Used to compare expressions. Syntax result = expression1 comparisonoperator expression2 result = object1 Is object2 result = string Like pattern Comparison operators have these parts

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 39 of 1081

Part

Description

result

Required; any numeric variable.

expression

Required; any expression.

comparisonoperator

Required; any comparison operator.

(continued) Part Description

object

Required; any object name.

string

Required; any string expression.

pattern

Required; any string expression or range of characters.

Remarks The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null Operator True if False if Null if

< (Less than)

expression1 < expression2

expression1 >= expression2

expression1 or expression2 = Null

<= (Less than or equal to)

expression1 <= expression2

expression1 > expression2

expression1 or expression2 = Null

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 40 of 1081

> (Greater than)

expression1 > expression2

expression1 <= expression2

expression1 or expression2 = Null

>= (Greater than or equal to)

expression1 >= expression2

expression1 < expression2

expression1 or expression2 = Null

= (Equal to)

expression1 = expression2

expression1 <> expression2

expression1 or expression2 = Null

<> (Not equal to)

expression1 <> expression2

expression1 = expression2

expression1 or expression2 = Null

Note The Is and Like operators have specific comparison functionality that differs from the operators in the table. When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings. The following table shows how the expressions are compared or the result when either expression is not a Variant If Then

Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, Currency, or Decimal)
Both expressions are String

Perform a numeric comparison.

Perform a string comparison.

One expression is a numeric data type and the other is a Variant that is, or can be, a number

Perform a numeric comparison.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 41 of 1081

One expression is a numeric data type and the other is a string Variant that can't be converted to a number

A Type Mismatch error occurs.

One expression is a String and the other is any Variant except a Null

Perform a string comparison.

(continued) One expression is Empty and the other is a numeric data type Perform a numeric comparison, using 0 as the Empty expression.

One expression is Empty and the other is a String

Perform a string comparison, using a zerolength string (" ") as the Empty expression.

If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared. The following table shows how the expressions are compared or the result from the comparison, depending on the underlying type of the Variant If Then

Both Variant expressions are numeric

Perform a numeric comparison.

Both Variant expressions are strings

Perform a string comparison.

One Variant expression is numeric and the other is a string

The numeric expression is less than the string expression.

One Variant expression is Empty and the other is numeric

Perform a numeric comparison, using 0 as the Empty expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 42 of 1081

One Variant expression is Empty and the other is a string

Perform a string comparison, using a zerolength string ("") as the Empty expression.

Both Variant expressions are Empty

The expressions are equal.

When a Single is compared to a Double, the Double is rounded to the precision of the Single. If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency. Similarly, when a Decimal is compared with a Single or Double, the Single or Double is converted to a Decimal. For Currency, any fractional value less than .0001 may be lost; for Decimal, any fractional value less than 1E-28 may be lost, or an overflow error can occur. Such fractional value loss may cause two values to compare as equal when they are not. See Also Is operator, Like operator, Operator precedence, Option Compare statement. Example This example shows various uses of comparison operators, which you use to compare expressions.
Dim MyResult, Var1, Var2 MyResult = (45 < 35) MyResult = (45 = 45) MyResult = (4 <> 3) MyResult = ("5" > "4") Var1 = "5": Var2 = 4 MyResult = (Var1 > Var2) Var1 = 5: Var2 = Empty MyResult = (Var1 > Var2) Var1 = 0: Var2 = Empty MyResult = (Var1 = Var2) ' Returns False. ' Returns True. ' Returns True. ' Returns True. ' Initialize variables. ' Returns True. ' Returns True. ' Returns True.

Const Statement
Description Declares constants for use in place of literal values. Syntax [Public | Private] Const constname [As type] = expression The Const statement syntax has these parts

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 43 of 1081

Part

Description

Public

Optional. Keyword used at module level to declare constants that are available to all procedures in all modules. Not allowed in procedures.

Private

Optional. Keyword used at module level to declare constants that are available only within the module where the declaration is made. Not allowed in procedures.

constname

Required. Name of the constant; follows standard variable naming conventions.

type

Optional. Data type of the constant; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or Variant. Use a separate As type clause for each constant being declared.

expression

Required. Literal, other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks Constants are private by default. Within procedures, constants are always private; their visibility can't be changed. In standard modules, the default visibility of module-level constants can be changed using the Public keyword. In class modules, however, constants can only be private and their visibility can't be changed using the Public keyword. To combine several constant declarations on the same line, separate each constant assignment with a comma. When constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them. You can't use variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr) in expressions assigned to constants. Note Constants can make your programs self-documenting and easy to modify. Unlike variables, constants can't be inadvertently changed while your program is running. If you don't explicitly declare the constant type using As type, the constant has the data type that is most appropriate for expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 44 of 1081

Constants declared in a Sub, Function, or Property procedure are local to that procedure. A constant declared outside a procedure is defined throughout the module in which it is declared. You can use constants anywhere you can use an expression. See Also #Const directive, Deftype statements, Function statement, Let statement, Property Get statement, Property Let statement, Property Set statement, Sub statement. Specifics (Microsoft Access) A constant in a Microsoft Access standard module is private by default. If you precede a constant with the keyword Public, however, it is then available to other modules in the current database. It is also available to modules that reference the current database. A constant defined in a class module is always private to that module, and can't be made public by using the Public keyword. Example This example uses the Const statement to declare constants for use in place of literal values. Public constants occur in the General section of a standard module, rather than a class module. Private constants can go in the General section of any type of module.
' Constants are Private by default. Const MyVar = 459 ' Declare Public constant. Public Const MyString = "HELP" ' Declare Private Integer constant. Private Const MyInt As Integer = 5 ' Declare multiple constants on same line. Const MyStr = "Hello", MyDouble As Double = 3.4567

Example (Microsoft Access) In Microsoft Access, you cannot declare public constants in the Declarations section of a class module. Constants in a class module must be private. You can declare both public and private constants in the Declarations section of a standard module.
' In class module. Const conCommission As Single = .08 ' In standard module. Const conErrorNumber As Integer = 91 Public Const conAddress As String = "8421 58th Avenue, College Park, MD"

Cos Function
Description Returns a Double specifying the cosine of an angle. Syntax

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 45 of 1081

Cos(number) The required number argument is a Double or any valid numeric expression that expresses an angle in radians. Remarks The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range 1 to 1. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. See Also Atn function, Sin function, Tan function. Example This example uses the Cos function to return the cosine of an angle.
Dim MyAngle, MySecant MyAngle = 1.3 MySecant = 1 / Cos(MyAngle) ' Define angle in radians. ' Calculate secant.

Count Property
Applies To Collection object, LinkedWindows collection, Windows collection. Description Returns a Long (Long Integer) containing the number of objects in a collection. Read-only. See Also Add method, Item method, Item method ("Extensibility Object Model Language Reference"), Remove method. Example This example uses the Collection object's Count property to specify how many iterations are required to remove all the elements of the collection called MyClasses. When collections are numerically indexed, the base is 1 by default. Since collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration.
Dim Num, MyClasses For Num = 1 To MyClasses.Count ' Remove name from the collection.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 46 of 1081

MyClasses.Remove 1 Next

' Default collection numeric indexes ' begin at 1.

CreateObject Function
Description Creates and returns a reference to an ActiveX object. Syntax CreateObject(class) The class argument uses the syntax appname.objecttype and has these parts Part Description

appname

Required; Variant (String). The name of the application providing the object.

objecttype

Required; Variant (String). The type or class of object to create.

Remarks Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object. To create an ActiveX object, assign the object returned by CreateObject to an object variable:
' Declare an object variable to hold the object ' reference. Dim as Object causes late binding. Dim ExcelSheet As Object Set ExcelSheet = CreateObject("Excel.Sheet")

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. Once an object is created, you reference it in code using the object variable you defined. In the following example, you access properties and methods of the new object using the object variable, ExcelSheet, and other Microsoft Excel objects, including the Application object and the Cells collection.
' Make Excel visible through the Application object. ExcelSheet.Application.Visible = True ' Place some text in the first cell of the sheet. ExcelSheet.Cells(1, 1).Value = "This is column A, row 1" ' Save the sheet to C:\test.doc directory. ExcelSheet.SaveAs "C:\ TEST.DOC" ' Close Excel with the Quit method on the Application object. ExcelSheet.Application.Quit ' Release the object variable. Set ExcelSheet = Nothing

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 47 of 1081

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding; that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:
Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.WorkSheet Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets(1)

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration. You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to an Excel.Application object:
Call MySub (CreateObject("Excel.Application"))

Note Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function. If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. See Also GetObject function, Set statement. Example This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.
Dim xlApp As Object ' Declare variable to hold the reference.

Set xlApp = CreateObject("excel.application") ' You may have to set Visible property to True ' if you want to see the application. xlApp.Visible = True ' Use xlApp to access Microsoft Excel's ' other objects. xlApp.Quit ' When you finish, use the Quit method to close Set xlApp = Nothing ' the application, then release the reference.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 48 of 1081

CurDir Function
Description Returns a Variant (String) representing the current path. Syntax CurDir[(drive)] The optional drive argument is a string expression that specifies an existing drive. If no drive is specified or if drive is a zero-length string (" "), CurDir returns the path for the current drive. See Also ChDir statement, ChDrive statement, MkDir statement, RmDir statement. Specifics (Macintosh) The optional drive argument is a string expression that specifies an existing drive. CurDir ignores any drive specified and simply returns the path for the current drive. Example This example uses the CurDir function to return the current path.
' In Microsoft Windows: ' Assume current path on C drive is "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL". ' Assume C is the current drive. Dim MyPath MyPath = CurDir ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("C") ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("D") ' Returns "D:\EXCEL". ' On the Macintosh: ' Drive letters are ignored. Path for current drive is returned. ' Assume current path on HD Drive is "HD:MY FOLDER". ' Assume HD is the current drive. Drive MD also exists on the machine. Dim MyPath MyPath = CurDir ' Returns "HD:MY FOLDER". MyPath = CurDir("HD") ' Returns "HD:MY FOLDER". MyPath = CurDir("MD") ' Returns "HD:MY FOLDER".

Currency Data Type


Description Currency variables are stored as 64-bit (8-byte) numbers in an integer format, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. This representation provides a range of 922,337,203,685,477.5808 to 922,337,203,685,477.5807. The type-declaration character for Currency is the at sign (@).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 49 of 1081

The Currency data type is useful for calculations involving money and for fixed -point calculations in which accuracy is particularly important. See Also Data type summary, Deftype statements, Long data type.

CVErr Function
Description Returns a Variant of subtype Error containing an error number specified by the user. Syntax CVErr(errornumber) The required errornumber argument is any valid error number. Remarks Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely your function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take. Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the return value of CVErr to a variable that is not a Variant. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type. See Also Data type summary, IsError function. Example This example uses the CVErr function to return a Variant whose VarType is vbError (10). The user-defined function CalculateDouble returns an error if the argument passed to it isn't a number. You can use CVErr to return user-defined errors from user-defined procedures or to defer handling of a run-time error. Use the IsError function to test if the value represents an error.
' Call CalculateDouble with an error-producing argument. Sub Test() Debug.Print CalculateDouble("345.45robert") End Sub ' Define CalculateDouble Function procedure. Function CalculateDouble(Number) If IsNumeric(Number) Then CalculateDouble = Number * 2 ' Return result. Else

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 50 of 1081

CalculateDouble = CVErr(2001) End If ' number. End Function

' Return a user-defined error

Example (Microsoft Excel) This example inserts the seven cell error values into cells A1:A7 on Sheet1.
myArray = Array(xlErrDiv0, xlErrNA, xlErrName, xlErrNull, _ xlErrNum, xlErrRef, xlErrValue) For i = 1 To 7 Worksheets("Sheet1").Cells(i, 1).Value = CVErr(myArray(i - 1)) Next i

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.
Worksheets("Sheet1").Activate If IsError(ActiveCell.Value) Then errval = ActiveCell.Value Select Case errval Case CVErr(xlErrDiv0) MsgBox "#DIV/0! error" Case CVErr(xlErrNA) MsgBox "#N/A error" Case CVErr(xlErrName) MsgBox "#NAME? error" Case CVErr(xlErrNull) MsgBox "#NULL! error" Case CVErr(xlErrNum) MsgBox "#NUM! error" Case CVErr(xlErrRef) MsgBox "#REF! error" Case CVErr(xlErrValue) MsgBox "#VALUE! error" Case Else MsgBox "This should never happen!!" End Select End If

Data Type Summary


Description 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

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 51 of 1081

Data type

Storage size

Range

Integer

2 bytes

32,768 to 32,767

Long (Long Integer)

4 bytes

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

Single (singleprecision floatingpoint)

4 bytes

3.402823E38 to 1.401298E45 for negative values; 1.401298E45 to 3.402823E38 for positive values

Double (doubleprecision floatingpoint)

8 bytes

1.79769313486232E308 to 4.94065645841247E324 for negative values; 4.94065645841247E324 to 1.79769313486232E308 for positive values

Currency (scaled integer)

8 bytes

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

Decimal

14 bytes

+/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

Date

8 bytes

January 1, 100 to December 31, 9999

Object

4 bytes

Any Object reference

String (variablelength)

10 bytes + string length

0 to approximately 2 billion

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 52 of 1081

String (fixedlength)

Length of string

1 to approximately 65,400

Variant (with numbers)

16 bytes

Any numeric value up to the range of a Double

Variant (with characters)

22 bytes + string length

Same range as for variable-length String

User-defined (using Type)

Number required by elements

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

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. See Also Boolean data type, Byte data type, Currency data type, Date data type, Decimal data type, Deftype statements, Double data type, Int, Fix functions, Integer data type, Long data type, Object data type, Single data type, String data type, Type statement, User-defined data type, Variant data type.

Date Data Type


Description 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# 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

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 53 of 1081

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. See Also Data type summary, Deftype statements, Double data type, Variant data type.

Date Function
Description Returns a Variant (Date) containing the current system date. Syntax Date Remarks To set the system date, use the Date statement. See Also Date statement, Format function, Now function, Time function, Time statement. Specifics (Microsoft Access) You can insert the current date on a form or report by clicking Date and Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to an expression containing the Date function. This expression will vary according to the format you have chosen to display the date. This command is available only in form Design view and report Design view. You can also use the Date function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than a Visual Basic module, as in the expression Date(). Example This example uses the Date function to return the current system date.
Dim MyDate MyDate = Date ' MyDate contains the current system date.

Example (Microsoft Access) You can use the Date function in a calculated control by setting the ControlSource property of the control as in the following example.
=Date()

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 54 of 1081

You can also use the Date function to set criteria for a query. For example, if you have an Orders table that contains an OrderDate field, you can create a query on the Orders table to return all records that have an OrderDate between 4-1-95 and today's date. Enter the following in the Criteria cell under the OrderDate field.
Between #4-1-95# and Date()

Date Statement
Description Sets the current system date. Syntax Date = date For systems running Microsoft Windows 95, the required date specification must be a date from January 1, 1980 through December 31, 2099. For systems running Microsoft Windows NT, date must be a date from January 1, 1980 through December 31, 2079. See Also Date function, Time function, Time statement. Specifics (Macintosh) For the Macintosh, date must be a date from January 1, 1904 through February 5, 2040. Example This example uses the Date statement to set the computer system date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.
Dim MyDate MyDate = #February 12, 1985# Date = MyDate ' Assign a date. ' Change system date.

DateAdd Function
Description Returns a Variant (Date) containing a date to which a specified time interval has been added. Syntax DateAdd(interval, number, date)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 55 of 1081

The DateAdd function syntax has these named arguments Part Description

interval

Required. String expression that is the interval of time you want to add.

number

Required. Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).

date

Required. Variant (Date) or literal representing date to which the interval is added.

Settings The interval argument has these settings Setting Description

yyyy

Year

Quarter

Month

Day of year

Day

Weekday

ww

Week

Hour

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 56 of 1081

Minute

Second

Remarks You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now. To add days to date, you can use Day of Year ("y"), Day ("d"), or Weekday ("w"). The DateAdd function won't return an invalid date. The following example adds one month to January 31:
DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb96 because 1996 is a leap year. If the calculated date would precede the year 100 (that is, you subtract more years than are in date), an error occurs. If number isn't a Long value, it is rounded to the nearest whole number before being evaluated. See Also DateDiff function, DatePart function, Day function, Format function, Now function, Weekday function, Year function. Example This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in the future.
Dim FirstDate As Date ' Declare variables. Dim IntervalType As String Dim Number As Integer Dim Msg IntervalType = "m" ' "m" specifies months as interval. FirstDate = InputBox("Enter a date") Number = InputBox("Enter number of months to add") Msg = "New date: " & DateAdd(IntervalType, Number, FirstDate) MsgBox Msg

Example (Microsoft Access) The following example shows how you can create a calculated control by using the DateAdd function to display the date by which a particular order must be shipped in this case, thirty days after the OrderDate. Suppose you have a form based on an Orders table, with a field called OrderDate. You can create another text box on the form to display the shipping date by setting the ControlSource property of this text box as in the following example.
=DateAdd("d", 30, [OrderDate])

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 57 of 1081

DateDiff Function
Description Returns a Variant (Long) specifying the number of time intervals between two specified dates. Syntax DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]]) The DateDiff function syntax has these named arguments Part Description

interval

Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.

date1, date2

Required; Variant (Date). Two dates you want to use in the calculation.

firstdayofweek

Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.

firstweekofyear

Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings The interval argument has these settings Setting Description

yyyy

Year

Quarter

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 58 of 1081

Month

Day of year

Day

Weekday

ww

Week

Hour

Minute

Second

The firstdayofweek argument has these settings Constant Value Description

vbUseSystem

Use the NLS API setting.

vbSunday

Sunday (default)

vbMonday

Monday

vbTuesday

Tuesday

vbWednesday

Wednesday

vbThursday

Thursday

vbFriday

Friday

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 59 of 1081

vbSaturday

Saturday

The firstweekofyear argument has these settings Constant Value Description

vbUseSystem

Use the NLS API setting.

vbFirstJan1

Start with week in which January 1 occurs (default).

vbFirstFourDays

Start with the first week that has at least four days in the new year.

vbFirstFullWeek

Start with first full week of the year.

Remarks You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year. To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday. If date1 refers to a later point in time than date2, the DateDiff function returns a negative number. The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols. If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in double quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years. When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed. See Also DateAdd function, DatePart function, Day function, Format function, Now function, Weekday

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 60 of 1081

function, Year function. Example This example uses the DateDiff function to display the number of days between a given date and today.
Dim TheDate As Date ' Declare variables. Dim Msg TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg

Example (Microsoft Access) The following examples use the DateDiff function to calculate the number of calendar weeks between the first of the year and today, and the number of days since February 1, 1995 respectively.
Debug.Print DateDiff("ww", "1-1", Now()) Debug.Print DateDiff("y", #1-Feb-1995#, Now())

The next example shows how to use the DateDiff function in a query expression. Suppose you have an Orders table that contains an OrderDate field and a ShippedDate field. You can create a calculated field in a query to display the time elapsed between an order date and a shipped date for each order. In the Query window, create a new query by adding the Orders table and dragging the OrderID field to the query design grid. In an empty Field cell, enter the following to create a calculated field.
DaysElapsed: DateDiff("y", [OrderDate], [ShippedDate])

DatePart Function
Description Returns a Variant (Integer) containing the specified part of a given date. Syntax DatePart(interval, date[,firstdayofweek[, firstweekofyear]]) The DatePart function syntax has these named arguments Part Description

interval

Required. String expression that is the interval of time you want to return.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 61 of 1081

date

Required. Variant (Date) value that you want to evaluate.

firstdayofweek

Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.

firstweekofyear

Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings The interval argument has these settings Setting Description

yyyy

Year

Quarter

Month

Day of year

Day

Weekday

ww

Week

Hour

Minute

Second

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 62 of 1081

The firstdayofweek argument has these settings Constant Value Description

vbUseSystem

Use the NLS API setting.

vbSunday

Sunday (default)

vbMonday

Monday

vbTuesday

Tuesday

vbWednesday

Wednesday

vbThursday

Thursday

vbFriday

Friday

vbSaturday

Saturday

The firstweekofyear argument has these settings Constant Value Description

vbUseSystem

Use the NLS API setting.

vbFirstJan1

Start with week in which January 1 occurs (default).

vbFirstFourDays

Start with the first week that has at least four days in the new year.

vbFirstFullWeek

Start with first full week of the year.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 63 of 1081

Remarks You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour. The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols. If date is a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed in double quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years. See Also DateAdd function, DateDiff function, Day function, Format function, Now function, Weekday function, Year function. Example This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.
Dim TheDate As Date ' Declare variables. Dim Msg TheDate = InputBox("Enter a date:") Msg = "Quarter: " & DatePart("q", TheDate) MsgBox Msg

Example (Microsoft Access) The following example uses the DatePart function to specify criteria for a select query. For example, suppose you want to create a query based on an Orders table to list all orders placed in the first quarter of 1996. Assuming your Orders table has a OrderID field and an OrderDate field, you can drag the OrderID field to the first cell in the query design grid, and enter the following in the Criteria cell beneath it.
(DatePart("q", [OrderDate]) = 1) and (DatePart("yyyy", [OrderDate]) = 1996)

DateSerial Function
Description Returns a Variant (Date) for a specified year, month, and day. Syntax DateSerial(year, month, day) The DateSerial function syntax has these named arguments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 64 of 1081

Part

Description

year

Required; Integer. Number between 100 and 9999, inclusive, or a numeric expression.

month

Required; Integer. Any numeric expression.

day

Required; Integer. Any numeric expression.

Remarks To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the accepted range for the unit; that is, 1 31 for days and 1 12 for months. However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date. The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 - 1), two months before August (8 - 2), 10 years before 1990 (1990 - 10); in other words, May 31, 1980.
DateSerial(1990 - 10, 8 - 2, 1 - 1)

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900 1999. For all other year arguments, use a four-digit year (for example, 1800). When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on where in the year it is applied. If any single argument is outside the range 32,768 to 32,767, an error occurs. If the date specified by the three arguments falls outside the acceptable range of dates, an error occurs. See Also Date function, Date statement, DateValue function, Day function, Month function, Now function, TimeSerial function, TimeValue function, Weekday function, Year function. Example This example uses the DateSerial function to return the date for the specified year, month, and day.
Dim MyDate ' MyDate contains the date for February 12, 1969. MyDate = DateSerial(1969, 2, 12) ' Return a date.

Example (Microsoft Access)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 65 of 1081

The following example uses the DateSerial function together with the Year, Month, and Day functions to return the number of days in a month. You can pass either a date or a string to the DaysInMonth function.
Function DaysInMonth(dteInput As Date) As Integer Dim intDays As Integer ' Add one month, subtract dates to find difference. intDays = DateSerial(Year(dteInput), Month(dteInput) + 1, Day(dteInput)) _ - DateSerial(Year(dteInput), Month(dteInput), Day(dteInput)) DaysInMonth = intDays Debug.Print intDays End Function

The following Sub procedure shows several different ways that you might call the DaysInMonth function.
Sub CallDaysInMonth() Dim intDays As Integer intDays = DaysInMonth(#4/1/96#) intDays = DaysInMonth("4-1-96") intDays = DaysInMonth("April 1, 1996") End Sub

DateValue Function
Description Returns a Variant (Date). Syntax DateValue(date) The required date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range. Remarks If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991. If the year part of date is omitted, DateValue uses the current year from your computer's system date. If the date argument includes time information, DateValue doesn't return it. However, if date includes invalid time information (such as "89:98"), an error occurs. See Also Date function, Date statement, DateSerial function, Day function, Month function, Now function,

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 66 of 1081

TimeSerial function, TimeValue function, Weekday function, Year function. Example This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant or Date variable, for example, MyDate = #2/12/69#.
Dim MyDate MyDate = DateValue("February 12, 1969") ' Return a date.

Day Function
Description Returns a Variant (Integer) specifying a whole number between 1 and 31, inclusive, representing the day of the month. Syntax Day(date) The required date argument is any Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned. See Also Date function, Date statement, Hour function, Minute function, Month function, Now function, Second function, Weekday function, Year function. Example This example uses the Day function to obtain the day of the month from a specified date. In the development environment, the date literal is displayed in short format using the locale settings of your code.
Dim MyDate, MyDay MyDate = #February 12, 1969# MyDay = Day(MyDate) ' Assign a date. ' MyDay contains 12.

Example (Microsoft Access) See the DateSerial function example (Microsoft Access).

DDB Function
Description Returns a Double specifying the depreciation of an asset for a specific time period using the double-declining balance method or some other method you specify.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 67 of 1081

Syntax DDB(cost, salvage, life, period[, factor]) The DDB function has these named arguments Part Description

cost

Required. Double specifying initial cost of the asset.

salvage

Required. Double specifying value of the asset at the end of its useful life.

life

Required. Double specifying length of useful life of the asset.

period

Required. Double specifying period for which asset depreciation is calculated.

factor

Optional. Variant specifying rate at which the balance declines. If omitted, 2 (doubledeclining method) is assumed.

Remarks The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period and decreases in successive periods. The life and period arguments must be expressed in the same units. For example, if life is given in months, period must also be given in months. All arguments must be positive numbers. The DDB function uses the following formula to calculate depreciation for a given period: Depreciation / period = ((cost salvage) * factor) / life See Also FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost (InitCost), the salvage value at the end of the asset's useful life

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 68 of 1081

(SalvageVal), the total life of the asset in years (LifeTime), and the period in years for which the depreciation is calculated (Depr).
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr Const YRMOS = 12 ' Number of months in a year. Fmt = "###,##0.00" InitCost = InputBox("What's the initial cost of the asset?") SalvageVal = InputBox("Enter the asset's value at end of its life.") MonthLife = InputBox("What's the asset's useful life in months?") Do While MonthLife < YRMOS ' Ensure period is >= 1 year. MsgBox "Asset life must be a year or more." MonthLife = InputBox("What's the asset's useful life in months?") Loop LifeTime = MonthLife / YRMOS ' Convert months to years. If LifeTime <> Int(MonthLife / YRMOS) Then LifeTime = Int(LifeTime + 1) ' Round up to nearest year. End If DepYear = CInt(InputBox("Enter year for depreciation calculation.")) Do While DepYear < 1 Or DepYear > LifeTime MsgBox "You must enter at least 1 but not more than " & LifeTime DepYear = InputBox("Enter year for depreciation calculation.") Loop Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear) MsgBox "The depreciation for year " & DepYear & " is " & _ Format(Depr, Fmt) & "."

Deactivate Event
See Activate, Deactivate Events.

Debug Object
Description The Debug object sends output to the Immediate window at run time. Methods Print method.

Decimal Data Type


Description Decimal variables are stored as 96-bit (12-byte) unsigned integers scaled by a variable power of 10. The power of 10 scaling factor specifies the number of digits to the right of the decimal point, and ranges from 0 to 28. With a scale of 0 (no decimal places), the largest possible value is +/-79,228,162,514,264,337,593,543,950,335. With a 28 decimal places, the largest value is +/-7.9228162514264337593543950335 and the smallest, non -zero value is +/0.0000000000000000000000000001. Note At this time the Decimal data type can only be used within a Variant, that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 69 of 1081

See Also Data type summary.

Declare Statement
Description Used at module level to declare references to external procedures in a dynamic-link library (DLL). Syntax 1 [Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])] Syntax 2 [Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type] The Declare statement syntax has these parts Part Description

Public

Optional. Used to declare procedures that are available to all other procedures in all modules.

Private

Optional. Used to declare procedures that are available only within the module where the declaration is made.

Sub

Optional (either Sub or Function must appear). Indicates that the procedure doesn't return a value.

Function

Optional (either Sub or Function must appear). Indicates that the procedure returns a value that can be used in an expression.

name

Required. Any valid procedure name. Note that DLL entry points are case sensitive.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 70 of 1081

Lib

Required. Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations.

libname

Required. Name of the DLL or code resource that contains the declared procedure.

Alias

Optional. Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed by the DLL naming convention.

aliasname

Optional. Name of the procedure in the DLL or code resource. If the first character is not a number sign (#), aliasname is the name of the procedure's entry point in the DLL. If (#) is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.

arglist

Optional. List of variables representing arguments that are passed to the procedure when it is called.

(continue) Part Description

type

Optional. Data type of the value returned by a Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), or Variant, a user-defined type, or an object type.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 71 of 1081

The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] Part Description

Optional

Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. The ParamArray keyword can't be used with ByVal, ByRef, or Optional.

varname

Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.

()

Required for array variables. Indicates that varname is an array.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 72 of 1081

Remarks For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following arglist to specify the return type of the function. Within arglist, you can use an As clause to specify the data type of any of the arguments passed to the procedure. In addition to specifying any of the standard data types, you can specify As Any in arglist to inhibit type checking and allow any data type to be passed to the procedure. Empty parentheses indicate that the Sub or Function procedure has no arguments and that Visual Basic should ensure that none are passed. In the following example, First takes no arguments. If you use arguments in a call to First, an error occurs:
Declare Sub First Lib "MyLib" ()

If you include an argument list, the number and type of arguments are checked each time the procedure is called. In the following example, First takes one Long argument:
Declare Sub First Lib "MyLib" (X As Long)

Note You can't have fixed-length strings in the argument list of a Declare statement; only variable-length strings can be passed to procedures. Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed. Note The vbNullString constant is used when calling external procedures, where the external procedure requires a string whose value is zero. This is not the same thing as a zero-length string (" "). See Also Call statement, Function statement, LastDLLError property, Sub statement. Specifics (Macintosh) On the Power, the Declare syntax is the same as in Windows, except that the CDecl keyword can be used to indicate that the procedure uses C language argument order, naming conventions, and calling conventions: [Public | Private ] Declare Function name [CDecl] Lib "libname" [Alias "aliasname"] [([arglist])] [As type] The Alias keyword indicates that the procedure being called is in a Macintosh code resource. This is useful when the external procedure name is the same as a keyword. Use the aliasname to specify the code resource type as follows: "[resourcetype]$[resourcename]" The resourcetype is any valid 4-character constant. If omitted, the default resourcetype is CODE. The resourcename is the procedure name in the code resource. If resourcename is omitted, it is assumed to be the same as name. On the Power Macintosh, the Declare statement supports calls into native code for code fragments only. Calling into code resources is also supported, but only in 68000 emulation mode.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 73 of 1081

When used on the Power Macintosh, the Declare statement syntax is as follows:
Declare Function MyFunction Lib "hd:system folder:extensions: _ MyCodeFragment" Alias "MyFunction" () As Long

For both code fragments and code resources, a full or partial path name may be specified for the Lib clause. If the specified Lib clause is ambiguous, it is resolved as follows: If the file contains a 'cfrg' resource, it's treated as a code fragment. If it doesn't contain a 'cfrg' resource, it is treated as a file containing code resources. This allows the creation of "fat" code fragments, that is, files that contain both code fragments and 68000 code resources. When running Visual Basic for Applications on a 68000 Macintosh, the code resource is used. When running it on a Power Macintosh, the native code fragment is used. The Macintosh toolbox can be accessed on the Power Macintosh using a declaration into the system code fragment. Specifics (Microsoft Access) In Microsoft Access, Declare statements are public by default. In a standard module, a public Declare statement is available to all procedures in the current database and in any referencing databases. You can preface a Declare statement with the Private keyword to ensure that it is not available outside of the current module. To use a Declare statement in a class module, you must precede the statement with the Private keyword. If you fail to include the Private keyword, Microsoft Access generates a compile-time error. Example This example shows how the Declare statement is used at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL) or Macintosh code resource. You can place the Declare statements in class modules if the Declare statements are Private.
' In Microsoft Windows (16-bit): Declare Sub MessageBeep Lib "User" (ByVal N As Integer) ' Assume SomeBeep is an alias for the procedure name. Declare Sub MessageBeep Lib "User" Alias "SomeBeep"(ByVal N As Integer) ' Use an ordinal in the Alias clause to call GetWinFlags. Declare Function GetWinFlags Lib "Kernel" Alias "#132"() As Long ' In 32-bit Microsoft Windows systems, specify the library USER32.DLL, ' rather than USER.DLL. You can use conditional compilation to write ' code that can run on either Win32 or Win16. #If Win32 Then Declare Sub MessageBeep Lib "User32" (ByVal N As Long) #Else Declare Sub MessageBeep Lib "User" (ByVal N As Integer) #End If ' On the Macintosh: Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _ As Integer) ' Use a code resource in the Alias clause. Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "XTST$MyAlert" _ (ByVal N As Integer) ' If the code-resource type specifier has only 3 characters, be sure to ' leave a blank space where the final character would normally be.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 74 of 1081

Declare Sub MessageAlert Lib "MyHd:AnAlert" Alias "COD $AnAlert" _ (ByVal N As Integer)

Example (Microsoft Access) In Microsoft Access, you can use the Declare statement at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). A Declare statement is public by default. In order to include a Declare statement in a class module, precede it with the Private keyword. The following example references a procedure in a DLL, then calls that procedure from Visual Basic.
' In standard module. Declare Sub MessageBeep Lib "User32" (ByVal intN As Integer) ' In class module. Private Declare Sub MessageBeep Lib "User32" (ByVal intN As Integer) ' Once you have referenced procedure in DLL with Declare ' statement, you can call that procedure normally from code. Sub SystemBeep(intBeeps As Integer, sngPause As Single) Dim intI As Integer Dim sngStart As Single For intI = 1 To intBeeps ' Call system function. Call MessageBeep(intBeeps) ' Get start time. sngStart = Timer ' Pause between beeps. Do While Timer < sngStart + sngPause ' Return control to operating system. DoEvents Loop Next intI End Sub

Deftype Statements
Description Used at module level to set the default data type for variables, arguments passed to procedures, and the return type for Function and Property Get procedures whose names start with the specified characters. Syntax DefBool letterrange[, letterrange] . . . DefByte letterrange[, letterrange] . . . DefInt letterrange[, letterrange] . . . DefLng letterrange[, letterrange] . . . DefCur letterrange[, letterrange] . . . DefSng letterrange[, letterrange] . . .

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 75 of 1081

DefDbl letterrange[, letterrange] . . . DefDec letterrange[, letterrange] . . . DefDate letterrange[, letterrange] . . . DefStr letterrange[, letterrange] . . . DefObj letterrange[, letterrange] . . . DefVar letterrange[, letterrange] . . . The required letterrange argument has the following syntax: letter1[-letter2] The letter1 and letter2 arguments specify the name range for which you can set a default data type. Each argument represents the first letter of the variable, argument, Function procedure, or Property Get procedure name and can be any letter of the alphabet. The case of letters in letterrange isn't significant. Remarks The statement name determines the data type Statement Data Type

DefBool

Boolean

DefByte

Byte

DefInt

Integer

DefLng

Long

DefCur

Currency

DefSng

Single

DefDbl

Double

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 76 of 1081

DefDec

Decimal (not currently supported)

DefDate

Date

DefStr

String

DefObj

Object

DefVar

Variant

For example, in the following program fragment, Message is a string variable:


DefStr A-Q . . . Message = "Out of stack space."

A Deftype statement affects only the module where it is used. For example, a DefInt statement in one module affects only the default data type of variables, arguments passed to procedures, and the return type for Function and Property Get procedures declared in that module; the default data type of variables, arguments, and return types in other modules is unaffected. If not explicitly declared with a Deftype statement, the default data type for all variables, all arguments, all Function procedures, and all Property Get procedures is Variant. When you specify a letter range, it usually defines the data type for variables that begin with letters in the first 128 characters of the character set. However, when you specify the letter range A Z, you set the default to the specified data type for all variables, including variables that begin with international characters from the extended part of the character set (128 255). Once the range A Z has been specified, you can't further redefine any subranges of variables using Deftype statements. Once a range has been specified, if you include a previously defined letter in another Deftype statement, an error occurs. However, you can explicitly specify the data type of any variable, defined or not, using a Dim statement with an As type clause. For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:
DefInt A-Z Dim TaxRate As Double

Deftype statements don't affect elements of user-defined types because the elements must be explicitly declared. See Also Function statement, Let statement, Property Get statement. Example This example shows various uses of the Deftype statements to set default data types of variables and function procedures whose names start with specified characters. The default data

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 77 of 1081

type can be overridden only by explicit assignment using the Dim statement. Deftype statements can only be used at the module level, that is, not within procedures.
' Variable names beginning with A through K default to Integer. DefInt A-K ' Variable names beginning with L through Z default to String. DefStr L-Z CalcVar = 4 ' Initialize Integer. StringVar = "Hello there" ' Initialize String. AnyVar = "Hello" ' Causes "Type mismatch" error. Dim Calc As Double ' Explicitly set the type to Double. Calc = 2.3455 ' Assign a Double. ' Deftype statements also apply to function procedures. CalcNum = ATestFunction(4) ' Call user-defined function. ' ATestFunction function procedure definition. Function ATestFunction(INumber) ATestFunction = INumber * 2 ' Return value is an integer. End Function

DeleteSetting Statement
Description Deletes a section or key setting from an application's entry in the Windows registry. Syntax DeleteSetting appname, section[, key] The DeleteSetting statement syntax has these named arguments Part Description

appname

Required. String expression containing the name of the application or project to which the section or key setting applies.

section

Required. String expression containing the name of the section where the key setting is being deleted. If only appname and section are provided, the specified section is deleted along with all related key settings.

key

Optional. String expression containing the name of the key setting being deleted.

Remarks If all arguments are provided, the specified key setting is deleted. However, the DeleteSetting

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 78 of 1081

statement does nothing if the specified section or key setting does not exist. See Also GetAllSettings function, GetSetting function, SaveSetting statement. Example The following example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the MyApp application, and then uses the DeleteSetting statement to remove them. Because no key argument is specified, the whole section is deleted, including the section name and all its keys.
' Place some settings in the registry. SaveSetting appname := "MyApp", section := "Startup", _ key := "Top", setting := 75 SaveSetting "MyApp","Startup", "Left", 50 ' Remove section and all its settings from registry. DeleteSetting "MyApp", "Startup"

Description Property
Applies To Err object, Reference object ("Extensibility Object Model Language Reference"). Description Returns or sets a string expression containing a descriptive string associated with an object. Read/write. For the Err object, returns or sets a descriptive string associated with an error. Remarks The Description property setting consists of a short description of the error. Use this property to alert the user to an error that you either can't or don't want to handle. When generating a userdefined error, assign a short description of your error to the Description property. If Description isn't filled in, and the value of Number corresponds to a Visual Basic run-time error, the string returned by the Error function is placed in Description when the error is generated. See Also Err object, Error function, HelpContext property, HelpFile property, LastDLLError property, Number property, Source property. Example This example assigns a user-defined message to the Description property of the Err object.
Err.Description = "It was not possible to access an object necessary " _ & "for this operation."

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 79 of 1081

Dim Statement
Description Declares variables and allocates storage space. Syntax Dim [WithEvents] varname[([subscripts])] [As [New] type] [, [WithEvents] varname[([subscripts])] [As [New] type]] . . . The Dim statement syntax has these parts Part Description

WithEvents

Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. Valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.

varname

Required. Name of the variable; follows standard variable naming conventions.

(continue) Part Description

subscripts

Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [, [lower To] upper] . . .

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 80 of 1081

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

New

Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.

type

Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variablelength strings), String * length (for fixedlength strings), Object, Variant, a userdefined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure. Use the Dim statement at module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.
Dim NumberOfEmployees As Integer

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.
Dim X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 81 of 1081

whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs. If you don't specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. Note When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure. See Also Array function, Option Base statement, Private statement, Public statement, ReDim statement, Set statement, Static statement, Type statement. Specifics (Microsoft Access) You can use the New keyword with the Dim statement to declare an object variable of a specific type. If you include the New keyword in your variable declaration, you automatically create a new object and point the object variable to it. If you declare an object variable by using the New keyword, you don't need to use the Set statement. By using the New keyword, you can create an object variable to point to any type of object. The New keyword is used most frequently to create a new instance of a class or to create a new Collection object, as shown in the following example.
' Create object variable and point it to new object. Dim colInstances As New Collection

The following example shows how to use the New keyword to create a new instance of a class.
' Create new instance of class module. Dim obj As New Class1

You can use the New keyword to create a new Microsoft Access object from some components that support Automation. Check the component's documentation to determine whether or not it supports this syntax. For example, from another component, assuming you have established a reference to the Microsoft Access type library, you can create a new Microsoft Access Application object with the following code.
Dim appAccess As New Access.Application

Example This example shows various uses of the Dim statement to declare variables. It also shows the Dim statement being used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.
' AnyValue and MyValue are declared as Variant by default with values ' set to Empty. Dim AnyValue, MyValue

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 82 of 1081

' Explicitly declare a variable of type Integer. Dim Number As Integer ' Multiple declarations on a single line. AnotherVar is of type Variant ' because its type is omitted. Dim AnotherVar, Choice As Boolean, BirthDate As Date ' DayArray is an array of Variants with 51 elements indexed, from ' 0 thru 50, assuming Option Base is set to 0 (default) for ' the current module. Dim DayArray(50) ' Matrix is a two-dimensional array of integers. Dim Matrix(3, 4) As Integer ' MyMatrix is a three-dimensional array of doubles with explicit ' bounds. Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double ' BirthDay is an array of dates with indexes from 1 to 10. Dim BirthDay(1 To 10) As Date ' MyArray is a dynamic array of variants. Dim MyArray()

Dir Function
Description Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive. Syntax Dir[(pathname[, attributes])] The Dir function syntax has these parts Part Description

pathname

Optional. String expression that specifies a file name may include directory or folder, and drive. A zero-length string (" ") is returned if pathname is not found.

attributes

Optional. Constant or numeric expression, whose sum specifies file attributes. If omitted, all files are returned that match pathname.

Settings The attributes argument settings are

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 83 of 1081

Constant

Value

Description

vbNormal

Normal.

vbHidden

Hidden.

(continue) vbSystem 4 System file.

vbVolume

Volume label; if specified, all other attributes are ignored.

vbDirectory

16

Directory or folder.

Note These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values. Remarks Dir supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files. You must specify pathname the first time you call the Dir function, or an error occurs. If you also specify file attributes, pathname must be included. Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (" "). Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs. You can change to a new pathname without retrieving all of the file names that match the current pathname. However, you can't call the Dir function recursively. Calling Dir with the vbDirectory attribute does not continually return subdirectories. Tip Because file names are retrieved in no particular order, you may want to store returned file names in an array and then sort the array. See Also ChDir statement, CurDir function, MacID function. Specifics (Macintosh) In Microsoft Windows, Dir supports the use of multiple character (*) and single character (?)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 84 of 1081

wildcards to specify multiple files. On the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files. Since the Macintosh doesn't support the wildcards, use the file type to identify groups of files. You can use the MacID function to specify file type instead of using the file names. For example, the following statement returns the name of the first TEXT file in the current folder:
Dir("SomePath", MacID("TEXT"))

To iterate over all files in a folder, specify an empty string:


Dir("")

If you use the MacID function with Dir in Microsoft Windows, an error occurs. Any attribute value greater than 256 is considered a MacID value. The following constants aren't available on the Macintosh Constant Value Description

vbSystem

System file

vbVolume

Volume label

The following constant is available only on the Macintosh Constant Value Description

vbAlias

64

Specified file name is an alias.

Example This example uses the Dir function to check if certain files and directories exist. The MacID function may be used on the Macintosh to specify the file type.
Dim MyFile, MyPath, MyName ' In Microsoft Windows: ' Returns "WIN.INI" if it exists. MyFile = Dir("C:\WINDOWS\WIN.INI") ' Returns filename with specified extension. If more than one *.ini ' file exists, the first file found is returned. MyFile = Dir("C:\WINDOWS\*.INI") ' Call Dir again without arguments to return the next *.INI file in the ' same directory. MyFile = Dir ' Return first *.TXT file with a set hidden attribute. MyFile = Dir("*.TXT", vbHidden)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 85 of 1081

' Display the names in C:\ that represent directories. MyPath = "c:\" ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Ignore the current directory and the encompassing directory. If MyName <> "." And MyName <> ".." Then ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then Debug.Print MyName ' Display entry only if it End If ' it represents a directory. End If MyName = Dir ' Get next entry. Loop ' On the Macintosh: ' Use the MacID function to specify file type. ' The following statement returns the first "TEXT" file found in the ' specified directory or folder. MyFile = Dir("HD:MY FOLDER:", MacID("TEXT"))

Do...Loop Statement
Description Repeats a block of statements while a condition is True or until a condition becomes True. Syntax Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop Or, you can use this syntax: Do [statements] [Exit Do] [statements] Loop [{While | Until} condition] The Do Loop statement syntax has these parts Part Description

condition

Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 86 of 1081

statements

One or more statements that are repeated while, or until, condition is True.

Remarks Any number of Exit Do statements may be placed anywhere in the DoLoop as an alternate way to exit a DoLoop. Exit Do is often used after evaluating some condition, for example, IfThen, in which case the Exit Do statement transfers control to the statement immediately following the Loop. When used within nested DoLoop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs. See Also Exit statement, For...Next statement, While...Wend statement. Example This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.
Dim Check, Counter Check = True: Counter = 0 Do ' Outer loop. Do While Counter < 20 Counter = Counter + 1 If Counter = 10 Then Check = False Exit Do End If Loop Loop Until Check = False ' Initialize variables. ' Inner loop. ' Increment Counter. ' If condition is True. ' Set value of flag to False. ' Exit inner loop. ' Exit outer loop immediately.

Example (Microsoft Excel) This example sorts the data in the first column on Sheet1 and then deletes any rows that contain duplicate data.
Worksheets("Sheet1").Range("A1").Sort _ key1:=Worksheets("Sheet1").Range("A1") Set currentCell = Worksheets("Sheet1").Range("A1") Do While Not IsEmpty(currentCell) Set nextCell = currentCell.Offset(1, 0) If nextCell.Value = currentCell.Value Then currentCell.EntireRow.Delete End If Set currentCell = nextCell Loop

DoEvents Function
Description Yields execution so that the operating system can process other events.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 87 of 1081

Syntax DoEvents( ) Remarks The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Standard Edition. DoEvents returns zero in all other applications. DoEvents passes control to the operating system. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent. DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. In the latter case, the task can continue completely independent of your application, and the operating system takes case of multitasking and time slicing. Caution make sure the procedure is not executed again from a different part of your code before the first call returns; this could cause unpredictable results. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control. See Also SendKeys statement. Specifics (Microsoft Access) In Microsoft Access, the DoEvents function is ignored if you use it in: A user-defined function or a procedure that calculates a field in a query, form, or report. A user-defined function that creates a list to fill a combo box, a list box, or an OLE object. If you include the DoEvents function in any of these, Microsoft Access will not relinquish control to the operating system. Example This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.
' Create a variable to hold number of Visual Basic forms loaded ' and visible. Dim I, OpenForms For I = 1 To 150000 ' Start loop. If I Mod 1000 = 0 Then ' If loop has repeated 1000 times. OpenForms = DoEvents ' Yield to operating system. End If Next I ' Increment loop counter.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 88 of 1081

Example (Microsoft Access) The following example uses the DoEvents function to return control to the operating system while a loop is executing. The DoEvents function always returns 0.
Sub LongLoop() Dim intI As Integer For intI = 1 To 1500 If intI Mod 100 = 0 Then DoEvents Debug.Print intI End If Next intI End Sub ' Start loop. ' If loop has repeated 100 times. ' Yield to operating system. ' Increment loop counter.

Double Data Type


Description Double (double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floatingpoint numbers ranging in value from 1.79769313486232E308 to 4.94065645841247E324 for negative values and from 4.94065645841247E324 to 1.79769313486232E308 for positive values. The type-declaration character for Double is the number sign (#). See Also Data type summary, Deftype statements, Single data type.

End Statement
Description Ends a procedure or block. Syntax End End Function End If End Property End Select End Sub End Type

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 89 of 1081

End With The End statement syntax has these forms Statement Description

End

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement and to clear variables.

End Function

Required to end a Function statement.

End If

Required to end a block IfThenElse statement.

End Property

Required to end a Property Let, Property Get, or Property Set procedure.

End Select

Required to end a Select Case statement.

End Sub

Required to end a Sub statement.

End Type

Required to end a user-defined type definition (Type statement).

End With

Required to end a With statement.

Remarks When executed, the End statement resets all module-level variables and all static local variables in all modules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables. Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events of forms and class modules is not executed.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 90 of 1081

Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated. The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms. Your program closes as soon as there are no other programs holding references to objects created from your public class modules and no code executing. See Also Exit statement, Function statement, If...Then...Else statement, Property Get statement, Property Let statement, Property Set statement, Select Case statement, Stop statement, Sub statement, Type statement, With statement. Example This example uses the End Statement to end code execution if the user enters an invalid password.
Sub Form_Load Dim Password, Pword PassWord = "Swordfish" Pword = InputBox("Type in your password") If Pword <> PassWord Then MsgBox "Sorry, incorrect password" End End If End Sub

Environ Function
Description Returns the String associated with an operating system environment variable. Syntax Environ({envstring | number}) The Environ function syntax has these named arguments Part Description

envstring

Optional. String expression containing the name of an environment variable.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 91 of 1081

number

Optional. Numeric expression corresponding to the numeric order of the environment string in the environment-string table. The number argument can be any numeric expression, but is rounded to a whole number before it is evaluated.

Remarks If envstring can't be found in the environment-string table, a zero-length string (" ") is returned. Otherwise, Environ returns the text assigned to the specified envstring; that is, the text following the equal sign (=) in the environment-string table for that environment variable. If you specify number, the string occupying that numeric position in the environment-string table is returned. In this case, Environ returns all of the text, including envstring. If there is no environment string in the specified position, Environ returns a zero-length string. Example This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-string table.
Dim EnvString, Indx, Msg, PathLen Indx = 1 Do EnvString = Environ(Indx) ' Declare variables. ' Initialize index to 1.

' Get environment ' variable. If Left(EnvString, 5) = "PATH=" Then ' Check PATH entry. PathLen = Len(Environ("PATH")) ' Get length. Msg = "PATH entry = " & Indx & " and length = " & PathLen Exit Do Else Indx = Indx + 1 ' Not PATH entry, End If ' so increment. Loop Until EnvString = "" If PathLen > 0 Then MsgBox Msg ' Display message. Else MsgBox "No PATH environment variable exists." End If

EOF Function
Description Returns an Integer containing the Boolean value True when the end of a file opened for Random or sequential Input has been reached. Syntax EOF(filenumber) The required filenumber argument is an Integer containing any valid file number. Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 92 of 1081

Use EOF to avoid the error generated by attempting to get input past the end of a file. The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF returns False until the last executed Get statement is unable to read an entire record. With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using the EOF function. With files opened for Output, EOF always returns True. See Also Get statement, Loc function, LOF function, Open statement. Example This example uses the EOF function to detect the end of a file. This example assumes that MYFILE is a text file with a few lines of text.
Dim InputData Open "MYFILE" For Input As #1 Do While Not EOF(1) Line Input #1, InputData Debug.Print InputData Loop Close #1 ' Open file for input. ' Check for end of file. ' Read line of data. ' Print to Debug window. ' Close file.

Eqv Operator
Description Used to perform a logical equivalence on two expressions. Syntax result = expression1 Eqv expression2 The Eqv operator syntax has these parts Part Description

result

Required; any numeric variable.

expression1

Required; any expression.

expression2

Required; any expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 93 of 1081

Remarks If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table If expression1 is And expression2 is The result is

True

True

True

True

False

False

False

True

False

False

False

True

The Eqv operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table If bit in expression1 is And bit in expression2 is The result is

See Also Operator precedence. Example This example uses the Eqv operator to perform logical equivalence on two expressions.
Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 94 of 1081

MyCheck MyCheck MyCheck MyCheck

= = = =

A B A A

> B > A > B Eqv

Eqv B > C Eqv B > C Eqv B > D B

' Returns True. ' Returns False. ' Returns Null. ' Returns -3 (bitwise comparison).

Erase Statement
Description Reinitializes the elements of fixed-size arrays and releases dynamic-array storage space. Syntax Erase arraylist The required arraylist argument is one or more comma-delimited array variables to be erased. Remarks Erase behaves differently depending on whether an array is fixed-size (ordinary) or dynamic. Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as follows Type of array Effect of Erase on fixed-array elements

Fixed numeric array

Sets each element to zero.

Fixed string array (variable length)

Sets each element to a zerolength string (" ").

Fixed string array (fixed length)

Sets each element to zero.

Fixed Variant array

Sets each element to Empty.

Array of user-defined types

Sets each element as if it were a separate variable.

Array of objects

Sets each element to the special value Nothing.

Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 95 of 1081

See Also Array function, Dim statement, Private statement, Public statement, ReDim statement, Static statement. Example This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.
' Declare array variables. Dim NumArray(10) As Integer Dim StrVarArray(10) As String Dim StrFixArray(10) As String * 10 Dim VarArray(10) As Variant Dim DynamicArray() As Integer ReDim DynamicArray(10) Erase NumArray Erase StrVarArray Erase StrFixArray Erase VarArray Erase DynamicArray ' Integer array. ' Variable-string array. ' Fixed-string array. ' Variant array. ' Dynamic array. ' Allocate storage space. ' Each element set to 0. ' Each element set to zero-length ' string (""). ' Each element set to 0. ' Each element set to Empty. ' Free memory used by array.

Err Object
Description Contains information about run-time errors. Remarks The properties of the Err object are set by the generator of an error Visual Basic, an object, or the Visual Basic programmer. The default property of the Err object is Number. Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a runtime error in your code, use the Raise method. The Err object's properties are reset to zero or zero-length strings (" ") after any form of the Resume or On Error statement and after an Exit Sub, Exit Function, or Exit Property statement within an error-handling routine. The Clear method can be used to explicitly reset Err. Use the Raise method, rather than the Error statement, to generate run-time errors for a class module. Using the Raise method in other code depends on the richness of the information you want to return. In code that uses Error statements instead of the Raise method to generate errors, the properties of the Err object are assigned the following default values when Error is executed

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 96 of 1081

Property

Value

Number

Value specified as argument to Error statement. Can be any valid error number.

Source

Name of the current Visual Basic project.

Description

A string corresponding to the return of the Error function for the specified Number, if this string exists. If the string doesn't exist, Description contains "Application-defined or object-defined error".

HelpFile

The fully qualified drive, path, and file name of the Visual Basic Help file.

HelpContext

The Visual Basic Help file context ID for the error corresponding to the Number property.

LastDLLError

On 32-bit Microsoft Windows operating systems only, contains the system error code for the last call to a dynamic-link library (DLL). The LastDLLError property is read-only.

You don't have to change existing code that uses the Err object and the Error statement. However, using both the Err object and the Error statement can result in unintended consequences. For example, even if you fill in properties for the Err object, they are reset to the default values indicated in the preceding table as soon as the Error statement is executed. Although you can still use the Error statement to generate Visual Basic run-time errors, it is retained principally for compatibility with existing code. Use the Err object, the Raise method, and the Clear method for system errors and in new code, especially for class modules. The Err object is an intrinsic object with global scope. There is no need to create an instance of it in your code. Properties Description property, HelpContext property, HelpContextID property, HelpFile property, LastDLLError property, Number property, Source property. Methods

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 97 of 1081

Clear method, Raise method. See Also Error function, Error object ("DAO Language Reference" in Volume 1), Error statement, On Error statement, Resume statement. Example This example uses the properties of the Err object in constructing an error-message dialog box. Note that if you use the Clear method first, when you generate a Visual Basic error with the Raise method, Visual Basic's default values become the properties of the Err object.
Dim Msg ' If an error occurs, construct an error message On Error Resume Next ' Defer error handling. Err.Clear Err.Raise 6 ' Generate an "Overflow" error. ' Check for error, then show message. If Err.Number <> 0 Then Msg = "Error # " & Str(Err.Number) & " was generated by " _ & Err.Source & Chr(13) & Err.Description MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContext End If

Error Function
Description Returns the error message that corresponds to a given error number. Syntax Error[(errornumber)] The optional errornumber argument can be any valid error number. If errornumber is a valid error number, but is not defined, Error returns the string "Application-defined or object-defined error." If errornumber is not valid, an error occurs. If errornumber is omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, or errornumber is 0, Error returns a zero-length string (" "). Remarks Examine the property settings of the Err object to identify the most recent run-time error. The return value of the Error function corresponds to the Description property of the Err object. See Also Err object. Example This example uses the Error function to print error messages that correspond to the specified

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 98 of 1081

error numbers.
Dim ErrorNumber For ErrorNumber = 61 To 64 Debug.Print Error(ErrorNumber) Next ErrorNumber ' Loop through values 61 - 64. ' Print error to Debug window.

Error Statement
Description Simulates the occurrence of an error. Syntax Error errornumber The required errornumber can be any valid error number. Remarks The Error statement is supported for backward compatibility. In new code, especially when creating objects, use the Err object's Raise method to generate run-time errors. If errornumber is defined, the Error statement calls the error handler after the properties of Err object are assigned the following default values Property Value

Number

Value specified as argument to Error statement. Can be any valid error number.

Source

Name of the current Visual Basic project.

Description

String expression corresponding to the return value of the Error function for the specified Number, if this string exists. If the string doesn't exist, Description contains a zero-length string (" ").

HelpFile

The fully qualified drive, path, and file name of the appropriate Visual Basic Help file.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 99 of 1081

HelpContext

The appropriate Visual Basic Help file context ID for the error corresponding to the Number property.

LastDLLError

Zero.

If no error handler exists or if none is enabled, an error message is created and displayed from the Err object properties. Note Not all Visual Basic host applications can create objects. See your host application's documentation to determine whether it can create classes and objects. See Also Clear method, Err object, Error function, On Error statement, Raise method, Resume statement. Example This example uses the Error statement to simulate error number 11.
On Error Resume Next Error 11 ' Defer error handling. ' Simulate the "Division by zero" error.

Exit Statement
Description Exits a block of DoLoop, For...Next, Function, Sub, or Property code. Syntax Exit Do Exit For Exit Function Exit Property Exit Sub The Exit statement syntax has these forms

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 100 of 1081

Statement

Description

Exit Do

Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.

Exit For

Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where Exit For occurs.

Exit Function

Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.

Exit Property

Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.

Exit Sub

Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure.

Remarks Do not confuse Exit statements with End statements. Exit does not define the end of a structure. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 101 of 1081

Do...Loop statement, End statement, For Each...Next statement, For...Next statement, Function statement, Property Get statement, Property Let statement, Property Set statement, Stop statement, Sub statement. Example This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.
Sub ExitStatementDemo() Dim I, MyNum Do For I = 1 To 1000 MyNum = Int(Rnd * 1000) Select Case MyNum Case 7: Exit For Case 29: Exit Do Case 54: Exit Sub End Select Next I Loop End Sub

' Set up infinite loop. ' Loop 1000 times. ' Generate random numbers. ' Evaluate random number. ' If 7, exit For...Next. ' If 29, exit Do...Loop. ' If 54, exit Sub procedure.

Exp Function
Description Returns a Double specifying e (the base of natural logarithms) raised to a power. Syntax Exp(number) The required number argument is a Double or any valid numeric expression. Remarks If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282. Note The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm. See Also Log function. Example This example uses the Exp function to return e raised to a power.
Dim MyAngle, MyHSin ' Define angle in radians. MyAngle = 1.3 ' Calculate hyperbolic sine. MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 102 of 1081

FileAttr Function
Description Returns a Long representing the file mode for files opened using the Open statement. Syntax FileAttr(filenumber, returntype) The FileAttr function syntax has these named arguments Part Description

filenumber

Required; Integer. Any valid file number.

returntype

Required; Integer. Number indicating the type of information to return. Specify 1 to return a value indicating the file mode. On 16-bit systems only, specify 2 to retrieve an operating system file handle. Returntype 2 is not supported in 32-bit systems and causes an error.

Return Values When the returntype argument is 1, the following return values indicate the file access mode Mode Value

Input

Output

Random

Append

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 103 of 1081

Binary

32

See Also GetAttr function, Open statement, SetAttr statement. Example This example uses the FileAttr function to return the file mode and file handle of an open file.
Dim FileNum, Mode, Handle FileNum = 1 Open "TESTFILE" For Append As FileNum Mode = FileAttr(FileNum, 1) Handle = FileAttr(FileNum, 2) Close FileNum ' Assign file number. ' Open file. ' Returns 8 (Append file mode). ' Returns file handle. ' Close file.

FileCopy Statement
Description Copies a file. Syntax FileCopy source, destination The FileCopy statement syntax has these named arguments Part Description

source

Required. String expression that specifies the name of the file to be copied. The source may include directory or folder, and drive.

destination

Required. String expression that specifies the target file name. The destination may include directory or folder, and drive.

Remarks If you try to use the FileCopy statement on a currently open file, an error occurs. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 104 of 1081

Kill statement, Name statement. Example This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that SRCFILE is a file containing some data.
Dim SourceFile, DestinationFile SourceFile = "SRCFILE" DestinationFile = "DESTFILE" FileCopy SourceFile, DestinationFile ' Define source file name. ' Define target file name. ' Copy source to target.

FileDateTime Function
Description Returns a Variant (Date) that indicates the date and time when a file was created or last modified. Syntax FileDateTime(pathname) The required pathname argument is a string expression that specifies a file name. The pathname may include the directory or folder, and the drive. See Also FileLen function, GetAttr function, VarType function. Example This example uses the FileDateTime function to determine the date and time a file was created or last modified. The format of the date and time displayed is based on the locale settings of your system.
Dim MyStamp ' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM. ' Assume English/U.S. locale settings. MyStamp = FileDateTime("TESTFILE") ' Returns "2/12/93 4:35:47 PM".

FileLen Function
Description Returns a Long specifying the length of a file in bytes. Syntax FileLen(pathname)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 105 of 1081

The required pathname argument is a string expression that specifies a file. The pathname may include the directory or folder, and the drive. Remarks If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened. Note To obtain the length of an open file, use the LOF function. See Also FileDateTime function, GetAttr function, LOF function. Example This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that TESTFILE is a file containing some data.
Dim MySize MySize = FileLen("TESTFILE") ' Returns file length (bytes).

Fix Function
See Int, Fix Functions.

For Each...Next Statement


Description Repeats a group of statements for each element in an array or collection. Syntax For Each element In group [statements] [Exit For] [statements] Next [element] The For...Each...Next statement syntax has these parts

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 106 of 1081

Part

Description

element

Required. Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, element can only be a Variant variable.

group

Required. Name of an object collection or array (except an array of user-defined types).

statements

Optional. One or more statements that are executed on each item in group.

Remarks The For...Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. If there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement. Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example IfThen, and transfers control to the statement immediately following Next. You can nest For...Each...Next loops by placing one For...Each...Next loop within another. However, each loop element must be unique. Note If you omit element in a Next statement, execution continues as if element is included. If a Next statement is encountered before its corresponding For statement, an error occurs. You can't use the For...Each...Next statement with an array of user-defined types because a Variant can't contain a user-defined type. See Also Do...Loop statement, Exit statement, For...Next statement, While...Wend statement. Example This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello." In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 107 of 1081

Dim Found, MyObject, MyCollection Found = False For Each MyObject In MyCollection If MyObject.Text = "Hello" Then Found = True Exit For End If Next

' Initialize variable. ' Iterate through each element. ' If Text equals "Hello". ' Set Found to True. ' Exit loop.

Example (Microsoft Excel) This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).
For Each c in Worksheets("Sheet1").Range("A1:D10") If c.Value < .001 Then c.Value = 0 End If Next c

This example loops on the range named "TestRange" and then displays the number of empty cells in the range.
numBlanks = 0 For Each c In Range("TestRange") If c.Value = "" Then numBlanks = numBlanks + 1 End If Next c MsgBox "There are " & numBlanks & " empty cells in this range."

This example closes and saves changes to all workbooks except the one that's running the example.
For Each w In Workbooks If w.Name <> ThisWorkbook.Name Then w.Close savechanges:=True End If Next w

This example deletes every worksheet in the active workbook without displaying the confirmation dialog box. There must be at least one other visible sheet in the workbook.
Application.DisplayAlerts = False For Each w In Worksheets w.Delete Next w Application.DisplayAlerts = True

This example creates a new worksheet and then inserts into it a list of all the names in the active workbook, including their formulas in A1-style notation in the language of the user.
Set newSheet = ActiveWorkbook.Worksheets.Add i = 1 For Each nm In ActiveWorkbook.Names newSheet.Cells(i, 1).Value = nm.NameLocal newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal i = i + 1 Next nm

For...Next Statement

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 108 of 1081

Description Repeats a group of statements a specified number of times. Syntax For counter = start To end [Step step] [statements] [Exit For] [statements] Next [counter] The ForNext statement syntax has these parts Part Description

counter

Required. Numeric variable used as a loop counter. The variable can't be a Boolean or an array element.

start

Required. Initial value of counter.

end

Required. Final value of counter.

step

Optional. Amount counter is changed each time through the loop. If not specified, step defaults to one.

statements

Optional. One or more statements between For and Next that are executed the specified number of times.

Remarks The step argument can be either positive or negative. The value of the step argument determines loop processing as follows Value Loop executes if

Positive or 0

counter <= end

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 109 of 1081

Negative

counter >= end

After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement. Tip Changing the value of counter while inside a loop can make it more difficult to read and debug your code. Any number of Exit For statements may be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating of some condition, for example If...Then, and transfers control to the statement immediately following Next. You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:
For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 ... Next K Next J Next I

Note If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs. See Also Do...Loop statement, Exit statement, For Each...Next statement, While...Wend statement. Example This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.
Dim Words, Chars, MyString For Words = 10 To 1 Step -1 For Chars = 0 To 9 MyString = MyString & Chars Next Chars MyString = MyString & " " Next Words ' Set up 10 repetitions. ' Set up 10 repetitions. ' Append number to string. ' Increment counter ' Append a space.

Example (Microsoft Excel) This example displays the number of columns in the selection on Sheet1. The code also tests for a multiple-area selection; if one exists, the code loops on the areas of the selection.
Worksheets("Sheet1").Activate areaCount = Selection.Areas.Count If areaCount <= 1 Then MsgBox "The selection contains " & _ Selection.Columns.Count & " columns." Else For i = 1 To areaCount MsgBox "Area " & i & " of the selection contains " & _

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 110 of 1081

Selection.Areas(i).Columns.Count & " columns." Next i End If

This example creates a new worksheet and then inserts a list of the active workbook's sheet names into the first column of the worksheet.
Set newSheet = Sheets.Add(Type:=xlWorksheet) For i = 1 To Sheets.Count newSheet.Cells(i, 1).Value = Sheets(i).Name Next i

This example selects every other item in list box one on Sheet1.
Dim items() As Boolean Set lbox = Worksheets("Sheet1").ListBoxes(1) ReDim items(1 To lbox.ListCount) For i = 1 To lbox.ListCount If i Mod 2 = 1 Then items(i) = True Else items(i) = False End If Next lbox.MultiSelect = xlExtended lbox.Selected = items

Format Function
Description Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression. Syntax Format(expression[, format[, firstdayofweek[, firstweekofyear]]]) The Format function syntax has these parts Part Description

expression

Required. Any valid expression.

format

Optional. A valid named or userdefined format expression.

firstdayofweek

Optional. A constant that specifies the first day of the week.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 111 of 1081

firstweekofyear

Optional. A constant that specifies the first week of the year.

Settings The firstdayofweek argument has these settings Constant Value Description

vbUseSystem

Use NLS API setting.

VbSunday

Sunday (default).

vbMonday

Monday.

vbTuesday

Tuesday.

vbWednesday

Wednesday.

vbThursday

Thursday.

vbFriday

Friday.

vbSaturday

Saturday.

The firstweekofyear argument has these settings Constant Value Description

vbUseSystem

Use NLS API setting.

vbFirstJan1

Start with week in which January 1 occurs (default).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 112 of 1081

vbFirstFourDays

Start with the first week that has at least four days in the year.

vbFirstFullWeek

Start with the first full week of the year.

Remarks To Format Do This

Numbers

Use predefined named numeric formats or create user-defined numeric formats.

Dates and times

Use predefined named date/time formats or create user-defined date/time formats.

Date and time serial numbers

Use date and time formats or numeric formats.

Strings

Create your own user-defined string formats.

If you try to format a number without specifying format, Format provides functionality similar to the Str function, although it is internationally aware. However, positive numbers formatted as strings using Format don't include a leading space reserved for the sign of the value; those converted using Str retain the leading space. See Also Format function different formats for different numeric values, Format function different formats for different string values, Format function named date/time formats, Format function named numeric formats, Format function user-defined date/time formats, Format function user-defined numeric formats, Format function user-defined string formats, Str function. Specifics (Microsoft Access) In Microsoft Access versions 1.x and 2.0, you could use the Format function to return one value for a zero-length string and another for a Null value. For example, you could use a format expression such as the following with the Format function to return the appropriate string value from code:
Dim varX As Variant, varStrX As Variant

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 113 of 1081

' Assign some value to varStrX and pass to Format function. varX = Format(varStrX, "@;ZLS;Null")

In Microsoft Access 97, you must test separately for the Null case, then return the appropriate value based on the result. For example, you could use the IIf function in an expression with the Format function such as the following:
varX = IIf(IsNull(varStrX),"Null", Format(varStrX, "@;ZLS"))

This change applies only when you use the Format function to format a string dependent on whether it's a zero-length string or a Null value. Other format expressions used with the Format function continue to work as they did in previous versions. If you convert a database from Microsoft Access version 1.x or 2.0 to Microsoft Access 97, you'll need to change code to test separately for the Null case. Example This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting.
Dim MyTime, MyDate, MyStr MyTime = #17:04:23# MyDate = #January 27, 1993# ' Returns current system time in the system-defined long time format. MyStr = Format(Time, "Long Time") ' Returns current system date in the system-defined long date format. MyStr = Format(Date, "Long Date") MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23". MyStr = Format(MyTime, "hh:mm:ss AMPM") ' Returns "05:04:23 PM". MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns "Wednesday, ' Jan 27 1993". ' If format is not supplied, a string is returned. MyStr = Format(23) ' Returns "23". ' User-defined formats. MyStr = Format(5459.4, "##,##0.00") MyStr = Format(334.9, "###0.00") MyStr = Format(5, "0.00%") MyStr = Format("HELLO", "<") MyStr = Format("This is it", ">") ' Returns "5,459.40". ' Returns "334.90". ' Returns "500.00%". ' Returns "hello". ' Returns "THIS IS IT".

Format Function Different Formats for Different Numeric Values


Description A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 114 of 1081

section is allowed. If you use The result is

One section only

The format expression applies to all values.

Two sections

The first section applies to positive values and zeros, the second to negative values.

Three sections

The first section applies to positive values, the second to negative values, and the third to zeros.

Four sections

The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.
"$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.
"$#,##0;;\Z\e\r\o"

See Also Format function, Format function different formats for different string values.

Format Function Different Formats for Different String Values


Description A format expression for strings can have one section or two sections separated by a semicolon (;).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 115 of 1081

If you use

The result is

One section only

The format applies to all string data.

Two sections

The first section applies to string data, the second to Null values and zerolength strings (" ").

See Also Format function, Format function different formats for different numeric values. Specifics (Microsoft Access) See the Format property specifics (Microsoft Access).

Format Function Named Date/Time Formats


Description The following table identifies the predefined date and time format names Format Name Description

General Date

Display a date and/or time. For real numbers, display a date and time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.

Long Date

Display a date according to your system's long date format.

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 116 of 1081

Medium Date

Display a date using the medium date format appropriate for the language version of the host application.

Short Date

Display a date using your system's short date format.

Long Time

Display a time using your system's long time format; includes hours, minutes, seconds.

Medium Time

Display time in 12-hour format using hours and minutes and the AM/PM designator.

Short Time

Display a time using the 24-hour format, for example, 17:45.

See Also Format function, Format function named numeric formats, Format function user-defined date/time formats.

Format Function Named Numeric Formats


Description The following table identifies the predefined numeric format names: Format name Description

General Number

Display number with no thousand separator.

Currency

Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 117 of 1081

Fixed

Display at least one digit to the left and two digits to the right of the decimal separator.

Standard

Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.

Percent

Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.

Scientific

Use standard scientific notation.

Yes/No

Display No if number is 0; otherwise, display Yes.

True/False

Display False if number is 0; otherwise, display True.

On/Off

Display Off if number is 0; otherwise, display On.

See Also Format function, Format function named date/time formats, Format function user-defined numeric formats.

Format Function User-Defined Date/Time Formats


Description The following table identifies characters you can use to create user-defined date/time formats:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 118 of 1081

Character

Description

(:)

Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

(/)

Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.

Display the date as ddddd and display the time as ttttt, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.

Display the day as a number without a leading zero (1 31).

dd

Display the day as a number with a leading zero (01 31).

ddd

Display the day as an abbreviation (Sun Sat).

dddd

Display the day as a full name (Sunday Saturday).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 119 of 1081

ddddd

Display the date as a complete date (including day, month, and year), formatted according to your system's short date format setting. For Microsoft Windows, the default short date format is m/d/yy.

dddddd

Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. For Microsoft Windows, the default long date format is mmmm dd, yyyy.

Display the day of the week as a number (1 for Sunday through 7 for Saturday).

ww

Display the week of the year as a number (1 54).

Display the month as a number without a leading zero (1 12). If m immediately follows h or hh, the minute rather than the month is displayed.

mm

Display the month as a number with a leading zero (01 12). If m immediately follows h or hh, the minute rather than the month is displayed.

mmm

Display the month as an abbreviation (Jan Dec).

mmmm

Display the month as a full month name (January December).

Display the quarter of the year as a number (1 4).

Display the day of the year as a number (1 366).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 120 of 1081

yy

Display the year as a 2-digit number (00 99).

yyyy

Display the year as a 4-digit number (100 9999).

Display the hour as a number without leading zeros (0 23).

hh

Display the hour as a number with leading zeros (00 23).

Display the minute as a number without leading zeros (0 59).

nn

Display the minute as a number with leading zeros (00 59).

Display the second as a number without leading zeros (0 59).

ss

Display the second as a number with leading zeros (00 59).

ttttt

Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. For Microsoft Windows, the default time format is h:mm:ss.

AM/PM

Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 121 of 1081

am/pm

Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.

A/P

Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.

a/p

Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.

AMPM

Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. For Microsoft Windows, the default format is AM/PM.

See Also Format function. Example The following are examples of user-defined date and time formats for December 7, 1958: Format Display

m/d/yy

12/7/58

d-mmm

7-Dec

dmmmmyy

7-December-58

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 122 of 1081

d mmmm

7 December

(continued) Format Display

mmmm yy

December 58

hh:mm AM/PM

08:50 PM

h:mm:ss a/p

8:50:35 p

h:mm

20:50

h:mm:ss

20:50:35

m/d/yy h:mm

12/7/58 20:50

Format Function User-Defined Numeric Formats


Description The following table identifies characters you can use to create user-defined number formats: Character Description

None

Display the number with no formatting.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 123 of 1081

(0)

Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position. If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.

(#)

Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position. This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

(continued) Character Description

(.)

Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 124 of 1081

the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.

(%)

Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.

(,)

Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed." For example, you can use the format string "##0,," to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.

(:)

Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 125 of 1081

(/)

Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.

(E- E+ ee+)

Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use Eor e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.

-+$()

Display a literal character. To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").

(continued) Character Description

(\)

Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\). Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, / and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 126 of 1081

("ABC")

Display the string inside the double quotation marks (" "). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).

See Also Format function. Example The following table contains some sample format expressions for numbers. (These examples all assume that your system's locale setting is English-U.S.) The first column contains the format strings; the other columns contain the resulting output if the formatted data has the value given in the column headings. Format (format) Positive 5 Negative 5 Decimal .5 Null

Zero-length string ("")

-5

0.5

-5

0.00

5.00

-5.00

0.50

#,##0

-5

#,##0.00;;;Nil

5.00

-5.00

0.50

Nil

$#,##0; ($#,##0)

$5

($5)

$1

$#,##0.00; ($#,##0.00)

$5.00

($5.00)

$0.50

0%

500%

-500%

50%

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 127 of 1081

0.00%

500.00%

500.00%

50.00%

0.00E+00

5.00E+00

5.00E+00

5.00E-01

0.00E-00

5.00E00

-5.00E00

5.00E-01

Format Function User-Defined String Formats


Description You can use any of the following characters to create a format expression for strings: Character Description

Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.

&

Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.

<

Force lowercase. Display all characters in lowercase format.

>

Force uppercase. Display all characters in uppercase format.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 128 of 1081

Force left to right fill of placeholders. The default is to fill placeholders from right to left.

See Also Format function, Format function different formats for different string values, Format function user-defined date/time formats, Format function user-defined numeric formats.

FreeFile Function
Description Returns an Integer representing the next file number available for use by the Open statement. Syntax FreeFile[(rangenumber)] The optional rangenumber argument is a Variant that specifies the range from which the next free file number is to be returned. Specify a 0 (default) to return a file number in the range 1 255, inclusive. Specify a 1 to return a file number in the range 256 511. Remarks Use FreeFile to supply a file number that is not already in use. See Also Open statement. Example This example uses the FreeFile function to return the next available file number. Five files are opened for output within the loop, and some sample data is written to each.
Dim MyIndex, FileNumber For MyIndex = 1 To 5 FileNumber = FreeFile ' Loop 5 times. ' Get unused file ' number. Open "TEST" & MyIndex For Output As #FileNumber ' Create filename. Write #FileNumber, "This is a sample." ' Output text. Close #FileNumber ' Close file. Next MyIndex

Function Statement
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 129 of 1081

Declares the name, arguments, and code that form the body of a Function procedure. Syntax [Public | Private] [Static] Function name [(arglist)] [As type] [statements] [name = expression] [Exit Function] [statements] [name = expression] End Function The Function statement syntax has these parts: Part Description

Public

Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.

Private

Optional. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.

Static

Optional. Indicates that the Function procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Function, even if they are used in the procedure.

name

Required. Name of the Function; follows standard variable naming conventions.

arglist

Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 130 of 1081

type

Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or (except fixed length), Object, Variant, or any userdefined type. Arrays of any type can't be returned, but a Variant containing an array can.

statements

Optional. Any group of statements to be executed within the Function procedure.

expression

Optional. Return value of the Function.

The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Part Description

Optional

Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 131 of 1081

varname

Required. Name of the variable representing the argument; follows standard variable naming conventions.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported) Date, String (variable length only), Object, Variant. If the parameter is not Optional, a user-defined type or an object type may also be specified.

defaultvalue

Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks If not explicitly specified using either Public or Private, Function procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. Caution Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword is usually not used with recursive Function procedures. All executable code must be in procedures. You can't define a Function procedure inside another Function, Sub, or Property procedure. The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure. Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function. You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures. To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zerolength string (" "), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 132 of 1081

Function. The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.
Function BinarySearch(. . .) As Boolean . . . ' Value not found. Return a value of False. If lower > upper Then BinarySearch = False Exit Function End If . . . End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure. Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure refers to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables. Caution Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression. See Also Call statement, Dim statement, Option Explicit statement, Property Get statement, Property Let statement, Property Set statement, Sub statement. Specifics (Microsoft Access) In Microsoft Access, a public Function procedure is available to all other procedures in the current database and in referencing Microsoft Access databases. However, it is not available to any other applications. If you declare a Function procedure as private in any module by preceding it with the Private keyword, that procedure is available only to other procedures in the same module. If a Function procedure is declared as public within a private module, such as a class module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases. Example This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 133 of 1081

' The following user-defined function returns the square root of the ' argument passed to it. Function CalculateSquareRoot(NumberArg As Double) As Double If NumberArg < 0 Then ' Evaluate argument. Exit Function ' Exit to calling procedure. Else CalculateSquareRoot = Sqr(NumberArg) ' Return square root. End If End Function

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg is passed by value.
Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs()) Dim ReturnValue ' If the function is invoked as follows: ReturnValue = CalcSum(4, 3 ,2 ,1) ' Local variables are assigned the following values: FirstArg = 4, ' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default ' lowerbound for arrays = 1.

Optional arguments can now have default values and types other than Variant.
' If a function's arguments are defined as follows: Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, _ Optional MyArg2 = "Dolly") Dim RetVal ' The function can be invoked as follows: RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied. RetVal = MyFunc("Test", , 5) ' Second argument omitted. ' Arguments one and three using named-arguments. RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)

FV Function
Description Returns a Double specifying the future value of an annuity based on periodic, fixed payments and a fixed interest rate. Syntax FV(rate, nper, pmt[, pv[, type]]) The FV function has these named arguments: Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 134 of 1081

nper

Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pmt

Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.

(continued) pv Optional. Variant specifying present value (or lump sum) of a series of future payments. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make. If omitted, 0 is assumed.

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the FV function to return the future value of an investment given the percentage rate that accrues per period (APR / 12), the total number of payments (TotPmts), the payment (Payment), the current value of the investment (PVal), and a number that

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 135 of 1081

indicates whether the payment is made at the beginning or end of the payment period (PayType). Note that because Payment represents cash paid out, it's a negative number.
Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "###,###,##0.00" ' Define money format. Payment = InputBox("How much do you plan to save each month?") APR = InputBox("Enter the expected interest annual percentage rate.") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("For how many months do you expect to save?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD PVal = InputBox("How much is in this savings account now?") FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType) MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "."

Get Statement
Description Reads data from an open disk file into a variable. Syntax Get [#]filenumber, [recnumber], varname The Get statement syntax has these parts Part Description

filenumber

Required. Any valid file number.

recnumber

Optional. Variant (Long). Record number (Random mode files) or byte number (Binary mode files) at which reading begins.

varname

Required. Valid variable name into which data is read.

Remarks Data read with Get is usually written to a file with Put. The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte following the last Get or Put statement (or pointed to by the last Seek function) is read. You must include delimiting commas, for example:
Get #4,,FileBuffer

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 136 of 1081

For files opened in Random mode, the following rules apply: If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read. If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then reads the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string. If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then the data that goes into the variable. For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable. Note You can use the Get statement to read a Variant array from disk, but you can't use Get to read a scalar Variant containing an array. You also can't use Get to read objects from disk. If the variable being read into is a Variant of VarType 8 (String), Get reads 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then reads the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string. If the variable being read into is a dynamic array, Get reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.
Dim MyArray(1 To 5,1 To 10) As Integer

The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2). If the variable being read into is a fixed-size array, Get reads only the data. No descriptor is read. If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read. Get reads elements of user-defined types as if each were being read individually, except that there is no padding between elements. On disk, a dynamic array in a user-defined type (written with Put) is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the individual elements, including any arrays and their descriptors. For files opened in Binary mode, all of the Random rules apply, except:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 137 of 1081

The Len clause in the Open statement has no effect. Get reads all variables from disk contiguously; that is, with no padding between records. For any array other than an array in a user-defined type, Get reads only the data. No descriptor is read. Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1:
VarString = String(10," ") Get #1,,VarString

See Also Open statement, Put statement, Seek function, Type statement, VarType function. Example This example uses the Get statement to read data from a file into a variable. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

Dim MyRecord As Record, Position ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Read the sample file using the Get statement. Position = 3 ' Define record number. Get #1, Position, MyRecord ' Read third record. Close #1 ' Close file.

GetAllSettings Function
Description Returns a list of key settings and their respective values (originally created with SaveSetting) from an application's entry in the Windows registry. Syntax GetAllSettings(appname, section) The GetAllSettings function syntax has these named arguments Part Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 138 of 1081

appname

Required. String expression containing the name of the application or project whose key settings are requested.

section

Required. String expression containing the name of the section whose key settings are requested. GetAllSettings returns a Variant whose contents is a twodimensional array of strings containing all the key settings in the specified section and their corresponding values.

Remarks GetAllSettings returns an uninitialized Variant if either appname or section does not exist. See Also DeleteSetting statement, GetSetting function, SaveSetting statement. Example This example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the application specified as appname, then uses the GetAllSettings function to display the settings. Note that application names and section names can't be retrieved with GetAllSettings. Finally, the DeleteSetting statement removes the application's entries.
' Variant to hold 2-dimensional array returned by GetAllSettings ' Integer to hold counter. Dim MySettings As Variant, intSettings As Integer ' Place some settings in the registry. SaveSetting appname := "MyApp", section := "Startup", _ key := "Top", setting := 75 SaveSetting "MyApp","Startup", "Left", 50 ' Retrieve the settings. MySettings = GetAllSettings(appname := "MyApp", section := "Startup") For intSettings = LBound(MySettings, 1) To UBound(MySettings, 1) Debug.Print MySettings(intSettings, 0), MySettings(intSettings, 1) Next intSettings DeleteSetting "MyApp", "Startup"

GetAttr Function
Description Returns an Integer representing the attributes of a file, directory, or folder. Syntax GetAttr(pathname) The required pathname argument is a string expression that specifies a file name. The

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 139 of 1081

pathname may include the directory or folder, and the drive. Return Values The value returned by GetAttr is the sum of the following attribute values Constant Value Description

vbNormal

Normal

vbReadOnly

Read-only

vbHidden

Hidden

vbSystem

System

vbDirectory

16

Directory or folder

vbArchive

32

File has changed since last backup

Note These constants are specified by Visual Basic for Applications. The names can be used anywhere in your code in place of the actual values. Remarks To determine which attributes are set, use the And operator to perform a bitwise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:
Result = GetAttr(FName) And vbArchive

A nonzero value is returned if the Archive attribute is set. See Also And operator, FileAttr function, SetAttr statement. Specifics (Macintosh) The following constants aren't available on the Macintosh

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 140 of 1081

Constant

Value

Description

vbSystem

System file.

vbArchive

32

File has changed since last backup.

The following constant is available only on the Macintosh Constant Value Description

vbAlias

64

Specified file name is an alias.

Example This example uses the GetAttr function to determine the attributes of a file and directory or folder.
Dim MyAttr ' Assume file TESTFILE has hidden attribute set. MyAttr = GetAttr("TESTFILE") ' Returns 2. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And vbHidden ' Assume file TESTFILE has hidden and read-only attributes set. MyAttr = GetAttr("TESTFILE") ' Returns 3. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And (vbHidden + vbReadOnly) ' Assume MYDIR is a directory or folder. MyAttr = GetAttr("MYDIR") ' Returns 16.

GetObject Function
Description Returns a reference to an ActiveX object from a file. Syntax GetObject([pathname] [, class]) The GetObject function syntax has these named arguments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 141 of 1081

Part

Description

pathname

Optional; Variant (String). The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.

class

Optional; Variant (String). A string representing the class of the object.

The class argument uses the syntax appname.objecttype and has these parts Part Description

appname

Required; Variant (String). The name of the application providing the object.

objecttype

Required; Variant (String). The type or class of object to create.

Remarks Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:
Dim CADObject As Object Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated. If pathname is a zero-length string (" "), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs. Some applications allow you to activate part of a file. Add an exclamation point ( !) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object. For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 142 of 1081

If you don't specify the object's class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:
Dim MyObject As Object Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the above example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports. Once an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object using the object variable MyObject. For example:
MyObject.Line 9, 90 MyObject.InsertText 9, 100, "Hello, world." MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"

Note Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function. If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string (" ") syntax, and it causes an error if the pathname argument is omitted. You can't use GetObject to obtain a reference to a class created with Visual Basic. See Also CreateObject function, Set statement. Example This example uses the GetObject function to get a reference to a specific Microsoft Excel worksheet (MyXL). It uses the worksheet's Application property to make Microsoft Excel visible, to close it, and so on. Using two API calls, the DetectExcel Sub procedure looks for Microsoft Excel, and if it is running, enters it in the Running Object Table. The first call to GetObject causes an error if Microsoft Excel is not running. In the example, the error causes the ExcelWasNotRunning flag to be set to True. The second call to GetObject specifies a file to open. If Microsoft Excel is not already running, this second call starts it and returns a reference to the worksheet represented by the specified file. The file in the example, mytest.xls, must exist in the specified location; otherwise the Visual Basic error "Automation error" is generated. Next the example code makes both Microsoft Excel and the window containing the specified worksheet visible. Finally, if no previous version of Microsoft Excel was running, the code uses the Application object's Quit method to close Microsoft Excel. If the application was already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.
' Declare necessary API routines: Declare Function FindWindow Lib "user32" Alias _ "FindWindowA" (ByVal lpClassName as String, _ ByVal lpWindowName As Long) As Long Declare Function SendMessage Lib "user32" Alias _

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 143 of 1081

"SendMessageA" (ByVal hWnd as Long,ByVal wMsg as Long _ ByVal wParam as Long _ ByVal lParam As Long) As Long Sub GetExcel() Dim MyXL As Object ' to Microsoft Excel. Dim ExcelWasNotRunning As Boolean ' Variable to hold reference ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running. On Error Resume Next ' Defer error trapping. ' Getobject function called without the first argument returns a ' reference to an instance of the application. If the application isn't ' running, an error occurs. Note the comma used as the first argument ' placeholder. Set MyXL = Getobject(, "Excel.Application") If Err.Number <> 0 Then ExcelWasNotRunning = True Err.Clear ' Clear Err object in case error occurred. ' Check for Excel. If Excel is running, ' enter it into the Running Object table. DetectExcel Set the object variable to reference the file you want to see. Set MyXL = Getobject("c:\vb4\MYTEST.XLS") ' Show Microsoft Excel through its Application property. Then ' show the actual window containing the file using the Windows ' collection of the MyXL object reference. MyXL.Application.Visible = True MyXL.Parent.Windows(1).Visible = True ' Do manipulations of your ' file here. ' ... ' If this copy of Microsoft Excel was not already running when you ' started, close it using the Application property's Quit method. ' Note that when you try to quit Microsoft Excel, the Microsoft Excel ' title bar blinks and Microsoft Excel displays a message asking if you ' want to save any loaded files. If ExcelWasNotRunning = True Then MyXL.Application.Quit End IF Set MyXL = Nothing End Sub Sub DetectExcel() ' Procedure dectects a running Excel and registers it. Const WM_USER = 1024 Dim hWnd As Long ' If Excel is running this API call returns its handle. hWnd = FindWindow("XLMAIN", 0) If hWnd = 0 Then ' 0 means Excel not running. Exit Sub Else ' Excel is running so use the SendMessage API ' function to enter it in the Running Object Table. SendMessage hWnd, WM_USER + 18, 0, 0 End If End Sub ' Release reference to the ' application and spreadsheet.

GetSetting Function
Description Returns a key setting value from an application's entry in the Windows registry. Syntax GetSetting(appname, section, key[, default]) The GetSetting function syntax has these named arguments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 144 of 1081

Part

Description

appname

Required. String expression containing the name of the application or project whose key setting is requested.

section

Required. String expression containing the name of the section where the key setting is found.

key

Required. String expression containing the name of the key setting to return.

default

Optional. Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zerolength string (" ").

Remarks If any of the items named in the GetSetting arguments do not exist, GetSetting returns the value of default. See Also DeleteSetting statement, GetAllSettings function, SaveSetting statement. Example This example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the application specified as appname, and then uses the GetSetting function to display one of the settings. Because the default argument is specified, some value is guaranteed to be returned. Note that section names can't be retrieved with GetSetting. Finally, the DeleteSetting statement removes all the application's entries.
' Variant to hold 2-dimensional array returned by GetSetting. Dim MySettings As Variant ' Place some settings in the registry. SaveSetting "MyApp","Startup", "Top", 75 SaveSetting "MyApp","Startup", "Left", 50

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 145 of 1081

Debug.Print GetSetting(appname := "MyApp", section := "Startup", _ key := "Left", default := "25") DeleteSetting "MyApp", "Startup"

GoSub...Return Statement
Description Branches to and returns from a subroutine within a procedure. Syntax GoSub line ... line ... Return The line argument can be any line label or line number. Remarks You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return statement must be in the same procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement. Note You can't enter or exit Sub procedures with GoSub...Return.

Tip Creating separate procedures that you can call may provide a more structured alternative to using GoSub...Return. See Also GoTo statement, On...GoSub, On...GoTo statements, Sub statement. Example This example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the GoSub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.
Sub GosubDemo() Dim Num ' Solicit a number from the user. Num = InputBox("Enter a positive number to be divided by 2.") ' Only use routine if user enters a positive number. If Num > 0 Then GoSub MyRoutine Debug.Print Num Exit Sub ' Use Exit to prevent an error. MyRoutine: Num = Num/2 ' Perform the division. Return ' Return control to statement.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 146 of 1081

End Sub

' following the GoSub statement.

GoTo Statement
Description Branches unconditionally to a specified line within a procedure. Syntax GoTo line The required line argument can be any line label or line number. Remarks GoTo can branch only to lines within the procedure where it appears. Note Too many GoTo statements can make code difficult to read and debug. Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible. See Also Do...Loop statement, For...Next statement, GoSub...Return statement, If...Then...Else statement, Select Case statement. Example This example uses the GoTo statement to branch to line labels within a procedure.
Sub GotoStatementDemo() Dim Number, MyString Number = 1 ' Initialize variable. ' Evaluate Number and branch to appropriate label. If Number = 1 Then GoTo Line1 Else GoTo Line2 Line1: MyString = "Number equals 1" GoTo LastLine ' Go to LastLine. Line2: ' The following statement never gets executed. MyString = "Number equals 2" LastLine: Debug.Print MyString ' Print "Number equals 1" in ' Debug window. End Sub

HelpContext Property
Applies To Err object. Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 147 of 1081

Returns or sets a string expression containing the context ID for a topic in a Microsoft Windows Help file. Read/write. Remarks The HelpContext property is used to automatically display the Help topic specified in the HelpFile property. If both HelpFile and HelpContext are empty, the value of Number is checked. If Number corresponds to a Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the Number value doesn't correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed. Note You should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn't recoverable. See Also Description property, Err object, HelpFile property, LastDLLError property, Number property, Source property. Example This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the Overflow error.
Dim Msg Err.Clear On Error Resume Next Err.Raise 6 ' Generate "Overflow" error. If Err.Number <> 0 Then Msg = "Press F1 or Help to see " & Err.HelpFile & " topic for" & _ " the following HelpContext: " & Err.HelpContext MsgBox Msg, , "Error: " & Err.Description, Err.HelpFile, _ Err.HelpContext End If

HelpFile Property
Applies To Err object. Description Returns or sets a string expression the fully qualified path to a Microsoft Windows Help file. Read/write. Remarks If a Help file is specified in HelpFile, it is automatically called when the user presses the Help button (or the F1 key) in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed. If no HelpFile is specified, the Visual Basic Help file is displayed.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 148 of 1081

Note ou should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn't recoverable. See Also Description property, Err object, HelpContext property, LastDLLError property, Number property, Source property. Example This example uses the HelpFile property of the Err object to start the Microsoft Windows Help system. By default, the HelpFile property contains the name of the Visual Basic Help file.
Dim Msg Err.Clear On Error Resume Next ' Suppress errors for demonstration purposes. Err.Raise 6 ' Generate "Overflow" error. Msg = "Press F1 or Help to see " & Err.HelpFile & _ " topic for this error" MsgBox Msg, , "Error: " & Err.Description,Err.HelpFile, Err.HelpContext

Hex Function
Description Returns a String representing the hexadecimal value of a number. Syntax Hex(number) The required number argument is any valid numeric expression or string expression. Remarks If number is not already a whole number, it is rounded to the nearest whole number before being evaluated. If number is Hex returns

Null

Null

Empty

Zero (0)

Any other number

Up to eight hexadecimal characters

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 149 of 1081

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation. See Also Oct function. Example This example uses the Hex function to return the hexadecimal value of a number.
Dim MyHex MyHex = Hex(5) MyHex = Hex(10) MyHex = Hex(459) ' Returns 5. ' Returns A. ' Returns 1CB.

Hide Method
Applies To UserForm object. Description Hides an object but doesn't unload it. Syntax object.Hide The object placeholder represents an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm with the focus is assumed to be object. Remarks When an object is hidden, it's removed from the screen and its Visible property is set to False. A hidden object's controls aren't accessible to the user, but they are available programmatically to the running application, to other processes that may be communicating with the application through dynamic data exchange (DDE) or Automation, and to Timer control events. When a UserForm is hidden, the user can't interact with the application until all code in the event procedure that caused the UserForm to be hidden has finished executing. If the UserForm isn't loaded when the Hide method is invoked, the Hide method loads the UserForm but doesn't display it. See Also Load statement, Show method, Unload statement. Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 150 of 1081

The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.
' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event of UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub ' This is the click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub

Hour Function
Description Returns a Variant (Integer) specifying a whole number between 0 and 23, inclusive, representing the hour of the day. Syntax Hour(time) The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned. See Also Day function, Minute function, Now function, Second function, Time function, Time statement. Example This example uses the Hour function to obtain the hour from a specified time. In the development environment, the time literal is displayed in short time format using the locale settings of your code.
Dim MyTime, MyHour MyTime = #4:35:17 PM# MyHour = Hour(MyTime) ' Assign a time. ' MyHour contains 16.

If...Then...Else Statement
Description Conditionally executes a group of statements, depending on the value of an expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 151 of 1081

Syntax If condition Then [statements] [Else elsestatements] Or, you can use the block form syntax: If condition Then [statements] [ElseIf condition-n Then [elseifstatements] ... [Else [elsestatements]] End If The IfThenElse statement syntax has these parts Part Description

condition

Required. One or more of the following two types of expressions:

A numeric expression or string expression that evaluates to True or False. If condition is Null, condition is treated as False.

An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.

statements

Optional in block form; required in single-line form that has no Else clause. One or more statements separated by colons; executed if condition is True.

condition-n

Optional. Same as condition.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 152 of 1081

elseifstatements

Optional. One or more statements executed if associated condition-n is True.

elsestatements

Optional. One or more statements executed if no previous condition or condition-n expression is True.

Remarks You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug. Note With the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements must be on the same line and separated by colons, as in the following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B

A block form If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement. To determine whether or not a statement is a block If, examine what follows the Then keyword. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement. The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another. When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If. Tip Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement. See Also #If...Then...#Else directive, Choose function, Select Case statement, Switch function. Example This example shows both the block and single-line forms of the If...Then...Else statement. It also illustrates the use of If TypeOf...Then...Else.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 153 of 1081

Dim Number, Digits, MyString Number = 53 ' Initialize variable. If Number < 10 Then Digits = 1 ElseIf Number < 100 Then ' Condition evaluates to True so the next statement is executed. Digits = 2 Else Digits = 3 End If ' Assign a value using the single-line form of syntax. If Digits = 1 Then MyString = "One" Else MyString = "More than one"

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.
Sub ControlProcessor(MyControl As Control) If TypeOf MyControl Is CommandButton Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is CheckBox Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is TextBox Then Debug.Print "You passed in a " & TypeName(MyControl) End If End Sub

Example (Microsoft Excel) This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).
For Each c in Worksheets("Sheet1").Range("A1:D10") If c.Value < .001 Then c.Value = 0 End If Next c

This example loops on the range named "TestRange" and then displays the number of empty cells in the range.
numBlanks = 0 For Each c In Range("TestRange") If c.Value = "" Then numBlanks = numBlanks + 1 End If Next c MsgBox "There are " & numBlanks & " empty cells in this range."

This example sets the standard font to Geneva (on the Macintosh) or Arial (in Windows).
If Application.OperatingSystem Like "*Macintosh*" Then Application.StandardFont = "Geneva" Else Application.StandardFont = "Arial" End If

IIf Function
Description Returns one of two parts, depending on the evaluation of an expression. Syntax

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 154 of 1081

IIf(expr, truepart, falsepart) The IIf function syntax has these named arguments Part Description

expr

Required. Expression you want to evaluate.

truepart

Required. Value or expression returned if expr is True.

falsepart

Required. Value or expression returned if expr is False.

Remarks IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True. See Also Choose function, If...Then...Else statement, Select Case statement, Switch function. Specifics (Microsoft Access) You can also use the IIf function (immediate if) in a calculated control on a Microsoft Access form or report. You can use the IIf function to evaluate an expression and return either of two other values, depending on whether the expression evaluates to True (1) or False (0). For example, you can use the IIf function to inspect a field on a form and determine whether its value is Null. If it is, you can force the function return an empty string. If the field has a value that is not Null, the function could return the field's contents. The following example checks the ShipCountry field in an Orders table, and returns an empty string if it is Null.
=IIf(IsNull(Forms!Orders![ShipCountry]), "", Forms!Orders![ShipCountry])

In Visual Basic, the IIf function evaluates both truepart and falsepart, even though it returns only one of them. In a Microsoft Access form or report, however, the IIf function evaluates either truepart or falsepart, whichever is appropriate. Therefore, you need not be concerned about the undesirable side effects of evaluating both arguments if you use the IIf function in a calculated control, query expression, or macro. Note The Microsoft Access Nz function converts Null values to zero, a zero-length string, or another value that you specify. If your expression handles Null values, you may be able use the Nz function as an alternative to the IIf function.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 155 of 1081

The IIf function is most useful within expressions that are in a form or report, rather than in Visual Basic code. In Visual Basic, the more full-featured If...Then...Else statement offers greater versatility. Example This example uses the IIf function to evaluate the TestMe parameter of the CheckIt procedure and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small".
Function CheckIt (TestMe As Integer) CheckIt = IIf(TestMe > 1000, "Large", "Small") End Function

Example (Microsoft Access) This example uses the IIf function to evaluate an OrderAmount field and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small". You can enter the following expression in the ControlSource property of a calculated control.
=IIf([OrderAmount] > 1000, "Large", "Small")

IMEStatus Function
Description Returns an Integer specifying the current Input Method Editor (IME) mode of Microsoft Windows; available in Far East versions only. Syntax IMEStatus Return Values The return values for the Japanese locale are as follows Constant Value Description

vbIMENoOP

No IME installed

vbIMEOn

IME on

vbIMEOff

IME off

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 156 of 1081

vbIMEDisable

IME disabled

vbIMEHiragana

Hiragana double-byte characters (DBC)

vbIMEKatakanaDbl

Katakana DBC

vbIMEKatakanaSng

Katakana single-byte characters (SBC)

vbIMEAlphaDbl

Alphanumeric DBC

vbIMEAlphaSng

Alphanumeric SBC

The return values for the Chinese (traditional and simplified) locale are as follows Constant Value Description

vbIMENoOP

No IME installed

vbIMEOn

IME on

vbIMEOff

IME off

For the Korean locale, the first five bits of the return are set as follows Bit Value Description Value Description

No IME installed

IME installed

IME disabled

IME enabled

IME English mode

Hangeul mode

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 157 of 1081

Banja mode (SB)

Junja mode (DB)

Normal mode

Hanja conversion mode

Imp Operator
Description Used to perform a logical implication on two expressions. Syntax result = expression1 Imp expression2 The Imp operator syntax has these parts Part Description

result

Required; any numeric variable.

expression1

Required; any expression.

expression2

Required; any expression.

Remarks The following table illustrates how result is determined If expression1 is And expression2 is The result is

True

True

True

True

False

False

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 158 of 1081

True

Null

Null

False

True

True

False

False

True

False

Null

True

Null

True

True

Null

False

Null

Null

Null

Null

The Imp operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table If bit in expression1 is And bit in expression2 is The result is

See Also Operator precedence. Example This example uses the Imp Operator to perform logical implication on two expressions.
Dim A, B, A = 10: B MyCheck = MyCheck = C, D, MyCheck = 8: C = 6: D = Null A > B Imp B > C A > B Imp C > B ' Initialize variables. ' Returns True. ' Returns False.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 159 of 1081

MyCheck MyCheck MyCheck MyCheck

= = = =

B B C B

> A > A > D Imp

Imp C > B Imp C > D Imp B > A A

' Returns True. ' Returns True. ' Returns Null. ' Returns -1 (bitwise comparison).

Initialize Event
Applies To UserForm object. Description Occurs after an object is loaded, but before it's shown. Syntax Private Sub object_Initialize( ) The object placeholder represents an object expression that evaluates to an object in the Applies To list. Remarks The Initialize event is typically used to prepare an application or UserForm for use. Variables are assigned initial values, and controls may be moved or resized to accommodate initialization data. Example The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.
' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event of UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub ' This is the click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub

Input # Statement
Description Reads data from an open sequential file and assigns the data to variables.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 160 of 1081

Syntax Input #filenumber, varlist The Input # statement syntax has these parts Part Description

filenumber

Required. Any valid file number.

varlist

Required. Comma-delimited list of variables that are assigned values read from the file can't be an array or object variable. However, variables that describe an element of an array or user-defined type may be used.

Remarks Data read with Input # is usually written to a file with Write #. Use this statement only with files opened in Input or Binary mode. When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how other input data is treated Data Value assigned to variable

Delimiting comma or blank line

Empty.

#NULL#

Null.

#TRUE# or #FALSE#

True or False.

#yyyy-mm-dd hh:mm:ss#

The date and/or time represented by the expression.

#ERROR errornumber#

errornumber (variable is a Variant tagged as an error).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 161 of 1081

Double quotation marks (" ") within input data are ignored. Data items in a file must appear in the same order as the variables in varlist and match variables of the same data type. If a variable is numeric and the data is not numeric, a value of zero is assigned to the variable. If you reach the end of the file while you are inputting a data item, the input is terminated and an error occurs. Note To be able to correctly read data from a file into variables using Input #, use the Write # statement instead of the Print # statement to write the data to the files. Using Write # ensures each separate data field is properly delimited. See Also Input function, Open statement, Print # statement, Write # statement. Example This example uses the Input # statement to read data from a file into two variables. This example assumes that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).
Dim MyString, MyNumber Open "TESTFILE" For Input As #1 ' Open file for input. Do While Not EOF(1) ' Loop until end of file. Input #1, MyString, MyNumber ' Read data into two variables. Debug.Print MyString, MyNumber ' Print data to Debug window. Loop Close #1 ' Close file.

Input Function
Description Returns String containing characters from a file opened in Input or Binary mode. Syntax Input(number, [#]filenumber) The Input function syntax has these parts Part Description

number

Required. Any valid numeric expression specifying the number of characters to return.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 162 of 1081

filenumber

Required. Any valid file number.

Remarks Data read with the Input function is usually written to a file with Print # or Put. Use this function only with files opened in Input or Binary mode. Unlike the Input # statement, the Input function returns all of the characters it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces. With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using the EOF function. Note Use the InputB function for byte data contained within text files. With InputB, number specifies the number of bytes to return rather than the number of characters to return. See Also Input # statement. Example This example uses the Input function to read one character at a time from a file and print it to the Debug window. This example assumes that TESTFILE is a text file with a few lines of sample data.
Dim MyChar Open "TESTFILE" For Input As #1 Do While Not EOF(1) MyChar = Input(1, #1) Debug.Print MyChar Loop Close #1 ' Open file. ' Loop until end of file. ' Get one character. ' Print to Debug window. ' Close file.

InputBox Function
Description Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box. Syntax InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile , context]) The InputBox function syntax has these named arguments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 163 of 1081

Part

Description

prompt

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage returnlinefeed character combination (Chr (13) & Chr(10)) between each line.

title

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

default

Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.

xpos

Optional. Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.

(continued) ypos Optional. Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.

helpfile

Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 164 of 1081

context

Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. If context is provided, helpfile must also be provided.

Remarks When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context. Some host applications, for example, Microsoft Excel, also automatically add a Help button to the dialog box. If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string (" "). Note To specify more than the first named argument, you must use InputBox in an expression. To omit some positional arguments, you must include the corresponding comma delimiter. See Also MsgBox function. Specifics (Microsoft Access) You can't open a Help file from a dialog box created by the InputBox function in Microsoft Access. If you specify values for the helpfile and context arguments, they will be ignored, and no Help button appears on the input box. However, Microsoft Access won't generate an error. Specifics (Microsoft Excel) In Microsoft Excel, the prompt string cannot contain more than 256 characters. Example This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are omitted, the dialog box is automatically centered for the respective axes. The variable MyValue contains the value entered by the user if the user clicks OK or presses the ENTER key. If the user clicks Cancel, a zero-length string is returned.
Dim Message, Title, Default, MyValue Message = "Enter a value between 1 and 3" ' Set prompt. Title = "InputBox Demo" ' Set title. Default = "1" ' Set default. ' Display message, title, and default value. MyValue = InputBox(Message, Title, Default) ' Use Helpfile and context. The Help button is added automatically. MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10) ' Display dialog box at position 100, 100. MyValue = InputBox(Message, Title, Default, 100, 100)

Example (Microsoft Access) The following example uses the InputBox function to return the user's name. Note that you can't open a Help file from a dialog box created by the InputBox function in Microsoft Access.
Sub Greeting()

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 165 of 1081

Dim strInput As String, strMsg As String strMsg = "Enter your name." strInput = InputBox(Prompt:=strMsg, Title:="User Info", XPos:=2000, _ YPos:=2000) MsgBox "Hello, " & strInput End Sub

InStr Function
Description Returns a Variant (Long) specifying the position of the first occurrence of one string within another. Syntax InStr([start, ]string1, string2[, compare]) The InStr function syntax has these arguments Part Description

start

Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified.

string1

Required. String expression being searched.

string2

Required. String expression sought.

compare

Optional. Specifies the type of string comparison. The compare argument can be omitted, or it can be 0, 1 or 2. Specify 0 (default) to perform a binary comparison. Specify 1 to perform a textual, noncasesensitive comparison. For Microsoft Access only, specify 2 to perform a comparison based on information contained in your database. If compare is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison.

Return Values

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 166 of 1081

If

InStr returns

string1 is zerolength

string1 is Null

Null

string2 is zerolength

start

string2 is Null

Null

string2 is not found

string2 is found within string1

Position at which match is found

start > string2

Remarks The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position. See Also Option Compare statement, StrComp function. Example This example uses the InStr function to return the position of the first occurrence of one string within another.
Dim SearchString, SearchChar, MyPos SearchString ="XXpXXpXXPXXP" SearchChar = "P" ' String to search in. ' Search for "P".

' A textual comparison starting at position 4. Returns 6. MyPos = Instr(4, SearchString, SearchChar, 1) ' A binary comparison starting at position 1. Returns 9. MyPos = Instr(1, SearchString, SearchChar, 0) ' Comparison is binary by default (last argument is omitted). MyPos = Instr(SearchString, SearchChar) ' Returns 9. MyPos = Instr(1, SearchString, "W") ' Returns 0.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 167 of 1081

Int, Fix Functions


Description Returns a value of the type passed to it containing the integer portion of a number. Syntax Int(number) Fix(number) The required number argument is a Double or any valid numeric expression. If number contains Null, Null is returned. Remarks Both Int and Fix remove the fractional part of number and return the resulting integer value. The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts 8.4 to 9, and Fix converts 8.4 to 8. Fix(number) is equivalent to:
Sgn(number) * Int(Abs(number))

See Also Integer data type. Specifics (Microsoft Access) If you use the Fix function to create a new field in a make-table query, the data type of the new field will be dbDouble. You can determine the data type using the DAO Type property. Example This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first negative integer greater than or equal to the number.
Dim MyNumber MyNumber = Int(99.8) MyNumber = Fix(99.2) MyNumber = Int(-99.8) MyNumber = Fix(-99.8) MyNumber = Int(-99.2) MyNumber = Fix(-99.2) ' Returns 99. ' Returns 99. ' Returns -100. ' Returns -99. ' Returns -100. ' Returns -99.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 168 of 1081

Integer Data Type


Description 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. See Also Data type summary, Deftype statements, Long data type, Variant data type.

IPmt Function
Description Returns a Double specifying the interest payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate. Syntax IPmt(rate, per, nper, pv[, fv[, type]]) The IPmt function has these named arguments Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

per

Required. Double specifying payment period in the range 1 through nper.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 169 of 1081

nper

Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pv

Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

fv

Optional. Variant specifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the IPmt function to calculate how much of a payment is interest when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 170 of 1081

payment period for which the interest portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
Dim FVal, Fmt, PVal, APR, TotPmts, PayType, Period, IntPmt, TotInt, Msg Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. Fmt = "###,###,##0.00" ' Define money format. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("How many monthly payments?") PayType = MsgBox("Do you make payments at end of the month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD For Period = 1 To TotPmts ' Total all interest. IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType) TotInt = TotInt + IntPmt Next Period Msg = "You'll pay a total of " & Format(TotInt, Fmt) Msg = Msg & " in interest for this loan." MsgBox Msg ' Display results.

IRR Function
Description Returns a Double specifying the internal rate of return for a series of periodic cash flows (payments and receipts). Syntax IRR(values( )[, guess]) The IRR function has these named arguments Part Description

values ()

Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).

guess

Optional. Variant specifying value you estimate will be returned by IRR. If omitted, guess is 0.1 (10 percent).

Remarks The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at regular intervals. The IRR function uses the order of values within the array to interpret the order of payments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 171 of 1081

and receipts. Be sure to enter your payment and receipt values in the correct sequence. The cash flow for each period doesn't have to be fixed, as it is for an annuity. IRR is calculated by iteration. Starting with the value of guess, IRR cycles through the calculation until the result is accurate to within 0.00001 percent. If IRR can't find a result after 20 tries, it fails. See Also DDB function, FV function, IPmt function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example In this example, the IRR function returns the internal rate of return for a series of 5 cash flows contained in the array Values(). The first array element is a negative cash flow representing business start-up costs. The remaining 4 cash flows represent positive cash flows for the subsequent 4 years. Guess is the estimated internal rate of return.
Dim Guess, Fmt, RetRate, Msg Static Values(5) As Double ' Set up array. Guess = .1 ' Guess starts at 10 percent. Fmt = "#0.00" ' Define percentage format. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = IRR(Values(), Guess) * 100 ' Calculate internal rate. Msg = "The internal rate of return for these five cash flows is " Msg = Msg & Format(RetRate, Fmt) & " percent." MsgBox Msg ' Display internal return rate.

Is Operator
Description Used to compare two object reference variables. Syntax result = object1 Is object2 The Is operator syntax has these parts Part Description

result

Required; any numeric variable.

object1

Required; any object name.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 172 of 1081

object2

Required; any object name.

Remarks If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways. In the following example, A has been set to refer to the same object as B:
Set A = B

The following example makes A and B refer to the same object as C:


Set A = C Set B = C

See Also Comparison operators, Operator precedence. Example This example uses the Is operator to compare two object references. The object variable names are generic and used for illustration purposes only.
Dim MyObject, YourObject, ThisObject, OtherObject, ThatObject, MyCheck Set YourObject = MyObject ' Assign object references. Set ThisObject = MyObject Set ThatObject = OtherObject MyCheck = YourObject Is ThisObject ' Returns True. MyCheck = ThatObject Is ThisObject ' Returns False. ' Assume MyObject <> OtherObject MyCheck = MyObject Is ThatObject ' Returns False.

Example (Microsoft Excel) This example selects the intersection of two named ranges ("rg1" and "rg2") on Sheet1. If the ranges don't intersect, the example displays a message.
Worksheets("Sheet1").Activate Set isect = Application.Intersect(Range("rg1"), Range("rg2")) If isect Is Nothing Then MsgBox "Ranges do not intersect" Else isect.Select End If

This example finds the first occurrence of the word "Phoenix" in column B on Sheet1 and then displays the address of the cell that contains this word. If the word isn't found, the example displays a message.
Set foundCell = If foundCell Is MsgBox "The Else MsgBox "The End If Worksheets("Sheet1").Columns("B").Find("Phoenix") Nothing Then word was not found" word was found in cell " & foundCell.Address

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 173 of 1081

IsArray Function
Description Returns a Boolean value indicating whether a variable is an array. Syntax IsArray(varname) The required varname argument is an identifier specifying a variable. Remarks IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with variants containing arrays. See Also Array function, IsDate function, IsEmpty function, IsError function, IsMissing function, IsNull function, IsNumeric function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsArray function to check if a variable is an array.
Dim MyArray(1 To 5) As Integer, YourArray, MyCheck ' Declare array variables. YourArray = Array(1, 2, 3) ' Use Array function. MyCheck = IsArray(MyArray) ' Returns True. MyCheck = IsArray(YourArray) ' Returns True.

IsDate Function
Description Returns a Boolean value indicating whether an expression can be converted to a date. Syntax IsDate(expression) The required expression argument is a Variant containing a date expression or string expression recognizable as a date or time. Remarks IsDate returns True if the expression is a date or can be converted to a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 174 of 1081

See Also Date data type, IsArray function, IsEmpty function, IsError function, IsMissing function, IsNull function, IsNumeric function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsDate function to determine if an expression can be converted to a date.
Dim MyDate, YourDate, NoDate, MyCheck MyDate = "February 12, 1969": YourDate = #2/12/69#: NoDate = "Hello" MyCheck = IsDate(MyDate) ' Returns True. MyCheck = IsDate(YourDate) ' Returns True. MyCheck = IsDate(NoDate) ' Returns False.

Example (Microsoft Access) The following example prompts the user for a string value, uses the IsDate function to determine whether the string can be converted to a date, and then displays an appropriate message.
Sub CheckDate() Dim strDate As String strDate = InputBox("Enter string to display as a date.") ' Test variable. If IsDate(strDate) Then ' If string is date, format and display in dialog. MsgBox "The date is: " & Format(DateValue(strDate), "Long Date") Else MsgBox "The value you entered is not a date." End If End Sub

IsEmpty Function
Description Returns a Boolean value indicating whether a variable has been initialized. Syntax IsEmpty(expression) The required expression argument is a Variant containing a numeric or string expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name. Remarks IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 175 of 1081

See Also IsArray function, IsDate function, IsError function, IsMissing function, IsNull function, IsNumeric function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsEmpty function to determine whether a variable has been initialized.
Dim MyVar, MyCheck MyCheck = IsEmpty(MyVar) MyVar = Null MyCheck = IsEmpty(MyVar) MyVar = Empty MyCheck = IsEmpty(MyVar) ' Returns True. ' Assign Null. ' Returns False. ' Assign Empty. ' Returns True.

Example (Microsoft Excel) This example sorts the data in the first column on Sheet1 and then deletes any rows that contain duplicate data.
Worksheets("Sheet1").Range("A1").Sort _ key1:=Worksheets("Sheet1").Range("A1") Set currentCell = Worksheets("Sheet1").Range("A1") Do While Not IsEmpty(currentCell) Set nextCell = currentCell.Offset(1, 0) If nextCell.Value = currentCell.Value Then currentCell.EntireRow.Delete End If Set currentCell = nextCell Loop

IsError Function
Description Returns a Boolean value indicating whether an expression is an error value. Syntax IsError(expression) The required expression argument must be a Variant of VarType vbError. Remarks Error values are created by converting real numbers to error values using the CVErr function. The IsError function is used to determine if a numeric expression represents an error. IsError returns True if the expression argument indicates an error; otherwise, it returns False. IsError only returns meaningful information for variants of VarType vbError. See Also CVErr function, IsArray function, IsDate function, IsEmpty function, IsMissing function, IsNull

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 176 of 1081

function, IsNumeric function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsError function to check if a numeric expression is an error value. The CVErr function is used to return an Error Variant from a user-defined function. Assume UserFunction is a user-defined function procedure that returns an error value; for example, a return value assigned with the statement UserFunction = CVErr(32767), where 32767 is a userdefined number.
Dim ReturnVal, MyCheck ReturnVal = UserFunction() MyCheck = IsError(ReturnVal)

' Returns True.

IsMissing Function
Description Returns a Boolean value indicating whether an optional Variant argument has been passed to a procedure. Syntax IsMissing(argname) The required argname argument contains the name of an optional Variant procedure argument. Remarks Use the IsMissing function to detect whether or not optional Variant arguments have been provided in calling a procedure. IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False. If IsMissing returns True for an argument, use of the missing argument in other code may cause a user-defined error. If IsMissing is used on a ParamArray argument, it always returns False. To detect an empty ParamArray, test to see if the array's upper bound is less than its lower bound. See Also Function statement, IsArray function, IsDate function, IsEmpty function, IsError function, IsNull function, IsNumeric function, IsObject function, Property Get statement, Property Let statement, Property Set statement, Sub statement, TypeName function, Variant data type, VarType function. Example This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure. Note that Optional arguments can now have default values and types other than Variant.
Dim ReturnValue ' The following statements call the user-defined function procedure. ReturnValue = ReturnTwice() ' Returns Null.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 177 of 1081

ReturnValue = ReturnTwice(2)

' Returns 4.

' Function procedure definition. Function ReturnTwice(Optional A) If IsMissing(A) Then ' If argument is missing, return a Null. ReturnTwice = Null Else ' If argument is present, return twice the value. ReturnTwice = A * 2 End If End Function

IsNull Function
Description Returns a Boolean value that indicates whether an expression contains no valid data (Null). Syntax IsNull(expression) The required expression argument is a Variant containing a numeric expression or string expression. Remarks IsNull returns True if expression is Null; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the entire expression. The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zerolength string (" "), which is sometimes referred to as a null string. Important Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null and, therefore, False. See Also IsArray function, IsDate function, IsEmpty function, IsError function, IsMissing function, IsNumeric function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsNull function to determine if a variable contains a Null.
Dim MyVar, MyCheck MyCheck = IsNull(MyVar) MyVar = "" MyCheck = IsNull(MyVar) MyVar = Null MyCheck = IsNull(MyVar) ' Returns False. ' Returns False. ' Returns True.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 178 of 1081

Example (Microsoft Access) The following example uses the IsNull function to determine whether the value of a control is Null. If it is, a message prompts the user to enter data. If the value is not Null, a message displays the value of the control.
Sub ControlValue(ctlText As Control) Dim strMsg As String ' Check that control is text box. If ctlText.ControlType = acTextBox Then ' If value of control is Null, prompt for data. If IsNull(ctlText.Value) Then strMsg = "No data in the field '" & ctlText.Name & "'." _ & vbCrLf & "Please enter data for this field now." If MsgBox(strMsg, vbQuestion) = vbOK Then Exit Sub End If ' If value is not Null, display value. Else MsgBox (ctlText.Value) End If End If End Sub

Example (Microsoft Excel) This example creates a list of registered functions, placing each one in a separate row on Sheet1. Column A contains the full path and file name of the DLL or code resource, column B contains the function name, and column C contains the code for the argument data type.
theArray = Application.RegisteredFunctions If IsNull(theArray) Then MsgBox "No registered functions" Else For i = LBound(theArray) To UBound(theArray) For j = 1 To 3 Worksheets("Sheet1").Cells(i, j).Formula = theArray(i, j) Next j Next i End If

IsNumeric Function
Description Returns a Boolean value indicating whether an expression can be evaluated as a number. Syntax IsNumeric(expression) The required expression argument is a Variant containing a numeric expression or string expression. Remarks IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 179 of 1081

IsNumeric returns False if expression is a date expression. See Also IsArray function, IsDate function, IsEmpty function, IsError function, IsMissing function, IsNull function, IsObject function, TypeName function, Variant data type, VarType function. Example This example uses the IsNumeric function to determine if a variable can be evaluated as a number.
Dim MyVar, MyCheck MyVar = "53" MyCheck = IsNumeric(MyVar) MyVar = "459.95" MyCheck = IsNumeric(MyVar) MyVar = "45 Help" MyCheck = IsNumeric(MyVar) ' Assign value. ' Returns True. ' Assign value. ' Returns True. ' Assign value. ' Returns False.

IsObject Function
Description Returns a Boolean value indicating whether an identifier represents an object variable. Syntax IsObject(identifier) The required identifier argument is a variable name. Remarks IsObject is useful only in determining whether a Variant is of VarType vbObject. This could occur if the Variant actually references (or once referenced) an object, or if it contains Nothing. IsObject returns True if identifier is a variable declared with Object type or any valid class type, or if identifier is a Variant of VarType vbObject, or a user-defined object; otherwise, it returns False. IsObject returns True even if the variable has been set to Nothing. Use error trapping to be sure that an object reference is valid. You can use the IsNothing function determine if an object reference has been set to Nothing. See Also IsArray function, IsDate function, IsEmpty function, IsError function, IsMissing function, IsNull function, IsNumeric function, Object data type, Set statement, TypeName function, Variant data type, VarType function. Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 180 of 1081

This example uses the IsObject function to determine if an identifier represents an object variable. MyObject and YourObject are object variables of the same type. They are generic names used for illustration purposes only.
Dim MyInt As Integer, YourObject, MyCheck ' Declare variables. Dim MyObject As Object Set YourObject = MyObject ' Assign an object reference. MyCheck = IsObject(YourObject) ' Returns True. MyCheck = IsObject(MyInt) ' Returns False.

Example (Microsoft Access) The following example uses the IsObject function to check whether an argument passed to the function is an object.
Sub CheckObject(varAny As Variant) Dim varX as Variant If IsObject(varAny) Then Set varX = varAny Else varX = varAny End If End Sub

Item Method
Applies To Collection object. Description Returns a specific member of a Collection object either by position or by key. Syntax object.Item(index) The Item method syntax has the following object qualifier and part Part Description

object

Required. An object expression that evaluates to an object in the Applies To list.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 181 of 1081

index

Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks If the value provided as index doesn't match any existing member of the collection, an error occurs. The Item method is the default method for a collection. Therefore, the following lines of code are equivalent:
Print MyCollection(1) Print MyCollection.Item(1)

See Also Add method, Caption property ("Extensibility Object Model Language Reference"), Count property ("Extensibility Object Model Language Reference"), Name property ("Extensibility Object Model Language Reference"), Remove method. Example This example uses the Item method to retrieve a reference to an object in a collection. Assuming Birthdays is a Collection object, the following code retrieves from the collection references to the objects representing Bill Smith's birthday and Adam Smith's birthday, using the keys "SmithBill" and "SmithAdam" as the index arguments. Note that the first call explicitly specifies the Item method, but the second does not. Both calls work because the Item method is the default for a Collection object. The references, assigned to SmithBillBD and SmithAdamBD using Set, can be used to access the properties and methods of the specified objects. To run this code, create the collection and populate it with at least the two referenced members.
Dim Dim Dim Set Set SmithBillBD SmithAdamBD Birthdays SmithBillBD SmithAdamBD As Object As Object = Birthdays.Item("SmithBill") = Birthdays("SmithAdam")

Example (Extensibility Object Model) The following example contains two ways to display a specific member of the CodePanes collection, one using the Item method.
Application.VBE.CodePanes.Item(2).Show Application.VBE.CodePanes(2).Show

Kill Statement

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 182 of 1081

Description Deletes files from a disk. Syntax Kill pathname The required pathname argument is a string expression that specifies one or more file names to be deleted. The pathname may include the directory or folder, and the drive. Remarks Kill supports the use of multiple-character ( *) and single-character ( ?) wildcards to specify multiple files. An error occurs if you try to use Kill to delete an open file. Note To delete directories, use the RmDir statement. See Also MacID function, RmDir statement. Specifics (Macintosh) In Microsoft Windows, Kill supports the use of multiple character (*) and single character (?) wildcards to specify multiple files. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files. Since the Macintosh doesn't support the wildcards, use the file type to identify groups of files to delete. You can use the MacID function to specify file type instead of repeating the command with separate file names. For example, the following statement deletes all TEXT files in the current folder.
Kill MacID("TEXT")

If you use the MacID function with Kill in Microsoft Windows, an error occurs. Example This example uses the Kill statement to delete a file from a disk. Since the Macintosh doesn't support wildcards, you can use the MacID function to specify the file type instead of the file name.
' Assume TESTFILE is a file containing some data. Kill "TestFile" ' Delete file. ' In Microsoft Windows: ' Delete all *.TXT files in current directory. Kill "*.TXT" ' On the Macintosh: ' Use the MacID function to delete all PICT files in current folder Kill MacID("PICT")

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 183 of 1081

LastDLLError Property
Applies To Err object. Description Returns a system error code produced by a call to a dynamic-link library (DLL). Read-only. Remarks The LastDLLError property applies only to DLL calls made from Visual Basic code. When such a call is made, the called function usually returns a code indicating success or failure, and the LastDLLError property is filled. Check the documentation for the DLL's functions to determine the return values that indicate success or failure. Whenever the failure code is returned, the Visual Basic application should immediately check the LastDLLError property. No exception is raised when the LastDLLError property is set. See Also Declare statement, Description property, Err object, HelpContext property, HelpContextID property ("Extensibility Object Model Language Reference"), HelpFile property, Number property, Source property. Example When pasted into a UserForm module, the following code causes an attempt to call a DLL function. The call fails because the argument that is passed in (a null pointer) generates an error, and in any event, SQL can't be cancelled if it isn't running. The code following the call checks the return of the call, and then prints at the LastDLLError property of the Err object to reveal the error code.
Private Declare Function SQLCancel Lib "ODBC32.dll" _ (ByVal hstmt As Long) As Integer Private Sub UserForm_Click() Dim RetVal ' Call with invalid argument. RetVal = SQLCancel(myhandle&) ' Check for SQL error code. If RetVal = -2 Then ' Display the information code. MsgBox "Error code is :" & Err.LastDllError End If End Sub

LBound Function
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 184 of 1081

Returns a Long containing the smallest available subscript for the indicated dimension of an array. Syntax LBound(arrayname[, dimension]) The LBound function syntax has these parts: Part Description

arrayname

Required. Name of the array variable; follows standard variable naming conventions.

dimension

Optional; Variant (Long). Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension. LBound returns the values in the following table for an array with the following dimensions:
Dim A(1 To 100, 0 To 3, -3 To 4)

Statement

Return Value

LBound(A, 1)

LBound(A, 2)

LBound(A, 3)

The default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement. The base of an array created with the Array function is zero; it is unaffected by Option Base. Arrays for which dimensions are set using the To clause in a Dim, Private, Public, ReDim, or

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 185 of 1081

Static statement can have any integer value as a lower bound. See Also Dim statement, Option Base statement, Private statement, Public statement, ReDim statement, Static statement, UBound function. Example This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array. Use the Option Base statement to override the default base array subscript value of 0.
Dim Lower Dim MyArray(1 To 10, 5 To 15, 10 To 20) Dim AnyArray(10) Lower = Lbound(MyArray, 1) Lower = Lbound(MyArray, 3) Lower = Lbound(AnyArray) ' Declare array variables. ' Returns 1. ' Returns 10. ' Returns 0 or 1, depending ' on setting of Option Base.

Example (Microsoft Excel) This example writes the elements of the first custom list in column one on Sheet1.
listArray = Application.GetCustomListContents(1) For i = LBound(listArray, 1) To UBound(listArray, 1) Worksheets("sheet1").Cells(i, 1).Value = listArray(i) Next i

This example assumes that you used an external data source to create a PivotTable on Sheet1 in the active workbook. The example inserts the SQL connection string and query string into a new worksheet.
Set newSheet = ActiveWorkbook.Worksheets.Add sdArray = Worksheets("Sheet1").UsedRange.PivotTable.SourceData For i = LBound(sdArray) To UBound(sdArray) newSheet.Cells(i, 1) = sdArray(i) Next i

LCase Function
Description Returns a String that has been converted to lowercase. Syntax LCase(string) The required string argument is any valid string expression. If string contains Null, Null is returned. Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 186 of 1081

Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged. See Also UCase function. Example This example uses the LCase function to return a lowercase version of a string.
Dim UpperCase, LowerCase Uppercase = "Hello World 1234" Lowercase = Lcase(UpperCase) ' String to convert. ' Returns "hello world 1234".

Left Function
Description Returns a Variant (String) containing a specified number of characters from the left side of a string. Syntax Left(string, length) The Left function syntax has these named arguments: Part Description

string

Required. String expression from which the leftmost characters are returned. If string contains Null, Null is returned.

length

Required; Variant (Long). Numeric expression indicating how many characters to return. If 0, a zero-length string (" ") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks To determine the number of characters in string, use the Len function. Note Use the LeftB function with byte data contained in a string. Instead of specifying the

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 187 of 1081

number of characters to return, length specifies the number of bytes. See Also Len function, Mid function, Right function. Example This example uses the Left function to return a specified number of characters from the left side of a string.
Dim AnyString, MyStr AnyString = "Hello World" MyStr = Left(AnyString, 1) MyStr = Left(AnyString, 7) MyStr = Left(AnyString, 20) ' Define string. ' Returns "H". ' Returns "Hello W". ' Returns "Hello World".

Len Function
Description Returns a Long containing the number of characters in a string or the number of bytes required to store a variable. Syntax Len(string | varname) The Len function syntax has these parts: Part Description

string

Any valid string expression. If string contains Null, Null is returned.

Varname

Any valid variable name. If varname contains Null, Null is returned. If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains.

Remarks One (and only one) of the two possible arguments must be specified. With user-defined types, Len returns the size as it will be written to the file. Note Use the LenB function with byte data contained in a string. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 188 of 1081

string. With user-defined types, LenB returns the in-memory size, including any padding between elements. Note Len may not be able to determine the actual number of storage bytes required when used with variable-length strings in user-defined data types. See Also Data type summary, InStr function. Example This example uses the Len function to return the number of characters in a string or the number of bytes required to store a variable. The Type...End Type block defining CustomerRecord must be preceded by the keyword Private if it appears in a class module. In a standard module, a Type statement can be Public.
Type CustomerRecord ID As Integer Name As String * 10 Address As String * 30 End Type ' Define user-defined type. ' Place this definition in a ' standard module.

Dim Customer As CustomerRecord ' Declare variables. Dim MyInt As Integer, MyCur As Currency Dim MyString, MyLen MyString = "Hello World" ' Initialize variable. MyLen = Len(MyInt) ' Returns 2. MyLen = Len(Customer) ' Returns 42. MyLen = Len(MyString) ' Returns 11. MyLen = Len(MyCur) ' Returns 8.

Let Statement
Description Assigns the value of an expression to a variable or property. Syntax [Let] varname = expression The Let statement syntax has these parts: Part Description

Let

Optional. Explicit use of the Let keyword is a matter of style, but it is usually omitted.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 189 of 1081

varname

Required. Name of the variable or property; follows standard variable naming conventions.

expression

Required. Value assigned to the variable or property.

Remarks A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable. You can't assign string expressions to numeric variables, and you can't assign numeric expressions to string variables. If you do, an error occurs at compile time. Variant variables can be assigned either string or numeric expressions. However, the reverse is not always true. Any Variant except a Null can be assigned to a string variable, but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable. Use the IsNumeric function to determine if the Variant can be converted to a number. Caution Assigning an expression of one numeric type to a variable of a different numeric type coerces the value of the expression into the numeric type of the resulting variable. Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables. See Also Const statement, Data type summary, IsNumeric function, LSet statement, Set statement, Variant data type. Example This example assigns the values of expressions to variables using both the explicit and implicit Let statement.
Dim MyStr, MyInt ' The following variable assignments use the Let statement. Let MyStr = "Hello World" Let MyInt = 5

The following are the same assignments without the Let statement.
Dim MyStr, MyInt MyStr = "Hello World" MyInt = 5

Like Operator
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 190 of 1081

Used to compare two strings. Syntax result = string Like pattern The Like operator syntax has these parts: Part Description

result

Required; any numeric variable.

string

Required; any string expression.

pattern

Required; any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks If string matches pattern, result is True; if there is no match, result is False. If either string or pattern is Null, result is Null. The behavior of the Like operator depends on the Option Compare statement. The default stringcomparison method for each module is Option Compare Binary. Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. In the following example, a typical binary sort order is shown: A<B<E<Z<a<b<e<z<<<<<< Option Compare Text results in string comparisons based on a case-insensitive, textual sort order determined by your system's locale. When you sort The same characters using Option Compare Text, the following text sort order is produced: (A=a) < (=) < (B=b) < (E=e) < (=) < (Z=z) < (=) Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 191 of 1081

Characters in pattern

Matches in string

Any single character.

Zero or more characters.

Any single digit (0 9).

[charlist]

Any single character in charlist.

[!charlist]

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits. Note To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character. By using a hyphen (-) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A Z. Multiple ranges are included within the brackets without delimiters. The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the Option Compare Binary example, the range [AE] matches A, B and E. With Option Compare Text, [AE] matches A, a, , , B, b, E, e. The range does not match or because accented characters fall after unaccented characters in the sort order. Other important rules for pattern matching include the following: An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself. A hyphen (-) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters. When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not. The character sequence [] is considered a zero-length string (" "). In some languages, there are special characters in the alphabet that represent two separate characters. For example, several languages use the character "" to represent the characters

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 192 of 1081

"a" and "e" when they appear together. The Like operator recognizes that the single special character and the two individual characters are equivalent. When a language that uses a special character is specified in the system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2 -character sequence in string. See Also Comparison operators, InStr function, Operator precedence, Option Compare statement, StrComp function. Specifics (Macintosh) On the Macintosh, sort order is determined by the character set. Specifics (Microsoft Access) In Microsoft Access, you can use the Like operator in a query expression or in a calculated control on a form or report. You can use the Like operator to specify inexact criteria in the query design grid. For example, if you type Like "C*" in the Criteria row of the query design grid, the query returns all field values beginning with the letter C. In a parameter query, you can use the Like operator to prompt the user for a pattern to search for. For example, suppose you have an Employees table that includes a LastName field. In the Query window, create a new query by adding the Employees table and dragging the LastName field to the grid. Enter the following expression in the Criteria cell:
Like [Enter first few letters of name:]&"*"

When the query is run, a dialog box prompts the user with "Enter first few letters of name:". If the user types Sm in the dialog box, the query looks for the pattern Sm* that is, all names beginning with the letters Sm. You can use the Like operator in an expression as a setting for the ValidationRule property. For example, you can restrict data entered in a text box control to an inexact specification. In the ValidationRule property of the text box, enter the following expression:
Like "P[A-F]###"

Data entered in this text box must now begin with the letter P, followed by any letter between A and F and three digits. Example This example uses the Like operator to compare a string to a pattern.
Dim MyCheck MyCheck = "aBBBa" Like "a*a" MyCheck = "F" Like "[A-Z]" MyCheck = "F" Like "[!A-Z]" MyCheck = "a2a" Like "a#a" ' Returns True. ' Returns True. ' Returns False. ' Returns True.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 193 of 1081

MyCheck = "aM5b" Like "a[L-P]#[!c-e]" MyCheck = "BAT123khg" Like "B?T*" MyCheck = "CAT123khg" Like "B?T*"

' Returns True. ' Returns True. ' Returns False.

Example (Microsoft Excel) This example deletes every defined name that contains "temp". The Option Compare Text statement must be included at the top of any module that contains this example.
For Each nm In ActiveWorkbook.Names If nm.Name Like "*temp*" Then nm.Delete End If Next nm

This example adds an arrowhead to every shape on Sheet1 that has the word "Line" in its name.
For Each d In Worksheets("Sheet1").DrawingObjects If d.Name Like "*Line*" Then d.ArrowHeadLength = xlLong d.ArrowHeadStyle = xlOpen d.ArrowHeadWidth = xlNarrow End If Next

Line Input # Statement


Description Reads a single line from an open sequential file and assigns it to a String variable. Syntax Line Input #filenumber, varname The Line Input # statement syntax has these parts: Part Description

filenumber

Required. Any valid file number.

varname

Required. Valid Variant or String variable name.

Remarks Data read with Line Input # is usually written from a file with Print #. The Line Input # statement reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage returnlinefeed (Chr(13) + Chr(10)) sequence. Carriage returnlinefeed sequences are skipped rather than appended to the character string.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 194 of 1081

See Also Chr function, Input # statement. Example This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. This example assumes that TESTFILE is a text file with a few lines of sample data.
Dim TextLine Open "TESTFILE" For Input As #1 Do While Not EOF(1) Line Input #1, TextLine Debug.Print TextLine Loop Close #1 ' Open file. ' Loop until end of file. ' Read line into variable. ' Print to Debug window. ' Close file.

Load Statement
Description Loads an object but doesn't show it. Syntax Load object The object placeholder represents an object expression that evaluates to an object in the Applies To list. Remarks When an object is loaded, it is placed in memory, but isn't visible. Use the Show method to make the object visible. Until an object is visible, a user can't interact with it. The object can be manipulated programatically in its Initialize event procedure. See Also Activate, Deactivate events, Hide method, StartUpPosition property, Unload statement. Example In the following example, UserForm2 is loaded during UserForm1's Initialize event. Subsequent clicking on UserForm2 reveals UserForm1.
' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event of UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 195 of 1081

' This is the click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub

Loc Function
Description Returns a Long specifying the current read/write position within an open file. Syntax Loc(filenumber) The required filenumber argument is any valid Integer file number. Remarks The following describes the return value for each file access mode: Mode Return value

Random

Number of the last record read from or written to the file.

Sequential

Current byte position in the file divided by 128. However, information returned by Loc for sequential files is neither used nor required.

Binary

Position of the last byte read or written.

See Also EOF function, LOF function, Seek function, Seek statement. Example This example uses the Loc function to return the current read/write position within an open file. This example assumes that TESTFILE is a text file with a few lines of sample data.
Dim MyLocation, MyLine Open "TESTFILE" For Binary As #1 Do While MyLocation < LOF(1) MyLine = MyLine & Input(1, #1) MyLocation = Loc(1) ' Print to Debug window. ' Open file just created. ' Loop until end of file. ' Read character into variable. ' Get current position within file.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 196 of 1081

Debug.Print MyLine; Tab; MyLocation Loop Close #1

' Close file.

Lock, Unlock Statements


Description Controls access by other processes to all or part of a file opened using the Open statement. Syntax Lock [#]filenumber[, recordrange] ... Unlock [#]filenumber[, recordrange] The Lock and Unlock statement syntax has these parts: Part Description

filenumber

Required. Any valid file number.

recordrange

Optional. The range of records to lock or unlock.

Settings The recordrange argument settings are: recnumber | [start] To end Setting Description

recnumber

Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.

start

Number of the first record or byte to lock or unlock.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 197 of 1081

end

Number of the last record or byte to lock or unlock.

Remarks The Lock and Unlock statements are used in environments where several processes might need access to the same file. Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly. The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you specify just one record, then only that record is locked or unlocked. If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file. If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end. Caution Be sure to remove all locks with an Unlock statement before closing a file or quitting your program. Failure to remove locks produces unpredictable results. See Also Open statement. Example This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

Dim MyRecord As Record, RecordNumber ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord) RecordNumber = 4 ' Define record number. Lock #1, RecordNumber ' Lock record. Get #1, RecordNumber, MyRecord ' Read record. MyRecord.ID = 234 ' Modify record. MyRecord.Name = "John Smith" Put #1, RecordNumber, MyRecord ' Write modified record. Unlock #1, RecordNumber ' Unlock current record. Close #1 ' Close file.

LOF Function
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 198 of 1081

Returns a Long representing the size, in bytes, of a file opened using the Open statement. Syntax LOF(filenumber) The required filenumber argument is an Integer containing a valid file number. Note Use the FileLen function to obtain the length of a file that is not open.

See Also EOF function, FileLen function, Loc function, Open statement. Example This example uses the LOF function to determine the size of an open file. This example assumes that TESTFILE is a text file containing sample data.
Dim FileLength Open "TESTFILE" For Input As #1 FileLength = LOF(1) Close #1 ' Open file. ' Get length of file. ' Close file.

Log Function
Description Returns a Double specifying the natural logarithm of a number. Syntax Log(number) The required number argument is a Double or any valid numeric expression greater than zero. Remarks The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282. You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows: Logn(x) = Log(x) / Log(n) The following example illustrates a custom Function that calculates base-10 logarithms:
Static Function Log10(X) Log10 = Log(X) / Log(10#) End Function

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 199 of 1081

See Also Exp function. Example This example uses the Log function to return the natural logarithm of a number.
Dim MyAngle, MyLog ' Define angle in radians. MyAngle = 1.3 ' Calculate inverse hyperbolic sine. MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1))

Long Data Type


Description 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 (&). See Also Data Type Summary, Deftype statements, Integer data type.

LSet Statement
Description Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type. Syntax LSet stringvar = string LSet varname1 = varname2 The LSet statement syntax has these parts: Part Description

stringvar

Required. Name of string variable.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 200 of 1081

string

Required. String expression to be leftaligned within stringvar.

varname1

Required. Variable name of the user-defined type being copied to.

varname2

Required. Variable name of the user-defined type being copied from.

Remarks LSet replaces any leftover characters in stringvar with spaces. If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar. Warning Using LSet to copy a variable of one user-defined type into a variable of a different user-defined type is not recommended. Copying data of one data type into space reserved for a different data type can cause unpredictable results. When you copy a variable from one user-defined type to another, the binary data from one variable is copied into the memory space of the other, without regard for the data types specified for the elements. See Also Data type summary, RSet statement. Example This example uses the LSet statement to left align a string within a string variable. Although LSet can also be used to copy a variable of one user-defined type to another variable of a different, but compatible, user-defined type, this practice is not recommended. Due to the varying implementations of data structures among platforms, such a use of LSet can't be guaranteed to be portable.
Dim MyString MyString = "0123456789" Lset MyString = "<-Left" ' Initialize string. ' MyString contains "<-Left

".

LTrim, RTrim, and Trim Functions


Description Returns a Variant (String) containing a copy of a specified string without leading spaces ( LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 201 of 1081

Syntax LTrim(string) RTrim(string) Trim(string) The required string argument is any valid string expression. If string contains Null, Null is returned. See Also Left function, Right function. Example This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string variable. It uses the Trim function to strip both types of spaces.
Dim MyString, TrimString MyString = " <-Trim-> " ' Initialize string. TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ". TrimString = RTrim(MyString) ' TrimString = " <-Trim->". TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->". ' Using the Trim function alone achieves the same result. TrimString = Trim(MyString) ' TrimString = "<-Trim->".

MacID Function
Description Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate. Syntax MacID(constant) The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, MSWD (Microsoft Word), XCEL (Microsoft Excel), and so on. Remarks MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:
Dir("SomePath", MacID("TEXT"))

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 202 of 1081

MacID is used with Shell and AppActivate to specify an application using the application's unique signature. See Also AppActivate statement, Dir function, Kill statement. Example This example shows various uses of the MacID function. The MacID function is not available in Microsoft Windows.
Dim filename, ReturnValue ' Return the first text file in folder HD:MY FOLDER. FileName = Dir("HD:MY FOLDER:", MacId("TEXT")) ' Deletes all "TEXT" files in the current folder. Kill MacId("TEXT") ' Run Microsoft Excel. ReturnValue = Shell(MacId("XCEL")) ' Activate Microsoft Word. AppActivate MacId("MSWD")

MacScript Function
Description Executes an AppleScript script and returns a value returned by the script, if any. Syntax MacScript script The script argument is a String expression. The String expression either can be a series of AppleScript commands or can specify the name of an AppleScript script or a script file. Remarks Multiline scripts can be created by embedding carriage-return characters (Chr(13)). See Also Chr Function. Example This example uses the MacScript function to open the Choose File dialog box (the Macintosh standard-file dialog). The full path of the file chosen by the user is returned. If appropriate, the path specification is preceded by the type of the file.
ThePath$ = Macscript("ChooseFile")

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 203 of 1081

Mid Function
Description Returns a Variant (String) containing a specified number of characters from a string. Syntax Mid(string, start[, length]) The Mid function syntax has these named arguments: Part Description

string

Required. String expression from which characters are returned. If string contains Null, Null is returned.

start

Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string (" ").

length

Optional; Variant (Long). Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks To determine the number of characters in string, use the Len function. Note Use the MidB function with byte data contained in a string. Instead of specifying the number of characters, the arguments specify numbers of bytes. See Also Left function, Len function, LTrim, RTrim, and Trim functions, Mid statement, Right function. Example This example uses the Mid function to return a specified number of characters from a string.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 204 of 1081

Dim MyString, FirstWord, LastWord, MidWords MyString = "Mid Function Demo" ' Create text string. FirstWord = Mid(MyString, 1, 3) ' Returns "Mid". LastWord = Mid(MyString, 14, 4) ' Returns "Demo". MidWords = Mid(MyString, 5) ' Returns "Function Demo".

Mid Statement
Description Replaces a specified number of characters in a Variant (String) variable with characters from another string. Syntax Mid(stringvar, start[, length]) = string The Mid statement syntax has these parts: Part Description

stringvar

Required. Name of string variable to modify.

start

Required; Variant (Long). Character position in stringvar where the replacement of text begins.

length

Optional; Variant (Long). Number of characters to replace. If omitted, all of string is used.

string

Required. String expression that replaces part of stringvar.

Remarks The number of characters replaced is always less than or equal to the number of characters in stringvar. Note Use the MidB statement with byte data contained in a string. In the MidB statement, start specifies the byte position within stringvar where replacement begins and length specifies the numbers of bytes to replace. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 205 of 1081

Mid function. Example This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.
Dim MyString MyString = "The dog jumps" Mid(MyString, 5, 3) = "fox" Mid(MyString, 5) = "cow" Mid(MyString, 5) = "cow jumped over" Mid(MyString, 5, 3) = "duck" ' Initialize string. ' MyString = "The fox jumps". ' MyString = "The cow jumps". ' MyString = "The cow jumpe". ' MyString = "The duc jumpe".

Minute Function
Description Returns a Variant (Integer) specifying a whole number between 0 and 59, inclusive, representing the minute of the hour. Syntax Minute(time) The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned. See Also Day function, Hour function, Now function, Second function, Time function, Time statement. Example This example uses the Minute function to obtain the minute of the hour from a specified time. In the development environment, the time literal is displayed in short time format using the locale settings of your code.
Dim MyTime, MyMinute MyTime = #4:35:17 PM# MyMinute = Minute(MyTime) ' Assign a time. ' MyMinute contains 35.

MIRR Function
Description Returns a Double specifying the modified internal rate of return for a series of periodic cash flows (payments and receipts).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 206 of 1081

Syntax MIRR(values( ), finance_rate, reinvest_rate) The MIRR function has these named arguments: Part Description

values( )

Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).

finance_rate

Required. Double specifying interest rate paid as the cost of financing.

reinvest_rate

Required. Double specifying interest rate received on gains from cash reinvestment.

Remarks The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates. The MIRR function takes into account both the cost of the investment (finance_rate) and the interest rate received on reinvestment of cash (reinvest_rate). The finance_rate and reinvest_rate arguments are percentages expressed as decimal values. For example, 12 percent is expressed as 0.12. The MIRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence. See Also DDB function, FV function, IPmt function, IRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the MIRR function to return the modified internal rate of return for a series of cash flows contained in the array Values(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvestment.
Dim LoanAPR, InvAPR, Fmt, RetRate, Msg Static Values(5) As Double LoanAPR = .1 InvAPR = .12 Fmt = "#0.00" ' Set up array. ' Loan rate. ' Reinvestment rate. ' Define money format.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 207 of 1081

Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = MIRR(Values(), LoanAPR, InvAPR) ' Calculate internal rate. Msg = "The modified internal rate of return for these five cash flows is" Msg = Msg & Format(Abs(RetRate) * 100, Fmt) & "%." MsgBox Msg ' Display internal return ' rate.

MkDir Statement
Description Creates a new directory or folder. Syntax MkDir path The required path argument is a string expression that identifies the directory or folder to be created. The path may include the drive. If no drive is specified, MkDir creates the new directory or folder on the current drive. See Also ChDir statement, CurDir function, RmDir statement. Example This example uses the MkDir statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive.
MkDir "MYDIR" ' Make new directory or folder.

Mod Operator
Description Used to divide two numbers and return only the remainder. Syntax result = number1 Mod number2 The Mod operator syntax has these parts:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 208 of 1081

Part

Description

result

Required; any numeric variable.

number1

Required; any numeric expression.

number2

Required; any numeric expression.

Remarks The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (result) equals 5.
A = 19 Mod 6.7

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is Null. Any expression that is Empty is treated as 0. See Also Operator precedence. Example This example uses the Mod operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer.
Dim MyResult MyResult = 10 Mod 5 MyResult = 10 Mod 3 MyResult = 12 Mod 4.3 MyResult = 12.6 Mod 5 ' Returns 0. ' Returns 1. ' Returns 0. ' Returns 3.

Example (Microsoft Excel) This example sets the column width of every other column on Sheet1 to 4 points.
For Each col In Worksheets("Sheet1").Columns If col.Column Mod 2 = 0 Then col.ColumnWidth = 4 End If Next col

This example sets the row height of every other row on Sheet1 to 4 points.
For Each rw In Worksheets("Sheet1").Rows If rw.Row Mod 2 = 0 Then rw.RowHeight = 4

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 209 of 1081

End If Next rw

This example selects every other item in list box one on Sheet1.
Dim items() As Boolean Set lbox = Worksheets("Sheet1").ListBoxes(1) ReDim items(1 To lbox.ListCount) For i = 1 To lbox.ListCount If i Mod 2 = 1 Then items(i) = True Else items(i) = False End If Next lbox.MultiSelect = xlExtended lbox.Selected = items

Month Function
Description Returns a Variant (Integer) specifying a whole number between 1 and 12, inclusive, representing the month of the year. Syntax Month(date) The required date argument is any Variant, numeric expression, string expression, or any combination, that can represent a date. If date contains Null, Null is returned. See Also Date function, Date statement, Day function, Now function, Weekday function, Year function. Example This example uses the Month function to obtain the month from a specified date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.
Dim MyDate, MyMonth MyDate = #February 12, 1969# MyMonth = Month(MyDate) ' Assign a date. ' MyMonth contains 2.

Example (Microsoft Access) See the DateSerial function example (Microsoft Access).

MsgBox Function
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 210 of 1081

Displays a message in a dialog box, waits for the user to click a button, and returns an Integer indicating which button the user clicked. Syntax MsgBox(prompt[, buttons] [, title] [,, helpfile , context]) The MsgBox function syntax has these named arguments: Part Description

prompt

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return linefeed character combination (Chr (13) & Chr(10)) between each line.

buttons

Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If omitted, the default value for buttons is 0.

title

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

helpfile

Optional. String expression that identifies the Help file to use to provide contextsensitive Help for the dialog box. If helpfile is provided, context must also be provided.

context

Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. If context is provided, helpfile must also be provided.

Settings

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 211 of 1081

The buttons argument settings are: Constant Value Description

vbOKOnly

Display OK button only.

vbOKCancel

Display OK and Cancel buttons.

vbAbortRetryIgnore

Display Abort, Retry, and Ignore buttons.

vbYesNoCancel

Display Yes, No, and Cancel buttons.

vbYesNo

Display Yes and No buttons.

vbRetryCancel

Display Retry and Cancel buttons.

vbCritical

16

Display Critical Message icon.

vbQuestion

32

Display Warning Query icon.

vbExclamation

48

Display Warning Message icon.

vbInformation

64

Display Information Message icon.

vbDefaultButton1

First button is default.

vbDefaultButton2

256

Second button is default.

vbDefaultButton3

512

Third button is default.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 212 of 1081

vbDefaultButton4

768

Fourth button is default.

vbApplicationModal

Application modal; the user must respond to the message box before continuing work in the current application.

vbSystemModal

4096

System modal; all applications are suspended until the user responds to the message box.

The first group of values (05) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the buttons argument, use only one number from each group. Note These constants are specified by Visual Basic for Applications. As a result, the names can be used anywhere in your code in place of the actual values. Return Values Constant Value Description

vbOK

OK

vbCancel

Cancel

vbAbort

Abort

vbRetry

Retry

vbIgnore

Ignore

vbYes

Yes

vbNo

No

Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 213 of 1081

When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context. Some host applications, for example, Microsoft Excel, also automatically add a Help button to the dialog box. If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is clicked. Note To specify more than the first named argument, you must use MsgBox in an expression. To omit some positional arguments, you must include the corresponding comma delimiter. See Also InputBox function, MsgBox action. Specifics (Microsoft Access) You can use the MsgBox function in Microsoft Access to create a formatted error message similar to built-in error messages displayed by Microsoft Access. This function permits you to supply a string in three sections for the prompt argument. You separate the sections with the at sign (@). The following example displays a formatted dialog box with a sectioned string. The first section of text in the string is displayed as a bold heading. The second section is displayed as plain text beneath that heading. The third section is displayed as plain text beneath the heading "Solution," which the function provides for you.
MsgBox "Wrong button!@This button doesn't work.@Try another.", _ vbOKOnly + vbExclamation

Note To display a message box without an icon in Microsoft Access, simply omit any constant that would denote an icon, or supply a value of zero for the buttons argument, as in the following example.
MsgBox "No icons included.", 0

Specifics (Microsoft Excel) In Microsoft Excel, the prompt string cannot contain more than 256 characters. Example This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No button is specified as the default response. The value returned by the MsgBox function depends on the button chosen by the user. This example assumes that DEMO.HLP is a Help file that contains a topic with a Help context number equal to 1000.
Dim Msg, Style, Title, Help, Ctxt, Response, MyString Msg = "Do you want to continue ?" ' Define message. Style = vbYesNo + vbCritical + vbDefaultButton2 ' Define buttons. Title = "MsgBox Demonstration" ' Define title. Help = "DEMO.HLP" ' Define Help file. Ctxt = 1000 ' Define topic ' context. ' Display message. Response = MsgBox(Msg, Style, Title, Help, Ctxt) If Response = vbYes Then ' User chose Yes. MyString = "Yes" ' Perform some action.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 214 of 1081

Else MyString = "No" End If

' User chose No. ' Perform some action.

Example (Microsoft Access) The following example uses the MsgBox function to create a formatted error message in Microsoft Access. Note the use of the at sign (@) to denote the different sections of the string.
Sub CustomMessage() Dim strMsg As String, strInput As String ' Initialize string. strMsg = "Number outside range.@You entered a number that is " _ & "less than 1 or greater than 10.@Press OK to enter " _ & "the number again." ' Prompt user for input. strInput = InputBox("Enter a number between 1 and 10.") ' Determine if user chose "Cancel". If strInput <> "" Then ' Test value of user input. Do While strInput < 0 Or strInput > 10 If MsgBox(strMsg, vbOKCancel, "Error!") = vbOK Then strInput = InputBox("Enter a number between 1 and 10.") Else Exit Sub End If Loop ' Display user's correct input. MsgBox "You entered the number " & strInput & "." Else Exit Sub End If End Sub

Name Statement
Description Renames a disk file, directory, or folder. Syntax Name oldpathname As newpathname The Name statement syntax has these parts: Part Description

oldpathname

Required. String expression that specifies the existing file name and location may include directory or folder, and drive.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 215 of 1081

newpathname

Required. String expression that specifies the new file name and location may include directory or folder, and drive. The file name specified by newpathname can't already exist.

Remarks Both newpathname and oldpathname must be on the same drive. If the path in newpathname exists and is different from the path in oldpathname, the Name statement moves the file to the new directory or folder and renames the file, if necessary. If newpathname and oldpathname have different paths and the same file name, Name moves the file to the new location and leaves the file name unchanged. Using Name, you can move a file from one directory or folder to another, but you can't move a directory or folder. Using Name on an open file produces an error. You must close an open file before renaming it. Name arguments cannot include multiple-character (*) and single-character (?) wildcards. See Also Kill statement. Example This example uses the Name statement to rename a file. For purposes of this example, assume that the directories or folders that are specified already exist.
Dim OldName, NewName OldName = "OLDFILE": NewName = "NEWFILE" Name OldName As NewName ' Define filenames. ' Rename file.

' In Microsoft Windows: OldName = "C:\MYDIR\OLDFILE": NewName = "C:\YOURDIR\NEWFILE" Name OldName As NewName ' Move and rename file. ' On the Macintosh: OldName = "HD:MY FOLDER:OLDFILE": NewName = "HD:YOUR FOLDER:NEWFILE" Name OldName As NewName ' Move and rename file.

Not Operator
Description Used to perform logical negation on an expression. Syntax result = Not expression The Not operator syntax has these parts:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 216 of 1081

Part

Description

result

Required; any numeric variable.

expression

Required; any expression.

Remarks The following table illustrates how result is determined: If expression is Then result is

True

False

False

True

Null

Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table: If bit in expression is Then bit in result is

See Also Operator precedence. Example This example uses the Not operator to perform logical negation on an expression.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 217 of 1081

Dim A, B, A = 10: B MyCheck = MyCheck = MyCheck = MyCheck =

C, D, MyCheck = 8: C = 6: D = Null Not(A > B) Not(B > A) Not(C > D) Not A

' Initialize variables. ' Returns False. ' Returns True. ' Returns Null. ' Returns -11 (bitwise comparison).

Now Function
Description Returns a Variant (Date) specifying the current date and time according your computer's system date and time. Syntax Now See Also Date function, Date statement, Day function, Hour function, Minute function, Month function, Second function, Time function, Time statement, Weekday function, Year function. Example This example uses the Now function to return the current system date and time.
Dim Today Today = Now ' Assign current system date and time.

Example (Microsoft Access) You can use the Now function in a calculated control to return the current system date and time. For example, you can create a text box and set its ControlSource property to the following expression.
=Now()

NPer Function
Description Returns a Double specifying the number of periods for an annuity based on periodic, fixed payments and a fixed interest rate. Syntax NPer(rate, pmt, pv[, fv[, type]])

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 218 of 1081

The NPer function has these named arguments: Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

pmt

Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.

(continued) pv Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

fv

Optional. Variant specifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). For all arguments, cash paid out (such as deposits to savings) is represented by negative

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 219 of 1081

numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the NPer function to return the number of periods during which payments must be made to pay off a loan whose value is contained in PVal. Also provided are the interest percentage rate per period (APR / 12), the payment (Payment), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
Dim FVal, PVal, APR, Payment, PayType, TotPmts Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. Payment = InputBox("How much do you want to pay each month?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType) If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1 MsgBox "It will take you " & TotPmts & " months to pay off your loan."

NPV Function
Description Returns a Double specifying the net present value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate. Syntax NPV(rate, values( )) The NPV function has these named arguments: Part Description

rate

Required. Double specifying discount rate over the length of the period, expressed as a decimal.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 220 of 1081

values ()

Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).

Remarks The net present value of an investment is the current value of a future series of payments and receipts. The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence. The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the array. The net present value calculation is based on future cash flows. If your first cash flow occurs at the beginning of the first period, the first value must be added to the value returned by NPV and must not be included in the cash flow values of values( ). The NPV function is similar to the PV function (present value) except that the PV function allows cash flows to begin either at the end or the beginning of a period. Unlike the variable NPV cash flow values, PV cash flows must be fixed throughout the investment. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, Pmt function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the NPV function to return the net present value for a series of cash flows contained in the array Values(). RetRate represents the fixed internal rate of return.
Dim Fmt, Guess, RetRate, NetPVal, Msg Static Values(5) As Double ' Set up array. Fmt = "###,##0.00" ' Define money format. Guess = .1 ' Guess starts at 10 percent. RetRate = .0625 ' Set fixed internal rate. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 NetPVal = NPV(RetRate, Values()) ' Calculate net present value. Msg = "The net present value of these cash flows is " Msg = Msg & Format(NetPVal, Fmt) & "." MsgBox Msg ' Display net present value.

Number Property
Applies To Err object.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 221 of 1081

Description Returns or sets a numeric value specifying an error. Number is the Err object's default property. Read/write. Remarks When returning a user-defined error from an object, set Err.Number by adding the number you selected as an error code to the vbObjectError constant. For example, you use the following code to return the number 1051 as an error code:
Err.Raise Number := vbObjectError + 1051, Source:= "SomeClass"

See Also Description property, Err object, HelpContext property, HelpContextID property ("Extensibility Object Model Language Reference"), HelpFile property, LastDLLError property, Source property. Example The first example illustrates a typical use of the Number property in an error-handling routine. The second example examines the Number property of the Err object to determine whether an error returned by an Automation object was defined by the object, or whether it was mapped to an error defined by Visual Basic. Note that the constant vbObjectError is a very large negative number that an object adds to its own error code to indicate that the error is defined by the server. Therefore, subtracting it from Err.Number strips it out of the result. If the error is objectdefined, the base number is left in MyError, which is displayed in a message box along with the original source of the error. If Err.Number represents a Visual Basic error, then the Visual Basic error number is displayed in the message box.
' Typical use of Number property. Sub test() On Error GoTo out Dim x, y x = 1 / y Exit Sub out: MsgBox Err.Number MsgBox Err.Description ' Check for division by zero error. If Err.Number = 11 Then y = y + 1 End If Resume End Sub ' Create division by zero error.

' Using Number property with an error from an ' Automation object. Dim MyError, Msg ' First, strip off the constant added by the object to indicate one ' of its own errors. MyError = Err.Number - vbObjectError ' If you subtract the vbObjectError constant, and the number is still ' in the range 0-65,535, it is an object-defined error code. If MyError > 0 And MyError < 65535 Then Msg = "The object you accessed assigned this number to the error: " _ & MyError & ". The originator of the error was: " _ & Err.Source & ". Press F1 to see originator's Help topic." ' Otherwise it is a Visual Basic error number. Else Msg = "This error (# " & Err.Number & ") is a Visual Basic error" & _ " number. Press Help button or F1 for the Visual Basic Help" _ & " topic for this error." End If

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 222 of 1081

MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext

Object Data Type


Description 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. 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. See Also Data type summary, Deftype statements, IsObject function, Variant data type.

Oct Function
Description Returns a Variant (String) representing the octal value of a number. Syntax Oct(number) The required number argument is any valid numeric expression or string expression. Remarks If number is not already a whole number, it is rounded to the nearest whole number before being evaluated. If number is Oct returns

Null

Null

Empty

Zero (0)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 223 of 1081

Any other number

Up to 11 octal characters

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8. See Also Hex function. Example This example uses the Oct function to return the octal value of a number.
Dim MyOct MyOct = Oct(4) MyOct = Oct(8) MyOct = Oct(459) ' Returns 4. ' Returns 10. ' Returns 713.

On Error Statement
Description Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine. Syntax On Error GoTo line On Error Resume Next On Error GoTo 0 The On Error statement syntax can have any of the following forms: Statement Description

On Error GoTo line

Enables the error-handling routine that starts at line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 224 of 1081

On Error Resume Next

Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred where execution continues. Use this form rather than On Error GoTo when accessing objects.

On Error GoTo 0

Disables any enabled error handler in the current procedure.

Remarks If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops. An "enabled" error handler is one that is turned on by an On Error statement; an "active" error handler is an enabled handler that is in the process of handling an error. If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error. Control returns to the calling procedure. If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If no inactive, enabled error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement. Note An error-handling routine is not a Sub procedure or Function procedure. It is a section of code marked by a line label or line number. Error-handling routines rely on the value in the Number property of the Err object to determine the cause of the error. The error-handling routine should test or save relevant property values in the Err object before any other error can occur or before a procedure that might cause an error is called. The property values in the Err object reflect only the most recent error. The error message associated with Err.Number is contained in Err.Description. On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the errorhandling routine where the error would occur, rather than transferring control to another location within the procedure. An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine. Note The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 225 of 1081

object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source). On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited. To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement immediately before the error-handling routine, as in the following fragment:
Sub InitializeMatrix(Var1, Var2, Var3, Var4) On Error GoTo ErrorHandler . . . Exit Sub ErrorHandler: . . . Resume Next End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the procedure flow. Error-handling code can be placed anywhere in a procedure. Untrapped errors in objects are returned to the controlling application when the object is running as an executable file. Within the development environment, untrapped errors are only returned to the controlling application if the proper options are set. See your host application's documentation for a description of which options should be set during debugging, how to set them, and whether the host can create classes. If you create an object that accesses other objects, you should try to handle errors passed back from them unhandled. If you cannot handle such errors, map the error code in Err.Number to one of your own errors, and then pass them back to the caller of your object. You should specify your error by adding your error code to the vbObjectError constant. For example, if your error code is 1052, assign it as follows:
Err.Number = vbObjectError + 1052

Note System errors during calls to dynamic-link libraries (DLL) do not raise exceptions and cannot be trapped with Visual Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property. See Also End statement, Err object, Exit statement, LastDLLError property, Resume statement. Example This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 226 of 1081

Sub OnErrorStatementDemo() On Error GoTo ErrorHandler Open "TESTFILE" For Output As #1 Kill "TESTFILE"

' Enable error-handling routine. ' Open file for output. ' Attempt to delete open ' file. On Error Goto 0 ' Turn off error trapping. On Error Resume Next ' Defer error trapping. ObjectRef = GetObject("MyWord.Basic") ' Try to start nonexistent ' object, then test for 'Check for likely Automation errors. If Err.Number = 440 Or Err.Number = 432 Then ' Tell user what happened. Then clear the Err object. Msg = "There was an error attempting to open the Automation object!" MsgBox Msg, , "Deferred Error Test" Err.Clear ' Clear Err object fields End If Exit Sub ' Exit to avoid handler. ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 55 ' "File already open" error. Close #1 ' Close open file. Case Else ' Handle other situations here... End Select Resume ' Resume execution at same line ' that caused the error. End Sub

On...GoSub, On...GoTo Statements


Description Branch to one of several specified lines, depending on the value of an expression. Syntax On expression GoSub destinationlist On expression GoTo destinationlist The On...GoSub and On...GoTo statement syntax has these parts: Part Description

expression

Required. Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.

destinationlist

Required. List of line numbers or line labels separated by commas.

Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 227 of 1081

The value of expression determines which line is branched to in destinationlist. If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs: If expression is Then

Equal to 0

Control drops to the statement following On...GoSub or On...GoTo.

Greater than number of items in list

Control drops to the statement following On...GoSub or On...GoTo.

Negative

An error occurs.

Greater than 255

An error occurs.

You can mix line numbers and line labels in the same list. You can use as many line labels and line numbers as you like with On...GoSub and On...GoTo. However, if you use more labels or numbers than fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line. Tip Select Case provides a more structured and flexible way to perform multiple branching.

See Also GoSub...Return statement, GoTo statement, Select Case statement. Example This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels, respectively.
Sub OnGosubGotoDemo() Dim Number, MyString Number = 2 ' Branch to Sub2. On Number GoSub Sub1, Sub2

' Initialize variable.

' Execution resumes here after ' On...GoSub. On Number GoTo Line1, Line2 ' Branch to Line2. ' Execution does not resume here after On...GoTo. Exit Sub Sub1: MyString = "In Sub1" : Return Sub2: MyString = "In Sub2" : Return Line1: MyString = "In Line1" Line2: MyString = "In Line2"

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 228 of 1081

End Sub

Open Statement
Description Enables input/output (I/O) to a file. Syntax Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength] The Open statement syntax has these parts: Part Description

pathname

Required. String expression that specifies a file name may include directory or folder, and drive.

mode

Required. Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.

access

Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.

lock

Optional. Keyword specifying the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.

filenumber

Required. A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.

reclength

Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 229 of 1081

Remarks You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer. If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes. If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs. The Len clause is ignored if mode is Binary. Important In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number. See Also Close statement, FreeFile function. Example This example illustrates various uses of the Open statement to enable input and output to a file. The following code opens the file TESTFILE in sequential-input mode.
Open "TESTFILE" For Input As #1 ' Close before reopening in another mode. Close #1

This example opens the file in Binary mode for writing operations only.
Open "TESTFILE" For Binary Access Write As #1 ' Close before reopening in another mode. Close #1

The following example opens the file in Random mode. The file contains records of the userdefined type Record.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

Dim MyRecord As Record ' Declare variable. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Close before reopening in another mode. Close #1

This code example opens the file for sequential output; any process can read or write to file.
Open "TESTFILE" For Output Shared As #1 ' Close before reopening in another mode. Close #1

This code example opens the file in Binary mode for reading; other processes can't read file.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 230 of 1081

Open "TESTFILE" For Binary Access Read Lock Read As #1

Operator Precedence
Description When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-toright order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence: Arithmetic Comparison Logical

Exponentiation (^)

Equality (=)

Not

Negation ()

Inequality (<>)

And

Multiplication and division (*, /)

Less than (<)

Or

Integer division (\)

Greater than (>)

Xor

Modulus arithmetic (Mod)

Less than or equal to (<=)

Eqv

Addition and subtraction (+, )

Greater than or equal to (>=)

Imp

String concatenation (&)

Like Is

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. When addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 231 of 1081

The string concatenation operator (&) is not an arithmetic operator, but in precedence, it does follow all arithmetic operators and precede all comparison operators. The Like operator is equal in precedence to all comparison operators, but is actually a patternmatching operator. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object. See Also Is operator, Like operator.

Option Base Statement


Description Used at module level to declare the default lower bound for array subscripts. Syntax Option Base {0 | 1} Remarks Because the default base is 0, the Option Base statement is never required. If used, the statement must appear in a module before any procedures. Option Base can appear only once in a module and must precede array declarations that include dimensions. Note The To clause in the Dim, Private, Public, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts. However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1. The base of an array created with the Array function or the ParamArray keyword is zero; Option Base does not affect Array or ParamArray. The Option Base statement only affects the lower bound of arrays in the module where the statement is located. See Also Dim statement, LBound function, Option Compare statement, Option Explicit statement, Option Private statement, Private statement, Public statement, ReDim statement, Static statement. Example This example uses the Option Base statement to override the default base array subscript value of 0. The LBound function returns the smallest available subscript for the indicated dimension of an array. The Option Base statement is used at the module level only.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 232 of 1081

Option base 1

' Set default array subscripts to 1.

Dim Lower Dim MyArray(20), TwoDArray(3, 4) ' Declare array variables. Dim ZeroArray(0 To 5) ' Override default base subscript. ' Use LBound function to test lower bounds of arrays. Lower = LBound(MyArray) ' Returns 1. Lower = LBound(TwoDArray, 2) ' Returns 1. Lower = LBound(ZeroArray) ' Returns 0.

Option Compare Statement


Description Used at module level to declare the default comparison method to use when string data is compared. Syntax Option Compare {Binary | Text | Database} Remarks If used, the Option Compare statement must appear in a module before any procedures. The Option Compare statement specifies the string comparison method (Binary, Text, or Database) for a module. If a module doesn't include an Option Compare statement, the default text comparison method is Binary. Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. A typical binary sort order is shown in the following example:
A < B < E < Z < a < b < e < z < < < < < <

Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system's locale. When the same characters are sorted using Option Compare Text, the following text sort order is produced:
(A=a) < ( =) < (B=b) < (E=e) < (=) < (Z=z) < (=)

Option Compare Database can only be used within Microsoft Access. This results in string comparisons based on the sort order determined by the locale ID of the database where the string comparisons occur. See Also Comparison operators, InStr function, Option Base statement, Option Explicit statement, Option Private statement, StrComp function. Specifics (Macintosh) On the Macintosh, sort order is determined by the character set.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 233 of 1081

Specifics (Microsoft Access) In Microsoft Access, all modules by default contain the Option Compare Database statement in the Declarations section. This statement sets the string comparison method for the module to the one specified for the entire database. You can change the string comparison method for all new databases by clicking Options on the Tools menu and changing the value in the New Database Sort Order box on the General tab of the Options dialog box. By default this value is set to General, which specifies a case-insensitive sort order based on the English alphabet. Changing the New Database Sort Order option doesn't affect the string comparison method for the current database. It only affects databases that are created after the option has been set. To specify a string comparison method for an individual module that is different from the one specified for the database, change Option Compare Database to Option Compare Binary or Option Compare Text. The Option Compare Binary statement compares strings by evaluating the ASCII values corresponding to the characters they contain, so the statement is case-sensitive. Option Compare Text is case-insensitive. Note If you are using the Bookmark property of a Recordset object, you must include an Option Compare Binary statement in the Declarations section of the module. The setting and return value for the Bookmark property is a Variant array of Byte data. If you use a case-insensitive string comparison method, the Bookmark property may point you to the wrong record. Example This example uses the Option Compare statement to set the default string comparison method. The Option Compare statement is used at the module level only.
' Set the string comparison method to Binary. Option compare Binary ' That is, "AAA" is less than "aaa" ' Set the string comparison method to Text. Option compare Text ' That is, "AAA" is equal to "aaa".

Option Explicit Statement


Description Used at module level to force explicit declaration of all variables in that module. Syntax Option Explicit Remarks If used, the Option Explicit statement must appear in a module before any procedures. When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 234 of 1081

name, an error occurs at compile time. If you don't use the Option Explicit statement, all undeclared variables are of Variant type unless the default type is otherwise specified with a Deftype statement. Note Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear. See Also Const statement, Deftype statements, Dim statement, Function statement, Option Base statement, Option Compare statement, Option Private statement, Private statement, Public statement, ReDim statement, Static statement, Sub statement. Specifics (Microsoft Access) In Microsoft Access, you can ensure that all new modules will automatically include the Option Explicit statement. Click Options on the Tool menu, click the Module tab, and select the Require Variable Declaration option. Once you select this option, it will automatically be set for all other databases which you create or open with Microsoft Access. Note When you select this option, only new modules will have the Option Explicit setting. You must enter the Option Explicit statement into the Declarations section of any existing modules. Or, when the module is open, click Options on the Tools menu, click the Module tab, and select the Require Variable Declaration option. Example This example uses the Option Explicit statement to force you to explicitly declare all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.
Option explicit Dim MyVar MyInt = 10 MyVar = 10 ' Force explicit variable declaration. ' Declare variable. ' Undeclared variable generates error. ' Declared variable does not generate error.

Option Private Statement


Description When used in host applications that allow references across multiple projects, Option Private Module prevents a module's contents from being referenced outside its project. In host applications that don't permit such references, for example, standalone versions of Visual Basic, Option Private has no effect. Syntax Option Private Module

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 235 of 1081

Remarks If used, the Option Private statement must appear at module level, before any procedures. When a module contains Option Private Module, the public parts, for example, variables, objects, and user-defined types declared at module level, are still available within the project containing the module, but they are not available to other applications or projects. Note Option Private is only useful for host applications that support simultaneous loading of multiple projects and permit references between the loaded projects. For example, Microsoft Excel permits loading of multiple projects and Option Private Module can be used to restrict cross-project visibility. Although Visual Basic permits loading of multiple projects, references between projects are never permitted in Visual Basic. See Also Option Base statement, Option Compare statement, Option Explicit statement, Private statement, Public statement. Specifics (Microsoft Access) When you include the Option Private statement in a standard module in Microsoft Access, any public variables or procedures in the module are still available to all other procedures in the current database. However, they are not available to procedures in other databases. Since class modules are private by default, including the Option Private statement in a class module generates an error. Example This example demonstrates the Option Private statement, which is used at the module level to indicate that the entire module is private. With Option Private Module, module-level symbols not declared Private are still available to other modules in the project, but not to other projects or applications.
Option private Module ' Indicate that module is private.

Or Operator
Description Used to perform a logical disjunction on two expressions. Syntax result = expression1 Or expression2 The Or operator syntax has these parts:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 236 of 1081

Part

Description

result

Required; any numeric variable.

expression1

Required; any expression.

expression2

Required; any expression.

Remarks If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined: If expression1 is And expression2 is Then result is

True

True

True

True

False

True

True

Null

True

False

True

True

False

False

False

(continued) False Null Null

Null

True

True

Null

False

Null

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 237 of 1081

Null

Null

Null

The Or operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table: If bit in expression1 is And bit in expression2 is Then result is

See Also Operator precedence. Example This example uses the Or operator to perform logical disjunction on two expressions.
Dim A, B, A = 10: B MyCheck = MyCheck = MyCheck = MyCheck = MyCheck = C, D, MyCheck = 8: C = 6: D = Null A > B Or B > C B > A Or B > C A > B Or B > D B > D Or B > A A Or B ' Initialize variables. ' Returns True. ' Returns True. ' Returns True. ' Returns Null. ' Returns 10 (bitwise comparison).

Partition Function
Description Returns a Variant (String) indicating where a number occurs within a calculated series of ranges. Syntax Partition(number, start, stop, interval) The Partition function syntax has these named arguments.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 238 of 1081

Part

Description

number

Required. Whole number that you want to evaluate against the ranges.

start

Required. Whole number that is the start of the overall range of numbers. The number can't be less than 0.

stop

Required. Whole number that is the end of the overall range of numbers. The number can't be equal to or less than start.

interval

Required. Whole number that is the interval spanned by each range in the series from start to stop. The number can't be less than 1.

Remarks The Partition function identifies the particular range in which number falls and returns a Variant (String) describing that range. The Partition function is most useful in queries. You can create a select query that shows how many orders fall within various ranges, for example, order values from 1 to 1000, 1001 to 2000, and so on. The following table shows how the ranges are determined using three sets of start, stop, and interval parts. The First Range and Last Range columns show what Partition returns. The ranges are represented by lowervalue:uppervalue, where the low end (lowervalue) of the range is separated from the high end (uppervalue) of the range with a colon (:). start stop interval Before First First Range Last Range After Last

99

" :1"

" 0: 4"

" 95: 99"

" 100: "

20

199

10

" : 19"

" 20: 29"

" 190: 199"

" 200: "

100

1010

20

" : 99"

" 100: 119"

" 1000: 1010"

" 1011: "

In the table shown above, the third line shows the result when start and stop define a set of numbers that can't be evenly divided by interval. The last range extends to stop (11 numbers) even though interval is 20. If necessary, Partition returns a range with enough leading spaces so that there are the same

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 239 of 1081

number of characters to the left and right of the colon as there are characters in stop, plus one. This ensures that if you use Partition with other numbers, the resulting text will be handled properly during any subsequent sort operation. If interval is 1, the range is number:number, regardless of the start and stop arguments. For example, if interval is 1, number is 100 and stop is 1000, Partition returns " 100: 100". If any of the parts is Null, Partition returns a Null. Example This example assumes you have an Orders table that contains a Freight field. It creates a select procedure that counts the number of orders for which freight cost falls into each of several ranges. The Partition function is used first to establish these ranges, then the SQL Count function counts the number of orders in each range. In this example, the arguments to the Partition function are start = 0, stop = 500, interval = 50. The first range would therefore be 0:49, and so on up to 500.
SELECT DISTINCTROW Partition([freight],0, 500, 50) AS Range, Count(Orders.Freight) AS Count FROM Orders GROUP BY Partition([freight],0,500,50);

Example (Microsoft Access) You can use the Partition function in the query design grid as well as in the SQL view of the Query window. In the query design grid, you can use the Partition function in a calculated field or to specify criteria for a select query. The following example shows how you can use the Partition function to create a calculated field that lists how many records fall into each specified range. Suppose you have an Orders table that contains a Freight field. In the Query window, create a new Totals query by adding the Orders table and clicking on the Totals button in the Query command bar. Drag the Freight field to the first Field cell on the query design grid, and set the value of the Total cell to Count. In another field cell, enter the following expression.
Range: Partition([Freight], 0, 1000, 50) <BREAK>

Set the Total cell below this field to Group By, and run the query. The Partition function returns eleven ranges (0:99, 100:199, 200:299, and so on). The query shows the number of orders with freight charges falling into each range. The next example shows how you can use the Partition function in the SQL view of the Query window. It creates a crosstab query that evaluates a Freight field in an Orders table. It calculates the number of orders for each customer for which freight cost falls within one of several ranges. The ranges are defined by the arguments to the Partition function: start = 0, stop = 1000, interval = 50. Enter the following expression in SQL view. When you run this query, each range will appear as a column heading.
TRANSFORM Count(Orders.[OrderID]) AS [CountOfOrderID] SELECT Orders.[CustomerID] FROM Orders GROUP BY Orders.[CustomerID] PIVOT Partition(Int([Freight]), 0, 1000, 50);

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 240 of 1081

Pmt Function
Description Returns a Double specifying the payment for an annuity based on periodic, fixed payments and a fixed interest rate. Syntax Pmt(rate, nper, pv[, fv[, type]]) The Pmt function has these named arguments. Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

nper

Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pv

Required. Double specifying present value (or lump sum) that a series of payments to be paid in the future is worth now. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

fv

Optional. Variant specifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 241 of 1081

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, PPmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the Pmt function to return the monthly payment for a loan over a fixed period. Given are the interest percentage rate per period (APR / 12), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
Dim Fmt, FVal, PVal, APR, TotPmts, PayType, Payment Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "###,###,##0.00" ' Define money format. FVal = 0 ' Usually 0 for a loan. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("How many monthly payments will you make?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD Payment = Pmt(APR / 12, TotPmts, -PVal, FVal, PayType) MsgBox "Your payment will be " & Format(Payment, Fmt) & " per month."

PPmt Function
Description Returns a Double specifying the principal payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate. Syntax

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 242 of 1081

PPmt(rate, per, nper, pv[, fv[, type]]) The PPmt function has these named arguments. Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

per

Required. Integer specifying payment period in the range 1 through nper.

nper

Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pv

Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

(continued) Part Description

fv

Optional. Variant specifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 243 of 1081

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PV function, Rate function, SLN function, SYD function. Example This example uses the PPmt function to calculate how much of a payment for a specific period is principal when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the principal portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
Dim NL, TB, Fmt, FVal, PVal, APR, TotPmts, PayType, Payment, Msg, _ MakeChart, Period, P, I Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. NL = Chr(13) & Chr(10) ' Define newline. TB = Chr(9) ' Define tab. Fmt = "###,###,##0.00" ' Define money format. FVal = 0 ' Usually 0 for a loan. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("How many monthly payments do you have to make?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD Payment = Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType)) Msg = "Your monthly payment is " & Format(Payment, Fmt) & ". " Msg = Msg & "Would you like a breakdown of your principal and " Msg = Msg & "interest per period?" MakeChart = MsgBox(Msg, vbYesNo) ' See if chart is desired. If MakeChart <> vbNo Then If TotPmts > 12 Then MsgBox "Only first year will be shown." Msg = "Month Payment Principal Interest" & NL For Period = 1 To TotPmts If Period > 12 Then Exit For ' Show only first 12. P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType) P = (Int((P + .005) * 100) / 100) ' Round principal. I = Payment - P I = (Int((I + .005) * 100) / 100) ' Round interest. Msg = Msg & Period & TB & Format(Payment, Fmt) Msg = Msg & TB & Format(P, Fmt) & TB & Format(I, Fmt) & NL Next Period MsgBox Msg ' Display amortization table.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 244 of 1081

End If

Print # Statement
Description Writes display-formatted data to a sequential file. Syntax Print #filenumber , [outputlist] The Print # statement syntax has these parts. Part Description

filenumber

Required. Any valid file number.

outputlist

Optional. Expression or list of expressions to print.

Settings The outputlist argument settings are [{Spc(n) | Tab[(n)]}] [expression] [charpos] Setting Description

Spc(n)

Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)

Used to position the insertion point to an absolute column number, where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 245 of 1081

Setting

Description

expression

Numeric expressions or string expressions to print.

charpos

Specifies the insertion point for the next character. Use a semicolon to position the insertion point immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks Data written with Print # is usually read from a file with Line Input # or Input. If you omit outputlist and include only a list separator after filenumber, a blank line is printed to the file. Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon. For Boolean data, either True or False is printed. The True and False keywords are not translated, regardless of the locale. Date data is written to the file using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the part provided gets written to the file. Nothing is written to the file if outputlist data is Empty. However, if outputlist data is Null, Null is written to the file. For Error data, the output appears as Error errorcode. The Error keyword is not translated regardless of the locale. All data written to the file using Print # is internationally aware; that is, the data is properly formatted using the appropriate decimal separator. Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly. If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file. Note If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file. Using Write # ensures the integrity of each separate data field by properly delimiting it, so it can be read back in using Input #. Using Write # also ensures it can be correctly read in any locale.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 246 of 1081

See Also Open statement, Print method, Spc function, Tab function, Write # statement. Example This example uses the Print # statement to write data to a file.
Open "TESTFILE" For Output As #1 Print #1, "This is a test" Print #1, Print #1, "Zone 1"; Tab ; "Zone 2" Print #1, "Hello" ; " " ; "World" Print #1, Spc(5) ; "5 leading spaces " Print #1, Tab(10) ; "Hello" ' Open file for output. ' Print text to file. ' Print blank line to file. ' Print in two print zones. ' Separate strings with space. ' Print five leading spaces. ' Print word at column 10.

' Assign Boolean, Date, Null and Error values. Dim MyBool, MyDate, MyNull, MyError MyBool = False : MyDate = #February 12, 1969# : MyNull = Null MyError = CVErr(32767) ' True, False, Null, and Error are translated using locale settings of ' your system. Date literals are written using standard short date ' format. Print #1, MyBool ; " is a Boolean value" Print #1, MyDate ; " is a date" Print #1, MyNull ; " is a null value" Print #1, MyError ; " is an error value" Close #1 ' Close file.

Print Method
Applies To Debug object. Description Prints text in the Immediate pane of the Debug window. Syntax object.Print [outputlist] The Print method syntax has the following object qualifier and part. Part Description

object

Optional. An object expression that evaluates to an object in the Applies To list.

outputlist

Optional. Expression or list of expressions to print. If omitted, a blank line is printed.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 247 of 1081

The outputlist argument has the following syntax and parts. {Spc(n) | Tab(n)} expression charpos Part Description

Spc(n)

Optional. Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)

Optional. Used to position the insertion point at an absolute column number where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.

expression

Optional. Numeric expression or string expression to print.

charpos

Optional. Specifies the insertion point for the next character. Use a semicolon (;) to position the insertion point immediately following the last character displayed. Use Tab(n) to position the insertion point at an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks Multiple expressions can be separated with either a space or a semicolon. All data printed to the Immediate window is properly formatted using the decimal separator for the locale settings specified for your system. The keywords are output in the appropriate language for the host application. For Boolean data, either True or False is printed. The True and False keywords are translated according to the locale setting for the host application. Date data is written using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the data provided is written. Nothing is written if outputlist data is Empty. However, if outputlist data is Null, Null is output. The Null keyword is appropriately translated when it is output.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 248 of 1081

For error data, the output is written as Error errorcode. The Error keyword is appropriately translated when it is output. The object is required if the method is used outside a module having a default display space. For example an error occurs if the method is called in a standard module without specifying an object, but if called in a form module, outputlist is displayed on the form. Note Because the Print method typically prints with proportionally-spaced characters, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter, such as a "W", occupies more than one fixed-width column, and a narrow letter, such as an "i", occupies less. To allow for cases where wider than average characters are used, your tabular columns must be positioned far enough apart. Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column. See Also Print # statement, Spc function, Tab function. Specifics (Microsoft Access) The Visual Basic Print method applies only to the Debug object in Microsoft Access, never to a Form object. The Debug object is required when you use the Print method in Microsoft Access. Don't confuse the Visual Basic Print method with the Microsoft Access Print method, which applies only to a Report object. Example Using the Print method, this example displays the value of the variable MyVar in the Immediate pane of the Debug window. Note that the Print method only applies to objects that can display text.
Dim MyVar MyVar = "Come see me in the Immediate pane." Debug.Print MyVar

PrintForm Method
Applies To UserForm object. Description Sends a bit-by-bit image of a UserForm object to the printer. Syntax object.PrintForm

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 249 of 1081

The object placeholder represents an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm with the focus is assumed to be object. Remarks PrintForm prints all visible objects and bitmaps of the UserForm object. PrintForm also prints graphics added to a UserForm object. The printer used by PrintForm is determined by the operating system's Control Panel settings. Example In the following example, the client area of the form is printed when the user clicks the form.
' This is the click event for UserForm1 Private Sub UserForm_Click() UserForm1.PrintForm End Sub

Private Statement
Description Used at module level to declare private variables and allocate storage space. Syntax Private [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . . The Private statement syntax has these parts. Part Description

WithEvents

Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. Valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.

varname

Required. Name of the variable; follows standard variable naming conventions.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 250 of 1081

subscripts

Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

New

Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.

type

Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variablelength strings), String * length (for fixedlength strings), Object, Variant, a userdefined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks Private variables are available only to the module in which they are declared. Use the Private statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:
Private NumberOfEmployees As Integer

You can also use a Private statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.
Private X As New Worksheet

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 251 of 1081

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. If you don't specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default. You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. Note When you use the Private statement in a procedure, you generally put the Private statement at the beginning of the procedure. See Also Array function, Const statement, Dim statement, Function statement, Option Base statement, Option Private statement, Property Get statement, Property Let statement, Property Set statement, Public statement, ReDim statement, Set statement, Static statement, Sub statement, Type statement. Example This example shows the Private statement being used at the module level to declare variables as private; that is, they are available only to the module in which they are declared.
Private Number As Integer ' Private Integer variable. Private NameArray(1 To 5) As String ' Private array variable. ' Multiple declarations, two Variants and one Integer, all Private. Private MyVar, YourVar, ThisVar As Integer

Property Get Statement


Description Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property. Syntax [Public | Private] [Static] Property Get name [(arglist)] [As type][statements][name = expression][Exit Property] [statements][name = expression]

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 252 of 1081

End Property The Property Get statement syntax has these parts. Part Description

Public

Optional. Indicates that the Property Get procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.

Private

Optional. Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.

Static

Optional. Indicates that the Property Get procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Get procedure, even if they are used in the procedure.

name

Required. Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.

arglist

Optional. List of variables representing arguments that are passed to the Property Get procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Get procedure must be the same as the corresponding argument in a Property Let procedure (if one exists).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 253 of 1081

type

Optional. Data type of the value returned by the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (except fixed length), Object, Variant, or user-defined type. Arrays of any type can't be returned, but a Variant containing an array can. The return type of a Property Get procedure must be the same data type as the last (or sometimes the only) argument in a corresponding Property Let procedure (if one exists) that defines the value assigned to the property on the right side of an expression.

(continued) statements Optional. Any group of statements to be executed within the body of the Property Get procedure.

expression

Optional. Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts. [Optional] [ByVal | ByRef] varname[( )] [As type] [= defaultvalue] Part Description

Optional

Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 254 of 1081

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.

varname

Required. Name of the variable representing the argument; follows standard variable naming conventions.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant. If the parameter is not Optional, a user-defined type or an object type may also be specified.

defaultvalue

Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. All executable code must be in procedures. You can't define a Property Get procedure inside another Property, Sub, or Function procedure. The Exit Property statement causes an immediate exit from a Property Get procedure. Program execution continues with the statement following the statement that called the Property Get procedure. Any number of Exit Property statements can appear anywhere in a Property Get procedure. Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub or Property Let procedure, you can use a Property Get procedure on the right side of an expression in the same way you use a Function or a property name when you want to return the value of a property. See Also Function statement, Property Let statement, Property Set statement, Sub statement.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 255 of 1081

Specifics (Microsoft Access) You can use the Property Get statement to define a property procedure that returns the value of a property. You will probably want to use the Property Get and Property Let statements together to create a property in a class module. For example, you could define a Property Let procedure in a class module to set a new property, and a Property Get procedure to return the value of that setting. When you create a new instance of this class, the property procedures behave like custom properties for the new object. Property procedures in a class module are public by default, and will be available to procedures in other modules in the current database, unless you preface them with the Private keyword. Example This example uses the Property Get statement to define a property procedure that gets the value of a property. The property identifies the current color of a pen in a drawing package as a string.
Dim CurrentColor As Integer Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3 ' Returns the current color of the pen as a string. Property Get PenColor() As String Select Case CurrentColor Case RED PenColor = "Red" Case GREEN PenColor = "Green" Case BLUE PenColor = "Blue" End Select End Property ' The following code gets the color of the pen ' calling the Property get procedure. ColorName = PenColor

Property Let Statement


Description Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property. Syntax [Public | Private] [Static] Property Let name ([arglist,] value)[statements][Exit Property] [statements] End Property The Property Let statement syntax has these parts.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 256 of 1081

Part

Description

Public

Optional. Indicates that the Property Let procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.

Private

Optional. Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.

Static

Optional. Indicates that the Property Let procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Let procedure, even if they are used in the procedure.

name

Required. Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.

arglist

Required. List of variables representing arguments that are passed to the Property Let procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Let procedure must be the same as the corresponding argument in a Property Get procedure.

value

Required. Variable to contain the value to be assigned to the property. When the procedure is called, this argument appears on the right side of the calling expression. The data type of value must be the same as the return type of the corresponding Property Get procedure.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 257 of 1081

statements

Optional. Any group of statements to be executed within the Property Let procedure.

The arglist argument has the following syntax and parts. [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Part Description

Optional

Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Note that it is not possible for the right side of a Property Let expression to be Optional.

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.

varname

Required. Name of the variable representing the argument; follows standard variable naming conventions.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant. If the parameter is not Optional, a user-defined type, or an object type may also be specified.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 258 of 1081

defaultvalue

Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Note Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked. That argument is referred to as value in the preceding syntax. Remarks If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. All executable code must be in procedures. You can't define a Property Let procedure inside another Property, Sub, or Function procedure. The Exit Property statement causes an immediate exit from a Property Let procedure. Program execution continues with the statement following the statement that called the Property Let procedure. Any number of Exit Property statements can appear anywhere in a Property Let procedure. Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left side of a property assignment expression or Let statement. See Also Function statement, Let statement, Property Get statement, Property Set statement, Sub statement. Specifics (Microsoft Access) You can use the Property Let statement to define a property procedure that assigns the value of a property. You will probably want to use the Property Let and Property Get statements together to create a property in a class module. For example, you could define a Property Let procedure in a class module to set a new property, and a Property Get procedure to return the value of that setting. When you create a new instance of this class, the property procedures behave like custom properties for the new object. Property procedures in a class module are public by default, and will be available to procedures in other modules in the current database, unless you preface them with the Private keyword. Example This example uses the Property Let statement to define a procedure that assigns a value to a property. The property identifies the pen color for a drawing package.
Dim CurrentColor As Integer

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 259 of 1081

Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3 ' Set the pen color property for a Drawing package. ' The module-level variable CurrentColor is set to ' a numeric value that identifies the color used for drawing. Property Let PenColor(ColorName As String) Select Case ColorName ' Check color name string. Case "Red" CurrentColor = RED ' Assign value for Red. Case "Green" CurrentColor = GREEN ' Assign value for Green. Case "Blue" CurrentColor = BLUE ' Assign value for Blue. Case Else CurrentColor = BLACK ' Assign default value. End Select End Property ' The following code sets the PenColor property for a drawing package ' by calling the Property let procedure. PenColor = "Red"

Property Set Statement


Description Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object. Syntax [Public | Private] [Static] Property Set name ([arglist,] reference)[statements][Exit Property] [statements] End Property The Property Set statement syntax has these parts. Part Description

Optional

Optional. Indicates that the argument may or may not be supplied by the caller.

Public

Optional. Indicates that the Property Set procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 260 of 1081

Private

Optional. Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.

Static

Optional. Indicates that the Property Set procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Set procedure, even if they are used in the procedure.

name

Required. Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.

arglist

Required. List of variables representing arguments that are passed to the Property Set procedure when it is called. Multiple arguments are separated by commas.

reference

Required. Variable containing the object reference used on the right side of the object reference assignment.

statements

Optional. Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts. [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Part Description

Optional

Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Note that it is not possible for the right side of a Property Set expression to be Optional.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 261 of 1081

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.

varname

Required. Name of the variable representing the argument; follows standard variable naming conventions.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable length only), Object, Variant. If the parameter is not Optional, a user-defined type, or an object type may also be specified.

defaultvalue

Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Note Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual object reference for the property when the procedure defined by the Property Set statement is invoked. It is referred to as reference in the preceding syntax. It can't be Optional. Remarks If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. All executable code must be in procedures. You can't define a Property Set procedure inside another Property, Sub, or Function procedure. The Exit Property statement causes an immediate exit from a Property Set procedure. Program

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 262 of 1081

execution continues with the statement following the statement that called the Property Set procedure. Any number of Exit Property statements can appear anywhere in a Property Set procedure. Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left side of an object reference assignment (Set statement). See Also Function statement, Property Get statement, Property Let statement, Set statement, Sub statement. Example This example uses the Property Set statement to define a property procedure that sets a reference to an object.
' The Pen property may be set to different Pen implementations. Property Set Pen(P As Object) Set CurrentPen = P ' Assign Pen to object. End Property

Public Statement
Description Used at module level to declare public variables and allocate storage space. Syntax Public [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . . The Public statement syntax has these parts Part Description

WithEvents

Optional. Keyword specifying that varname is an object variable used to respond to events triggered by an ActiveX object. Valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 263 of 1081

varname

Required. Name of the variable; follows standard variable naming conventions.

subscripts

Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

(continued) New Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.

type

Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, (for variablelength strings), String * length (for fixedlength strings), Object, Variant, a userdefined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are public only within the project in which they reside.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 264 of 1081

Caution The Public statement can't be used in a class module to declare a fixed-length string variable. Use the Public statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:
Public NumberOfEmployees As Integer

Also use a Public statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.
Public X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs. If you don't specify a data type or object type and there is no Deftype statement in the module, the variable is Variant by default. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. See Also Array function, Const statement, Dim statement, Option Base statement, Option Private statement, Private statement, Property Get statement, Property Let statement, Property Set statement, ReDim statement, Set statement, Static statement, Type statement. Specifics (Microsoft Access) By default, module-level variables are private to that module. You must explicitly declare a public variable with the Public statement. Module-level variables declared in standard modules with the Public statement are available to all other procedures in all modules in the current database and in referencing Microsoft Access databases. However, they are not available to any applications other than Microsoft Access. If a public variable is declared in a module that contains the Option Private statement or in a class module, the variable is available to all procedures in the current database, but not to procedures in other databases. Note The Public statement can't be used in a class module to declare a constant, a fixed-length string, or an array. In addition, if you include a Declare statement in a class module, you must precede it with the Private keyword. For more information about the Declare statement, see Declare Statement.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 265 of 1081

Example This example uses the Public statement at the module level (General section) of a standard module to explicitly declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.
Public Number As Integer ' Public Integer variable. Public NameArray(1 To 5) As String ' Public array variable. ' Multiple declarations, two Variants and one Integer, all Public. Public MyVar, YourVar, ThisVar As Integer

Put Statement
Description Writes data from a variable to a disk file. Syntax Put [#]filenumber, [recnumber], varname The Put statement syntax has these parts Part Description

filenumber

Required. Any valid file number.

recnumber

Optional. Variant (Long). Record number (Random mode files) or byte number (Binary mode files) at which writing begins.

varname

Required. Name of variable containing data to be written to disk.

Remarks Data written with Put is usually read from a file with Get. The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte after the last Get or Put statement or pointed to by the last Seek function is written. You must include delimiting commas, for example:
Put #4,,FileBuffer

For files opened in Random mode, the following rules apply:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 266 of 1081

If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written. If the length of the data being written is greater than the length specified in the Len clause of the Open statement, an error occurs. If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string. If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then writes the variable. For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable. Note You can use the Put statement to write a Variant array to disk, but you can't use Put to write a scalar Variant containing an array to disk. You also can't use Put to write objects to disk. If the variable being written is a Variant of VarType 8 (String), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then writes the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string. If the variable being written is a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.
Dim MyArray(1 To 5,1 To 10) As Integer

The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2). If the variable being written is a fixed-size array, Put writes only the data. No descriptor is written to disk. If the variable being written is any other type of variable (not a variable-length string or a Variant), Put writes only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written. Put writes elements of user-defined types as if each were written individually, except there is no padding between elements. On disk, a dynamic array in a user-defined type written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements, including any arrays and their descriptors. For files opened in Binary mode, all of the Random rules apply, except: The Len clause in the Open statement has no effect. Put writes all variables to disk contiguously; that is, with no padding between records. For any array other than an array in a user-defined type, Put writes only the data. No descriptor is written.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 267 of 1081

Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. The number of bytes written equals the number of characters in the string. For example, the following statements write 10 bytes to file number 1:
VarString$ = String$(10," ") Put #1,,VarString$

See Also Get statement, Open statement, Seek function, Type statement, VarType function. Example This example uses the Put statement to write data to a file. Five records of the user-defined type Record are written to the file.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

Dim MyRecord As Record, RecordNumber ' Declare variables. ' Open file for random access. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) For RecordNumber = 1 To 5 ' Loop 5 times. MyRecord.ID = RecordNumber ' Define ID. MyRecord.Name = "My Name" & RecordNumber ' Create a string. Put #1, RecordNumber, MyRecord ' Write record to file. Next RecordNumber Close #1 ' Close file.

PV Function
Description Returns a Double specifying the present value of an annuity based on periodic, fixed payments to be paid in the future and a fixed interest rate. Syntax PV(rate, nper, pmt[, fv[, type]]) The PV function has these named arguments Part Description

rate

Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 268 of 1081

nper

Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pmt

Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.

(continued) Part Description

fv

Optional. Variant specifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

type

Optional. Variant specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, Rate function, SLN function, SYD function.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 269 of 1081

Example In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the next 20 years. Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is made at the beginning or end of the payment period (PayType). Note that YrIncome is a negative number because it represents cash paid out from the annuity each year.
Dim Fmt, APR, TotPmts, YrIncome, FVal, PayType, PVal Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "###,##0.00" ' Define money format. APR = .0825 ' Annual percentage rate. TotPmts = 20 ' Total number of payments. YrIncome = 50000 ' Yearly income. FVal = 1000000 ' Future value. PayType = BEGINPERIOD ' Payment at beginning of month. PVal = PV(APR, TotPmts, -YrIncome, FVal, PayType) MsgBox "The present value is " & Format(PVal, Fmt) & "."

QBColor Function
Description Returns a Long representing the RGB color code corresponding to the specified color number. Syntax QBColor(color) The required color argument is a whole number in the range . Settings The color argument has these settings Number Color Number Color

Black

Gray

Blue

Light Blue

Green

10

Light Green

Cyan

11

Light Cyan

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 270 of 1081

Red

12

Light Red

Magenta

13

Light Magenta

Yellow

14

Light Yellow

White

15

Bright White

Remarks The color argument represents color values used by earlier versions of Basic (such as Microsoft Visual Basic for MS-DOS and the Basic Compiler). Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate color in the RGB system used by Visual Basic for Applications. See Also RGB function. Example This example uses the QBColor function to change the BackColor property of the form passed in as MyForm to the color indicated by ColorCode. QBColor accepts integer values between 0 and 15.
Sub ChangeBackColor (ColorCode As Integer, MyForm As Form) MyForm.BackColor = QBColor(ColorCode) End Sub

QueryClose Event
Applies To UserForm object. Description Occurs before a UserForm closes. Syntax Private Sub UserForm_QueryClose(cancel As Integer, closemode As Integer) The QueryClose event syntax has these parts

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 271 of 1081

Part

Description

cancel

An integer. Setting this argument to any value other than 0 stops the QueryClose event in all loaded user forms and prevents the UserForm and application from closing.

closemode

A value or constant indicating the cause of the QueryClose event.

Return Values The closemode argument returns the following values Constant Value Description

vbFormControlMenu

The user has chosen the Close command from the Control menu on the UserForm.

vbFormCode

The Unload statement is invoked from code.

vbAppWindows

The current Windows operating environment session is ending.

vbAppTaskManager

The Windows Task Manager is closing the application.

These constants are listed in the Visual Basic for Applications object library in the Object Browser. Note that vbFormMDIForm is also specified in the Object Browser, but is not yet supported. Remarks This event is typically used to make sure there are no unfinished tasks in the user forms included in an application before that application closes. For example, if a user hasn't saved new data in any UserForm, the application can prompt the user to save the data.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 272 of 1081

When an application closes, you can use the QueryClose event procedure to set the Cancel property to True, stopping the closing process. Example The following code forces the user to click the UserForm's client area to close it. If the user tries to use the Close box in the title bar, the Cancel parameter is set to a nonzero value, preventing termination. However, if the user has clicked the client area, CloseMode has the value 1 and the Unload Me is completed.
Private Sub UserForm_Activate() UserForm1.Caption = "You must Click me to kill me!" End Sub Private Sub UserForm_Click() Unload Me End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) ' Prevent user from closing with the Close box in the title bar. If CloseMode <> 1 Then Cancel = 1 UserForm1.Caption = "The Close box won't work! Click me!" End Sub

Raise Method
Applies To Err object. Description Generates a run-time error. Syntax object.Raise number, source, description, helpfile, helpcontext The Raise method has the following object qualifier and named arguments Argument Description

object

Required. Always the Err object.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 273 of 1081

number

Required. Long integer that identifies the nature of the error. Visual Basic errors (both Visual Basic-defined and userdefined errors) are in the range 0 65535. When setting the Number property to your own error code in a class module, you add your error code number to the vbObjectError constant. For example, to generate the error number 1050, assign vbObjectError + 1050 to the Number property.

source

Optional. String expression naming the object or application that generated the error. When setting this property for an object, use the form project.class. If source is not specified, the programmatic ID of the current Visual Basic project is used.

(continued) Argument Description

description

Optional. String expression describing the error. If unspecified, the value in Number is examined. If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as Description. If there is no Visual Basic error corresponding to Number, the "Application-defined or object-defined error" message is used.

helpfile

Optional. The fully qualified path to the Microsoft Windows Help file in which help on this error can be found. If unspecified, Visual Basic uses the fully qualified drive, path, and file name of the Visual Basic Help file.

helpcontext

Optional. The context ID identifying a topic within helpfile that provides help for the error. If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 274 of 1081

Remarks All of the arguments are optional except number. If you use Raise without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error. Raise is used for generating run-time errors and can be used instead of the Error statement. Raise is useful for generating errors when writing class modules, because the Err object gives richer information than is possible if you generate errors with the Error statement. For example, with the Raise method, the source that generated the error can be specified in the Source property, online Help for the error can be referenced, and so on. See Also Clear method, Description property, Err object, Error statement, HelpContext property, HelpContextID property ("Extensibility Object Model Language Reference"), HelpFile property, LastDLLError property, Number property, Source property. Specifics (Microsoft Access) The Raise method raises a specified Visual Basic error. The properties of the Err object are set as though the error had actually occurred in running code. However, this works only for Visual Basic errors, not for Microsoft Access errors or Microsoft Jet database engine errors. If you use the Raise method with an error number reserved by Microsoft Access or by the Microsoft Jet database engine, the value of the Err object's Description property is "Applicationdefined or object-defined error." To determine the descriptive string for a Microsoft Access or Jet database engine error that hasn't actually occurred in running code, use the AccessError method. The AccessError method takes a Long value that represents an error number and returns the descriptive string associated with the error. Example This example uses the Err object's Raise method to generate an error within an Automation object written in Visual Basic. It has the programmatic ID MyProj.MyObject.
Const MyContextID = 1010407 ' Define a constant for contextID. Function TestName(CurrentName, NewName) If Instr(NewName, "bob") Then ' Test the validity of NewName. ' Raise the exception. Err.Raise vbObjectError + 27, "MyProj.MyObject", _ "No ""bob"" allowed in your name", "c:\MyProj\MyHelp.Hlp", _ MyContextID End If End Function

Randomize Statement
Description Initializes the random-number generator.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 275 of 1081

Syntax Randomize [number] The optional number argument is a Variant or any valid numeric expression. Remarks Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value. If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value. Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence. See Also Rnd function, Timer function. Example This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.
Dim MyValue Randomize MyValue = Int((6 * Rnd) + 1) ' Initialize random-number generator. ' Generate random value between 1 and 6.

Rate Function
Description Returns a Double specifying the interest rate per period for an annuity. Syntax Rate(nper, pmt, pv[, fv[, type[, guess]]]) The Rate function has these named arguments

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 276 of 1081

Part

Description

nper

Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

pmt

Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.

pv

Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

fv

Optional. Variant specifying future value or cash balance you want after you make the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.

type

Optional. Variant specifying a number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

guess

Optional. Variant specifying value you estimate will be returned by Rate. If omitted, guess is 0.1 (10 percent).

Remarks An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 277 of 1081

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. Rate is calculated by iteration. Starting with the value of guess, Rate cycles through the calculation until the result is accurate to within 0.00001 percent. If Rate can't find a result after 20 tries, it fails. If your guess is 10 percent and Rate fails, try a different value for guess. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, SLN function, SYD function. Example This example uses the Rate function to calculate the interest rate of a loan given the total number of payments (TotPmts), the amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an approximation of the expected interest rate (Guess).
Dim Fmt, FVal, Guess, PVal, Payment, TotPmts, PayType, APR Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "##0.00" ' Define percentage format. FVal = 0 ' Usually 0 for a loan. Guess = .1 ' Guess of 10 percent. PVal = InputBox("How much did you borrow?") Payment = InputBox("What's your monthly payment?") TotPmts = InputBox("How many monthly payments do you have to make?") PayType = MsgBox("Do you make payments at the end of the month?", _ vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100 MsgBox "Your interest rate is " & Format(CInt(APR), Fmt) & " percent."

ReDim Statement
Description Used at procedure level to reallocate storage space for dynamic array variables. Syntax ReDim [Preserve] varname(subscripts) [As type] [, varname(subscripts) [As type]] . . . The ReDim statement syntax has these parts Part Description

Preserve

Optional. Keyword used to preserve the data in an existing array when you change the size of the last dimension.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 278 of 1081

varname

Required. Name of the variable; follows standard variable naming conventions.

(continued) Part Description

subscripts

Required. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

type

Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variablelength strings), String * length (for fixedlength strings), Object, Variant, a userdefined type, or an object type. Use a separate As type clause for each variable being defined. For a Variant containing an array, type describes the type of each element of the array, but doesn't change the Variant to some other type.

Remarks The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed using an As type clause, unless you're using the Preserve keyword, in which case, no changes of data type are permitted. If you use the Preserve keyword, you can resize only the last array dimension and you can't

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 279 of 1081

change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.
ReDim X(10, 10, 10) . . . ReDim Preserve X(10, 10, 15)

Similarly, when you use Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error. Caution If you make an array smaller than it was, data in the eliminated elements will be lost. If you pass an array to a procedure by reference, you can't redimension the array within the procedure. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. Caution The ReDim statement acts as a declarative statement if the variable it declares doesn't exist at module level or procedure level. If another variable with the same name is created later, even in a wider scope, ReDim will refer to the later variable and won't necessarily cause a compilation error, even if Option Explicit is in effect. To avoid such conflicts, ReDim should not be used as a declarative statement, but simply for redimensioning arrays. Note To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array. See Also Array function, Dim statement, Option Base statement, Private statement, Public statement, Set statement, Static statement. Example This example uses the ReDim statement to allocate and reallocate storage space for dynamicarray variables. It assumes the Option Base is 1.
Dim MyArray() As Integer Redim MyArray(5) For I = 1 To 5 MyArray(I) = I Next I ' Declare dynamic array. ' Allocate 5 elements. ' Loop 5 times. ' Initialize array.

The next statement resizes the array and erases the elements.
Redim MyArray(10) For I = 1 To 10 MyArray(I) = I Next I ' Resize to 10 elements. ' Loop 10 times. ' Initialize array.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 280 of 1081

The following statement resizes the array but does not erase elements.
Redim Preserve MyArray(15) ' Resize to 15 elements.

Rem Statement
Description Used to include explanatory remarks in a program. Syntax Rem comment You can also use the following syntax: ' comment The optional comment argument is the text of any comment you want to include. A space is required between the Rem keyword and comment. Remarks If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement. Execution continues with the first executable statement following the Rem statement. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon (:). You can use a apostrophe (') instead of the Rem keyword. When you use a apostrophe, the colon is not required after other statements. Example This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.
Rem This is the first form of the syntax.

The following shows the second form of the syntax.


Dim MyStr1, MyStr2 MyStr1 = "Hello": Rem Comment after a statement separated by a colon. MyStr2 = "Goodbye" ' This is also a comment; no colon is needed.

Remove Method
Applies To

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 281 of 1081

Collection object. Description Removes a member from a Collection object. Syntax object.Remove index The Remove method syntax has the following object qualifier and part Part Description

object

Required. An object expression that evaluates to an object in the Applies To list.

index

Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks If the value provided as index doesn't match an existing member of the collection, an error occurs. See Also Add method, Add method ("Extensibility Object Model Language Reference"), Item method, Item method ("Extensibility Object Model Language Reference"), ItemAdded event ("Extensibility Object Model Language Reference"), ItemRemoved event ("Extensibility Object Model Language Reference"). Example This example illustrates the use of the Remove method to remove objects from a Collection object, MyClasses. This code removes the object whose index is 1 on each iteration of the loop.
Dim Num, MyClasses For Num = 1 To MyClasses.Count MyClasses.Remove 1 Next Num

' Remove the first object each time ' through the loop until there are ' no objects left in the collection.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 282 of 1081

Example (Extensibility Object Model) The example verifies that a particular member of the VBComponents collection is a module, and then it uses the Remove method to remove the module.
Debug.Print Application.VBE.ActiveVBProject.VBComponents(4).Name Application.VBE.ActiveVBProject.VBComponents.Remove _ Application.VBE.ActiveVBProject.VBComponents(4)

Reset Statement
Description Closes all disk files opened using the Open statement. Syntax Reset Remarks The Reset statement closes all active files opened by the Open statement and writes the contents of all file buffers to disk. See Also Close statement, End statement, Open statement. Example This example uses the Reset statement to close all open files and write the contents of all file buffers to disk. Note the use of the Variant variable FileNumber as both a string and a number.
Dim FileNumber For FileNumber = 1 To 5 ' Loop 5 times. ' Open file for output. FileNumber is concatenated into the string ' TEST for the filename, but is a number following a #. Open "TEST" & FileNumber For Output As #FileNumber Write #FileNumber, "Hello World" ' Write data to file. Next FileNumber Reset ' Close files and write contents ' to disk.

Resize Event
Applies To UserForm object. Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 283 of 1081

Occurs when a user form is resized. Syntax Private Sub UserForm_Resize( ) Remarks Use a Resize event procedure to move or resize controls when the parent UserForm is resized. You can also use this event procedure to recalculate variables or properties. Example The following example uses the Activate and Click events to illustrate triggering of the UserForm's Resize event. As the user clicks the client area of the form, it grows or shrinks and the new height is specified in the title bar. Note that the Tag property is used to store the UserForm's initial height.
' Activate event for UserForm1 Private Sub UserForm_Activate() UserForm1.Caption = "Click me to make me taller!" Tag = Height ' Save the initial height. End Sub ' Click event for UserForm1 Private Sub UserForm_Click() Dim NewHeight As Single NewHeight = Height ' If the form is small, make it tall. If NewHeight = Val(Tag) Then Height = Val(Tag) * 2 Else ' If the form is tall, make it small. Height = Val(Tag) End If End Sub ' Resize event for UserForm1 Private Sub UserForm_Resize() UserForm1.Caption = "New Height: " & Height & " & "Click to resize me!" End Sub

" _

Resume Statement
Description Resumes execution after an error-handling routine is finished. Syntax Resume [0] Resume Next Resume line

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 284 of 1081

The Resume statement syntax can have any of the following forms Statement Description

Resume

If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.

Resume Next

If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement).

Resume line

Execution resumes at line specified in the required line argument. The line argument is a line label or line number and must be in the same procedure as the error handler.

Remarks If you use a Resume statement anywhere except in an error-handling routine, an error occurs. See Also End statement, Err object, Exit statement, On Error statement. Example This example uses the Resume statement to end error handling in a procedure, and then resume execution with the statement that caused the error. Error number 55 is generated to illustrate using the Resume statement.
Sub ResumeStatementDemo() On Error GoTo ErrorHandler Open "TESTFILE" For Output As #1 Kill "TESTFILE" ' Enable error-handling routine. ' Open file for output. ' Attempt to delete open file.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 285 of 1081

Exit Sub ' Exit Sub to avoid error handler. ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 55 ' "File already open" error. Close #1 ' Close open file. Case Else ' Handle other situations here.... End Select Resume ' Resume execution at same line ' that caused the error. End Sub

RGB Function
Description Returns a Long whole number representing an RGB color value. Syntax RGB(red, green, blue) The RGB function syntax has these named arguments. Part Description

red

Required; Variant (Integer). Number in the range 0 255, inclusive, that represents the red component of the color.

green

Required; Variant (Integer). Number in the range 0 255, inclusive, that represents the green component of the color.

blue

Required; Variant (Integer). Number in the range 0 255, inclusive, that represents the blue component of the color.

Remarks Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed. The value for any argument to RGB that exceeds 255 is assumed to be 255. The following table lists some standard colors and the red, green, and blue values they include

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 286 of 1081

Color

Red value

Green value

Blue value

Black

Blue

255

Green

255

Cyan

255

255

Red

255

Magenta

255

255

Yellow

255

255

White

255

255

255

See Also QBColor function. Specifics (Macintosh) The RGB color values returned by this function are incompatible with those used by the Macintosh operating system. They may be used within the context of Microsoft applications for the Macintosh, but should not be used when communicating color changes directly to the Macintosh operating system. Example This example shows how the RGB function is used to return a whole number representing an RGB color value. It is used for those application methods and properties that accept a color specification. The object MyObject and its property are used for illustration purposes only. If MyObject does not exist, or if it does not have a Color property, an error occurs.
Dim RED, I, RGBValue, MyObject Red = RGB(255, 0, 0) I = 75 RGBValue = RGB(I, 64 + I, 128 + I) MyObject.Color = RGB(255, 0, 0) ' Return the value for Red. ' Initialize offset. ' Same as RGB(75, 139, 203). ' Set the Color property of ' MyObject to Red.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 287 of 1081

Example (Microsoft Excel) This example sets the gridline color in the active window in Book1.xls to red.
Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate ActiveWindow.GridlineColor = RGB(255,0,0)

This example sets the color of the tick labels on the value axis in Chart1 to green.
Charts("Chart1").Axes(xlValue).TickLabels.Font.Color = RGB(0, 255, 0)

This example sets the marker background and foreground colors for the second point in series one in Chart1 to green and red, respectively.
With Charts("Chart1").SeriesCollection(1).Points(2) .MarkerBackgroundColor = RGB(0,255,0) ' Green. .MarkerForegroundColor = RGB(255,0,0) ' Red. End With

This example sets the interior pattern color for rectangle one on Sheet1 to red.
With Worksheets("Sheet1").Rectangles(1).Interior .Pattern = xlGrid .PatternColor = RGB(255,0,0) End With

Right Function
Description Returns a Variant (String) containing a specified number of characters from the right side of a string. Syntax Right (string, length) The Right function syntax has these named arguments. Part Description

string

Required. String expression from which the rightmost characters are returned. If string contains Null, Null is returned.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 288 of 1081

length

Required; Variant (Long). Numeric expression indicating how many characters to return. If 0, a zero-length string (" ") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks To determine the number of characters in string, use the Len function. Note Use the RightB function with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes. See Also Left function, Len function, Mid function. Example This example uses the Right function to return a specified number of characters from the right side of a string.
Dim AnyString, MyStr AnyString = "Hello World" MyStr = Right(AnyString, 1) MyStr = Right(AnyString, 6) MyStr = Right(AnyString, 20) ' Define string. ' Returns "d". ' Returns " World". ' Returns "Hello World".

RmDir Statement
Description Removes an existing directory or folder. Syntax RmDir path The required path argument is a string expression that identifies the directory or folder to be removed. The path may include the drive. If no drive is specified, RmDir removes the directory or folder on the current drive. Remarks An error occurs if you try to use RmDir on a directory or folder containing files. Use the Kill statement to delete all files before attempting to remove a directory or folder. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 289 of 1081

ChDir statement, CurDir function, Kill statement, MkDir statement. Example This example uses the RmDir statement to remove an existing directory or folder.
' Assume that MYDIR is an empty directory or folder. RmDir "MYDIR" ' Remove MYDIR.

Rnd Function
Description Returns a Single containing a random number. Syntax Rnd[(number)] The optional number argument is a Single or any valid numeric expression. Return Values If number is Rnd generates

Less than zero

The same number every time, using number as the seed.

Greater than zero

The next random number in the sequence.

Equal to zero

The most recently generated number.

Not supplied

The next random number in the sequence.

Remarks The Rnd function returns a value less than 1 but greater than or equal to zero. The value of number determines how Rnd generates a random number: For any given initial seed, the same number sequence is generated because each successive call

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 290 of 1081

to the Rnd function uses the previous number as a seed for the next number in the sequence. Before calling Rnd, use the Randomize statement without an argument to initialize the randomnumber generator with a seed based on the system timer. To produce random integers in a given range, use this formula:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range. Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence. See Also Randomize statement, Timer function. Example This example uses the Rnd function to generate a random integer value from 1 to 6.
Dim MyValue MyValue = Int((6 * Rnd) + 1) ' Generate random value between 1 and 6.

RSet Statement
Description Right aligns a string within a string variable. Syntax RSet stringvar = string The RSet statement syntax has these parts. Part Description

stringvar

Required. Name of string variable.

string

Required. String expression to be rightaligned within stringvar.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 291 of 1081

Remarks If stringvar is longer than string, RSet replaces any leftover characters in stringvar with spaces, back to its beginning. Note RSet can't be used with user-defined types.

See Also Data type summary, LSet statement. Example This example uses the RSet statement to right align a string within a string variable.
Dim MyString MyString = "0123456789" Rset MyString = "Right->" ' Initialize string. ' MyString contains "

Right->".

RTrim Function
See LTrim, RTrim, and Trim Functions.

SaveSetting Statement
Description Saves or creates an application entry in the Windows registry. Syntax SaveSetting appname, section, key, setting The SaveSetting statement syntax has these named arguments. Part Description

appname

Required. String expression containing the name of the application or project to which the setting applies.

section

Required. String expression containing the name of the section where the key setting is being saved.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 292 of 1081

key

Required. String expression containing the name of the key setting being saved.

setting

Required. Expression containing the value that key is being set to.

Remarks An error occurs if the key setting can't be saved for any reason. See Also DeleteSetting statement, GetAllSettings function, GetSetting function. Example The following example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the MyApp application, and then uses the DeleteSetting statement to remove them.
' Place some settings in the registry. SaveSetting appname := "MyApp", section := "Startup", _ key := "Top", setting := 75 SaveSetting "MyApp","Startup", "Left", 50 ' Remove section and all its settings from registry. DeleteSetting "MyApp", "Startup"

Second Function
Description Returns a Variant (Integer) specifying a whole number between 0 and 59, inclusive, representing the second of the minute. Syntax Second(time) The required time argument is any Variant, numeric expression, string expression, or any combination, that can represent a time. If time contains Null, Null is returned. See Also Day function, Hour function, Minute function, Now function, Time function, Time statement. Example This example uses the Second function to obtain the second of the minute from a specified time. In the development environment, the time literal is displayed in short time format using the

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 293 of 1081

locale settings of your code.


Dim MyTime, MySecond MyTime = #4:35:17 PM# MySecond = Second(MyTime) ' Assign a time. ' MySecond contains 17.

Seek Function
Description Returns a Long specifying the current read/write position within a file opened using the Open statement. Syntax Seek(filenumber) The required filenumber argument is an Integer containing a valid file number. Remarks Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31 1), inclusive. The following describes the return values for each file access mode. Mode Return Value

Random

Number of the next record read or written.

Binary, Output, Append, Input

Byte position at which the next operation takes place. The first byte in a file is at position 1, the second byte is at position 2, and so on.

See Also Get statement, Loc function, Open statement, Put statement, Seek statement. Example This example uses the Seek function to return the current file position. The example assumes TESTFILE is a file containing records of the user-defined type Record.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 294 of 1081

For files opened in Random mode, Seek returns number of next record.
Dim MyRecord As Record ' Declare variable. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) Do While Not EOF(1) ' Loop until end of file. Get #1, , MyRecord ' Read next record. Debug.Print Seek(1) ' Print record number to Debug ' window. Loop Close #1 ' Close file.

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.
Dim MyChar Open "TESTFILE" For Input As #1 Do While Not EOF(1) MyChar = Input(1, #1) Debug.Print Seek(1) Loop Close #1 ' Open file for reading. ' Loop until end of file. ' Read next character of data. ' Print byte position to Debug ' window. ' Close file.

Seek Statement
Description Sets the position for the next read/write operation within a file opened using the Open statement. Syntax Seek [#]filenumber, position The Seek statement syntax has these parts: Part Description

filenumber

Required. Any valid file number.

position

Required. Number in the range 1 2,147,483,647, inclusive, that indicates where the next read/write operation should occur.

Remarks Record numbers specified in Get and Put statements override file positioning performed by Seek. Performing a file-write operation after a Seek operation beyond the end of a file extends the file.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 295 of 1081

If you attempt a Seek operation to a negative or zero position, an error occurs. See Also Get statement, Loc function, Open statement, Put statement, Seek function. Example This example uses the Seek statement to set the position for the next read or write within a file. This example assumes TESTFILE is a file containing records of the user-defined type Record.
Type Record ID As Integer Name As String * 20 End Type ' Define user-defined type.

For files opened in Random mode, Seek sets the next record.
Dim MyRecord As Record, MaxSize, RecordNumber ' Declare variables. ' Open file in random-file mode. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) MaxSize = LOF(1) \ Len(MyRecord) ' Get number of records in file. ' The loop reads all records starting from the last. For RecordNumber = MaxSize To 1 Step - 1 Seek #1, RecordNumber ' Set position. Get #1, , MyRecord ' Read record. Next RecordNumber Close #1 ' Close file.

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.
Dim MaxSize, NextChar, MyChar Open "TESTFILE" For Input As #1 ' Open file for input. MaxSize = LOF(1) ' Get size of file in bytes. ' The loop reads all characters starting from the last. For NextChar = MaxSize To 1 Step -1 Seek #1, NextChar ' Set position. MyChar = Input(1, #1) ' Read character. Next NextChar Close #1 ' Close file.

Select Case Statement


Description Executes one of several groups of statements, depending on the value of an expression. Syntax Select Case testexpression [Case expressionlist-n [statements-n]] ... [Case Else [elsestatements]] End Select

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 296 of 1081

The Select Case statement syntax has these parts: Part Description

testexpression

Required. Any numeric expression or string expression.

expressionlistn

Required if a Case appears. Delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression. The To keyword specifies a range of values. If you use the To keyword, the smaller value must appear before To. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values. If not supplied, the Is keyword is automatically inserted.

statements-n

Optional. One or more statements executed if testexpression matches any part of expressionlist-n.

elsestatements

Optional. One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed. The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following End Select. You can use multiple expressions or ranges in each Case clause. For example, the following line is valid:
Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

Note The Is comparison operator is not the same as the Is keyword used in the Select Case statement. You also can specify ranges and multiple expressions for character strings. In the following example, Case matches strings that are exactly equal to everything, strings that fall between nuts and soup in alphabetic order, and the current value of TestItem:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 297 of 1081

Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement. See Also Choose function, End statement, If...Then...Else statement, On...GoSub, On...GoTo statements. Example This example uses the Select Case statement to evaluate the value of a variable. The second Case clause contains the value of the variable being evaluated, and therefore only the statement associated with it is executed.
Dim Number Number = 8 ' Initialize variable. Select Case Number ' Evaluate Number. Case 1 To 5 ' Number between 1 and 5. Debug.Print "Between 1 and 5" ' The following is the only Case clause that evaluates to True. Case 6, 7, 8 ' Number between 6 and 8. Debug.Print "Between 6 and 8" Case Is > 8 And Number < 11 ' Number is 9 or 10. Debug.Print "Greater than 8" Case Else ' Other values. Debug.Print "Not between 1 and 10" End Select

Example (Microsoft Excel) This example displays the name of the mail system installed on the computer.
Select Case Application.MailSystem Case Is = xlMAPI MsgBox "Mail system is Microsoft Mail" Case Is = xlPowerTalk MsgBox "Mail system is PowerTalk" Case Is = xlNoMailSystem MsgBox "No mail system installed" End Select

This example displays a message box that indicates the location of the active cell in the PivotTable.
Worksheets("Sheet1").Activate Select Case ActiveCell.LocationInTable Case Is = xlRowHeader MsgBox "Active cell is part of a row header" Case Is = xlColumnHeader MsgBox "Active cell is part of a column header" Case Is = xlPageHeader MsgBox "Active cell is part of a page header" Case Is = xlDataHeader MsgBox "Active cell is part of a data header" Case Is = xlRowItem MsgBox "Active cell is part of a row item" Case Is = xlColumnItem MsgBox "Active cell is part of a column item" Case Is = xlPageItem MsgBox "Active cell is part of a page item" Case Is = xlDataItem MsgBox "Active cell is part of a data item" Case Is = xlTableBody MsgBox "Active cell is part of the table body" End Select

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 298 of 1081

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.
Worksheets("Sheet1").Activate If IsError(ActiveCell.Value) Then errval = ActiveCell.Value Select Case errval Case CVErr(xlErrDiv0) MsgBox "#DIV/0! error" Case CVErr(xlErrNA) MsgBox "#N/A error" Case CVErr(xlErrName) MsgBox "#NAME? error" Case CVErr(xlErrNull) MsgBox "#NULL! error" Case CVErr(xlErrNum) MsgBox "#NUM! error" Case CVErr(xlErrRef) MsgBox "#REF! error" Case CVErr(xlErrValue) MsgBox "#VALUE! error" Case Else MsgBox "This should never happen!!" End Select End If

SendKeys Statement
Description Sends one or more keystrokes to the active window as if typed at the keyboard. Syntax SendKeys string[, wait] The SendKeys statement syntax has these named arguments: Part Description

string

Required. String expression specifying the keystrokes to send.

wait

Optional. Boolean value specifying the wait mode. If False (default), control is returned to the procedure immediately after the keys are sent. If True, keystrokes must be processed before control is returned to the procedure.

Remarks Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter A, use "A" for string. To represent more

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 299 of 1081

than one character, append each additional character to the one preceding it. To represent the letters A, B, and C, use "ABC" for string. The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({}). For example, to specify the plus sign, use {+}. Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To specify brace characters, use {{} and {}}. To specify characters that aren't displayed when you press a key, such as ENTER or TAB, and keys that represent actions rather than characters, use the codes shown below: Key Code

BACKSPACE

{BACKSPACE}, {BS}, or {BKSP}

BREAK

{BREAK}

CAPS LOCK

{CAPSLOCK}

DEL or DELETE

{DELETE} or {DEL}

DOWN ARROW

{DOWN}

END

{END}

ENTER

{ENTER} or ~

ESC

{ESC}

HELP

{HELP}

HOME

{HOME}

(continued)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 300 of 1081

INS or INSERT

{INSERT} or {INS}

LEFT ARROW

{LEFT}

NUM LOCK

{NUMLOCK}

PAGE DOWN

{PGDN}

PAGE UP

{PGUP}

PRINT SCREEN

{PRTSC}

RIGHT ARROW

{RIGHT}

SCROLL LOCK

{SCROLLLOCK}

TAB

{TAB}

UP ARROW

{UP}

F1

{F1}

F2

{F2}

F3

{F3}

F4

{F4}

F5

{F5}

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 301 of 1081

F6

{F6}

F7

{F7}

F8

{F8}

F9

{F9}

F10

{F10}

F11

{F11}

F12

{F12}

F13

{F13}

F14

{F14}

F15

{F15}

F16

{F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following codes: Key Code

SHIFT

CTRL

ALT

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 302 of 1081

while E is pressed, followed by C without SHIFT, use "+EC". To specify repeating keys, use the form {key number}. You must put a space between key and number. For example, {LEFT 42} means press the LEFT ARROW key 42 times; {h 10} means press H 10 times. Note SendKeys to send keystrokes to an application that is not designed to run in Microsoft Windows. SendKeys also can't send the PRINT SCREEN key {PRTSC} to any application. See Also AppActivate statement, DoEvents function. Example This example uses the Shell function to run the Calculator application included with Microsoft Windows. It uses the SendKeys statement to send keystrokes to add some numbers, and then quit the Calculator. The SendKeys statement is not available on the Macintosh. (To see the example, paste it into a procedure, then run the procedure. Because AppActivate changes the focus to the Calculator application, you can't single step through the code.)
Dim ReturnValue, I ReturnValue = Shell("Calc.exe", 1) AppActivate ReturnValue For I = 1 To 100 SendKeys I & "{+}", True Next I SendKeys "=", True SendKeys "%{F4}", True ' Run Calculator. ' Activate the Calculator. ' Set up counting loop. ' Send keystrokes to Calculator ' to add each value of I. ' Get grand total. ' Send ALT+F4 to close Calculator.

Set Statement
Description Assigns an object reference to a variable or property. Syntax Set objectvar = {[New] objectexpression | Nothing} The Set statement syntax has these parts: Part Description

objectvar

Required. Name of the variable or property; follows standard variable naming conventions.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 303 of 1081

New

Optional. New is usually used during declaration to enable implicit object creation. When New is used with Set, it creates a new instance of the class. If objectvar contained a reference to an object, that reference is released when the new one is assigned. The New keyword can't be used to create new instances of any intrinsic data type and can't be used to create dependent objects.

(continued) objectexpression Required. Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.

Nothing

Optional. Discontinues association of objectvar with any specific object. Assigning Nothing to objectvar releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

Remarks To be valid, objectvar must be an object type consistent with the object being assigned to it. The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object. The following example illustrates how Dim is used to declare an array with the type Form1. No instance of Form1 actually exists. Set then assigns references to new instances of Form1 to the myChildForms variable. Such code might be used to create child forms in an MDI application.
Dim Set Set Set Set myChildForms(1 to myChildForms(1) = myChildForms(2) = myChildForms(3) = myChildForms(4) = 4) As Form1 New Form1 New Form1 New Form1 New Form1

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because such variables are references to the object rather than copies of the object, any change in the object is reflected in all variables that refer to it. However, when you use the New keyword in the Set statement, you are actually creating an instance of the object.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 304 of 1081

See Also Dim statement, Let statement, Private statement, Public statement, ReDim statement, Static statement. Example This example uses the Set statement to assign object references to variables. YourObject is assumed to be a valid object with a Text property.
Dim YourObject, MyObject, MyStr Set MyObject = YourObject ' Assign object reference. ' MyObject and YourObject refer to the same object. YourObject.Text = "Hello World" ' Initialize property. MyStr = MyObject.Text ' Returns "Hello World". ' Discontinue association. MyObject no longer refers to YourObject. Set MyObject = Nothing ' Release the object.

Example (Microsoft Excel) This example adds a new worksheet to the active workbook and then sets the name of the worksheet.
Set newSheet = Worksheets.Add newSheet.Name = "1995 Budget"

This example creates a new worksheet and then inserts into it a list of all the names in the active workbook, including their formulas in A1-style notation in the language of the user.
Set newSheet = ActiveWorkbook.Worksheets.Add i = 1 For Each nm In ActiveWorkbook.Names newSheet.Cells(i, 1).Value = nm.NameLocal newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal i = i + 1 Next

SetAttr Statement
Description Sets attribute information for a file. Syntax SetAttr pathname, attributes The SetAttr statement syntax has these named arguments:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 305 of 1081

Part

Description

pathname

Required. String expression that specifies a file name may include directory or folder, and drive.

attributes

Required. Constant or numeric expression, whose sum specifies file attributes.

Settings The attributes argument settings are: Constant Value Description

vbNormal

Normal (default).

vbReadOnly

Read-only.

vbHidden

Hidden.

vbSystem

System file.

vbArchive

32

File has changed since last backup.

Note These constants are specified by Visual Basic for Applications. The names can be used anywhere in your code in place of the actual values. Remarks A run-time error occurs if you try to set the attributes of an open file. See Also FileAttr function, GetAttr function. Specifics (Macintosh) The following constants aren't available on the Macintosh:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 306 of 1081

Constant

Value

Description

vbSystem

System file.

vbArchive

32

File has changed since last backup.

The following constant is available only on the Macintosh. Constant Value Description

vbAlias

64

Specified file name is an alias.

Example This example uses the SetAttr statement to set attributes for a file.
SetAttr "TESTFILE", vbHidden ' Set hidden attribute. SetAttr "TESTFILE", vbHidden + vbReadOnly ' Set hidden and read-only ' attributes.

Sgn Function
Description Returns a Variant (Integer) indicating the sign of a number. Syntax Sgn(number) The required number argument can be any valid numeric expression. Return Values If number is Sgn returns

Greater than zero

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 307 of 1081

Equal to zero

Less than zero

Remarks The sign of the number argument determines the return value of the Sgn function. See Also Abs function. Example This example uses the Sgn function to determine the sign of a number.
Dim MyVar1, MyVar2, MyVar3, MySign MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0 MySign = Sgn(MyVar1) MySign = Sgn(MyVar2) MySign = Sgn(MyVar3)

' Returns 1. ' Returns -1. ' Returns 0.

Shell Function
Description Runs an executable program and returns a Variant (Double) representing the program's task ID if successful, otherwise it returns zero. Syntax Shell(pathname[,windowstyle]) The Shell function syntax has these named arguments: Part Description

pathname

Required; Variant (String). Name of the program to execute and any required arguments or command-line switches; may include directory or folder and drive.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 308 of 1081

windowstyle

Optional. Variant (Integer) corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus.

The windowstyle named argument has these values: Constant Value Description

vbHide

Window is hidden and focus is passed to the hidden window.

vbNormalFocus

Window has focus and is restored to its original size and position.

vbMinimizedFocus

Window is displayed as an icon with focus.

vbMaximizedFocus

Window is maximized with focus.

vbNormalNoFocus

Window is restored to its most recent size and position. The currently active window remains active.

vbMinimizedNoFocus

Window is displayed as an icon. The currently active window remains active.

Remarks If the Shell function successfully executes the named file, it returns the task ID of the started program. The task ID is a unique number that identifies the running program. If the Shell function can't start the named program, an error occurs. If you use the MacID function with Shell in Microsoft Windows, an error occurs. Note The Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed. See Also AppActivate statement, MacID function.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 309 of 1081

Specifics (Macintosh) The Shell function syntax has these named arguments: Part Description

pathname

On the Macintosh, you can use the MacID function to specify an application's signature instead of its name. The following example uses the signature for Microsoft Word:

Shell MacID("MSWD")

windowstyle

On the Macintosh (System 7.0 or later), windowstyle only determines whether or not the application gets the focus when it is run.

The vbHide constant is not applicable on Apple Macintosh platforms. Example This example uses the Shell function to run an application specified by the user. On the Macintosh, using the MacID function ensures that the application can be launched even if the file name of the application has been changed. The Shell function is not available on Macintosh versions earlier than System 7.0.
' In Microsoft Windows: ' Specifying 1 as the second argument opens the application in ' normal size and gives it the focus. Dim RetVal RetVal = Shell("C:\WINDOWS\CALC.EXE", 1) ' Run Calculator. ' On the Macintosh: ' Both statements launch Microsoft Excel. RetVal = Shell("Microsoft Excel") ' Specify filename. RetVal = Shell(MacID("XCEL")) ' Specify signature.

Show Method
Applies To CodePane object, UserForm object. Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 310 of 1081

Displays a UserForm object. Syntax [object.]Show The optional object is an object expression that evaluates to an object in the Applies To list. If object is omitted, the UserForm associated with the active UserForm module is assumed to be object. Remarks If the specified object isn't loaded when the Show method is invoked, Visual Basic automatically loads it. A UserForm is always modal; therefore, the user must respond before using any other part of the application. No subsequent code is executed until the UserForm is hidden or unloaded. Although other forms in the application are disabled when a UserForm is displayed, other applications are not. See Also Hide method, Load statement, Unload statement. Example The following example assumes two UserForms in a program. In UserForm1's Initialize event, UserForm2 is loaded and shown. When the user clicks UserForm2, it is hidden and UserForm1 appears. When UserForm1 is clicked, UserForm2 is shown again.
' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event for UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub ' This is the click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub

Example (Extensibility Object Model) The following example uses the Show method to move the specified code pane to the foreground.
Application.VBE.CodePanes(2).Show

Sin Function
file://C:\temporary\~hhE561.htm 3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 311 of 1081

Description Returns a Double specifying the sine of an angle. Syntax Sin(number) The required number argument is a Double or any valid numeric expression that expresses an angle in radians. Remarks The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse. The result lies in the range 1 to 1. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. See Also Atn function, Cos function, Tan function. Example This example uses the Sin function to return the sine of an angle.
Dim MyAngle, MyCosecant MyAngle = 1.3 MyCosecant = 1 / Sin(MyAngle) ' Define angle in radians. ' Calculate cosecant.

Single Data Type


Description 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.401298E45 for negative values and from 1.401298E45 to 3.402823E38 for positive values. The type-declaration character for Single is the exclamation point (!). See Also Data type summary, Deftype statements, Double data type, Variant data type.

SLN Function
file://C:\temporary\~hhE561.htm 3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 312 of 1081

Description Returns a Double specifying the straight-line depreciation of an asset for a single period. Syntax SLN(cost, salvage, life) The SLN function has these named arguments: Part Description

cost

Required. Double specifying initial cost of the asset.

salvage

Required. Double specifying value of the asset at the end of its useful life.

life

Required. Double specifying length of the useful life of the asset.

Remarks The depreciation period must be expressed in the same unit as the life argument. All arguments must be positive numbers. See Also DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SYD function. Example This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, PDepr Const YEARMONTHS = 12 ' Number of months in a year. Fmt = "###,##0.00" ' Define money format. InitCost = InputBox("What's the initial cost of the asset?") SalvageVal = InputBox("What's the asset's value at the end of its " _ & "useful life?") MonthLife = InputBox("What's the asset's useful life in months?") Do While MonthLife < YEARMONTHS ' Ensure period is >= 1 year. MsgBox "Asset life must be a year or more." MonthLife = InputBox("What's the asset's useful life in months?") Loop LifeTime = MonthLife / YEARMONTHS ' Convert months to years. If LifeTime <> Int(MonthLife / YEARMONTHS) Then LifeTime = Int(LifeTime + 1) ' Round up to nearest year. End If

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 313 of 1081

PDepr = SLN(InitCost, SalvageVal, LifeTime) MsgBox "The depreciation is " & Format(PDepr, Fmt) & " per year."

Source Property
Applies To Err object. Description Returns or sets a string expression specifying the name of the object or application that originally generated the error. Read/write. Remarks The Source property specifies a string expression representing the object that generated the error; the expression is usually the object's class name or programmatic ID. Use Source to provide information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application. When generating an error from code, Source is your application's programmatic ID. For class modules, Source should contain a name having the form project.class. When an unexpected error occurs in your code, the Source property is automatically filled in. For errors in a standard module, Source contains the project name. For errors in a class module, Source contains a name with the project.class form. See Also Description property, Err object, GetObject function, HelpContext property, HelpContextID property ("Extensibility Object Model Language Reference"), HelpFile property, LastDLLError property, Number property, On Error statement. Example This example assigns the Programmatic ID of an Automation object created in Visual Basic to the variable MyObjectID, and then assigns that to the Source property of the Err object when it generates an error with the Raise method. When handling errors, you should not use the Source property (or any Err properties other than Number) programatically. The only valid use of properties other than Number is for displaying rich information to an end user in cases where you can't handle an error. The example assumes that App and MyClass are valid references.
Dim MyClass, MyObjectID, MyHelpFile, MyHelpContext ' An object of type MyClass generates an error and fills all Err object ' properties, including Source, which receives MyObjectID, which is a ' combination of the Title property of the App object and the Name ' property of the MyClass object. MyObjectID = App.Title & "." & MyClass.Name Err.Raise Number := vbObjectError + 894, Source := MyObjectID, _ Description := "Was not able to complete your task", _ HelpFile := MyHelpFile, HelpContext := MyHelpContext

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 314 of 1081

Space Function
Description Returns a Variant (String) consisting of the specified number of spaces. Syntax Space(number) The required number argument is the number of spaces you want in the string. Remarks The Space function is useful for formatting output and clearing data in fixed-length strings. See Also Spc function, String function. Example This example uses the Space function to return a string consisting of a specified number of spaces.
Dim MyString ' Returns a string with 10 spaces. MyString = Space(10) ' Insert 10 spaces between two strings. MyString = "Hello" & Space(10) & "World"

Spc Function
Description Used with the Print # statement or the Print method to position output. Syntax Spc(n) The required n argument is the number of spaces to insert before displaying or printing the next expression in a list. Remarks If n is less than the output line width, the next print position immediately follows the number of spaces printed. If n is greater than the output line width, Spc calculates the next print position

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 315 of 1081

using the formula: currentprintposition + (n Mod width) For example, if the current print position is 24, the output line width is 80, and you specify Spc (90), the next print will start at position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the output line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates spaces equal to n (width currentprintposition). Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter i occupies less than one fixed-width column. See Also Mod operator, Print # statement, Print method, Space function, Tab function, Width # statement. Example This example uses the Spc function to position output in a file and in the Debug window.
' The Spc function can be used with the Print # statement. Open "TESTFILE" For Output As #1 ' Open file for output. Print #1, "10 spaces between here"; Spc(10); "and here." Close #1 ' Close file.

The following statement causes the text to be printed in the Debug window (using the Print method), preceded by 30 spaces.
Debug.Print Spc(30); "Thirty spaces later..."

Sqr Function
Description Returns a Double specifying the square root of a number. Syntax Sqr(number) The required number argument is a Double or any valid numeric expression greater than or equal to zero. Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 316 of 1081

This example uses the Sqr function to calculate the square root of a number.
Dim MySqr MySqr = Sqr(4) MySqr = Sqr(23) MySqr = Sqr(0) MySqr = Sqr(-4) ' Returns 2. ' Returns 4.79583152331272. ' Returns 0. ' Generates a run-time error.

StartUpPosition Property
Applies To UserForm object. Description Returns or sets a value specifying the position of a UserForm when it first appears. You can use one of four settings for StartUpPosition: Setting Value Description

Manual

No initial setting specified.

CenterOwner

Center on the item to which the UserForm belongs.

CenterScreen

Center on the whole screen.

Windows Default

Position in upper-left corner of screen.

Remarks You can set the StartUpPosition property programmatically or from the Properties window. See Also Load statement. Example The following example uses the Load statement and the Show method in UserForm1's Click event to load UserForm2 with the StartUpPosition property set to 3 (the Windows default

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 317 of 1081

position). The Show method then makes UserForm2 visible.


Private Sub UserForm_Click() Load UserForm2 UserForm2.StartUpPosition = 3 UserForm2.Show End Sub

Static Statement
Description Used at procedure level to declare variables and allocate storage space. Variables declared with the Static statement retain their values as long as the code is running. Syntax Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type]] . . . The Static statement syntax has these parts: Part Description

varname

Required. Name of the variable; follows standard variable naming conventions.

subscripts

Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

New

Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 318 of 1081

type and can't be used to declare instances of dependent objects.

type

Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, (for variablelength strings), String * length (for fixedlength strings), Object, Variant, a userdefined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks Once module code is running, variables declared with the Static statement retain their value until the module is reset or restarted. Use the Static statement in nonstatic procedures to explicitly declare variables that are visible only within the procedure, but whose lifetime is the same as the module in which the procedure is defined. Use a Static statement within a procedure to declare the data type of a variable that retains its value between procedure calls. For example, the following statement declares a fixed-size array of integers:
Static EmployeeNumber(200) As Integer

The following statement declares a variable for a new instance of a worksheet:


Static X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. When you use the New keyword in the declaration, an instance of the object is created on the first reference to the object. If you don't specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default. Note The Static statement and the Static keyword are similar, but used for different effects. If you declare a procedure using the Static keyword (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once, and the value of the variables is preserved for the entire time the program is running. For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited. The Static statement is used to declare specific variables within nonstatic procedures to preserve their value for as long as the program is running. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 319 of 1081

Note When you use Static statements within a procedure, put them at the beginning of the procedure with other declarative statements such as Dim. See Also Array function, Dim statement, Function statement, Option Base statement, Private statement, Public statement, ReDim statement, Sub statement. Example This example uses the Static statement to retain the value of a variable for as long as module code is running.
' Function definition. Function KeepTotal(Number) ' Only the variable Accumulate preserves its value between calls. Static Accumulate Accumulate = Accumulate + Number KeepTotal = Accumulate End Function ' Static function definition. Static Function MyFunction(Arg1, Arg2, Arg3) ' All local variables preserve value between function calls. Accumulate = Arg1 + Arg2 + Arg3 Half = Accumulate / 2 MyFunction = Half End Function

Example (Microsoft Excel) This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Note 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 example.
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.Pmt(loanInt / 1200, loanTerm * 12, loanAmt) MsgBox "Monthly payment is " & Format(payment, "Currency")

Stop Statement
Description Suspends execution. Syntax

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 320 of 1081

Stop Remarks You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code. The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables, unless it is in a compiled executable (.exe) file. See Also End statement. Example This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.
Dim I For I = 1 To 10 Debug.Print I Stop Next I ' Start For...Next loop. ' Print I to Debug window. ' Stop during each iteration.

Str Function
Description Returns a Variant (String) representation of a number. Syntax Str(number) The required number argument is a Long containing any valid numeric expression. Remarks When numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, the returned string contains a leading space and the plus sign is implied. Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. Unlike Str, the Format function doesn't include a leading space for the sign of number. Note The Str function recognizes only the period (.) as a valid decimal separator. When different decimal separators may be used (for example, in international applications), use CStr to convert a number to a string.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 321 of 1081

See Also Format function, Val function. Example This example uses the Str function to return a string representation of a number. When a number is converted to a string, a leading space is always reserved for its sign.
Dim MyString MyString = Str(459) MyString = Str(-459.65) MyString = Str(459.001) ' Returns " 459". ' Returns "-459.65". ' Returns " 459.001".

StrComp Function
Description Returns a Variant (Integer) indicating the result of a string comparison. Syntax StrComp(string1, string2[, compare]) The StrComp function syntax has these named arguments: Part Description

string1

Required. Any valid string expression.

string2

Required. Any valid string expression.

compare

Optional. Specifies the type of string comparison. The compare argument can be omitted, or it can be 0, 1 or 2. Specify 0 (default) to perform a binary comparison. Specify 1 to perform a textual comparison. For Microsoft Access only, specify 2 to perform a comparison based on information contained in your database. If compare is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison.

Return Values

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 322 of 1081

The StrComp function has the following return values: If StrComp returns

string1 is less than string2

string1 is equal to string2

string1 is greater than string2

string1 or string2 is Null

Null

See Also InStr function, Option Compare statement. Example This example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.
Dim MyStr1, MyStr2, MyComp MyStr1 = "ABCD": MyStr2 = "abcd" MyComp = StrComp(MyStr1, MyStr2, 1) MyComp = StrComp(MyStr1, MyStr2, 0) MyComp = StrComp(MyStr2, MyStr1) ' Define variables. ' Returns 0. ' Returns -1. ' Returns 1.

StrConv Function
Description Returns a Variant (String) converted as specified. Syntax StrConv(string, conversion) The StrConv function syntax has these named arguments:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 323 of 1081

Part

Description

string

Required. String expression to be converted.

conversion

Required; Integer. The sum of values specifying the type of conversion to perform.

Settings The conversion argument settings are: Constant Value Description

vbUpperCase

Converts the string to uppercase characters.

vbLowerCase

Converts the string to lowercase characters.

vbProperCase

Converts the first letter of every word in string to uppercase.

vbWide*

4*

Converts narrow (single-byte) characters in string to wide (double-byte) characters.

vbNarrow*

8*

Converts wide (double-byte) characters in string to narrow (single-byte) characters.

vbKatakana**

16**

Converts Hiragana characters in string to Katakana characters.

vbHiragana**

32**

Converts Katakana characters in string to Hiragana characters.

vbUnicode

64

Converts the string to Unicode using the default code page of the system.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 324 of 1081

vbFromUnicode

128

Converts the string from Unicode to the default code page of the system.

* Applies to Far East locales. ** Applies to Japan only. Note These constants are specified by Visual Basic for Applications. As a result, they may be used anywhere in your code in place of the actual values. Most can be combined, for example, vbUpperCase + vbWide, except when they are mutually exclusive, for example, vbUnicode + vbFromUnicode. The constants vbWide, vbNarrow, vbKatakana, and vbHiragana cause run-time errors when used in locales where they do not apply. The following are valid word separators for proper casing: Null (Chr$(0)), horizontal tab (Chr$(9)), linefeed (Chr$(10)), vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (SBCS) (Chr$(32)). The actual value for a space varies by country for DBCS. See Also Chr function, String data type.

String Data Type


Description 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 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 ($). See Also Data type summary, Deftype statements, String function, Variant data type.

String Function

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 325 of 1081

Description Returns a Variant (String) containing a repeating character string of the length specified. Syntax String(number, character) The String function syntax has these named arguments: Part Description

number

Required; Long. Length of the returned string. If number contains Null, Null is returned.

character

Required; Variant. Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks If you specify a number for character greater than 255, String converts the number to a valid character code using the formula: character Mod 256 See Also Mod operator, Space function, String data type. Example This example uses the String function to return repeating character strings of the length specified.
Dim MyString MyString = String(5, "*") MyString = String(5, 42) MyString = String(10, "ABC") ' Returns "*****". ' Returns "*****". ' Returns "AAAAAAAAAA".

Sub Statement
Description

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 326 of 1081

Declares the name, arguments, and code that form the body of a Sub procedure. Syntax [Private | Public] [Static] Sub name [(arglist)] [statements][Exit Sub][statements] End Sub The Sub statement syntax has these parts: Part Description

Public

Optional. Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.

Private

Optional. Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.

Static

Optional. Indicates that the Sub procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Sub, even if they are used in the procedure.

name

Required. Name of the Sub; follows standard variable naming conventions.

arglist

Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.

statements

Optional. Any group of statements to be executed within the Sub procedure.

The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 327 of 1081

Part

Description

Optional

Optional. Keyword indicating that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.

ByVal

Optional. Indicates that the argument is passed by value.

ByRef

Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

ParamArray

Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. ParamArray can't be used with ByVal, ByRef, or Optional.

varname

Required. Name of the variable representing the argument; follows standard variable naming conventions.

type

Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable-length only), Object, Variant. If the parameter is not Optional, a user-defined type, or an object type may also be specified.

defaultvalue

Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 328 of 1081

If not explicitly specified using either Public or Private, Sub procedures are public by default. If Static is not used, the value of local variables is not preserved between calls. Caution Sub procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures. All executable code must be in procedures. You can't define a Sub procedure inside another Sub, Function, or Property procedure. The Exit Sub keywords cause an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure. Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression. You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures. Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure. Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. You can use an Option Explicit statement to force explicit declaration of variables. Note You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.

See Also Call statement, Dim statement, Function statement, Option Explicit statement, Property Get statement, Property Let statement, Property Set statement. Specifics (Microsoft Access) In Microsoft Access, a public Sub procedure in a standard module is available to all other procedures in the current database and in referencing Microsoft Access databases. However, it is not available to any other applications. If you declare a Sub procedure as private in any module, that procedure is available only to other procedures within the same module. If a Sub procedure is declared as public within a private module, such as a class module, then the procedure is available to all other procedures in that database, but is not available to other

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 329 of 1081

Microsoft Access databases. When you create an event procedure for a form or report, Microsoft Access automatically inserts a code stub for a Sub procedure and precedes it with the Private keyword. For example, create a command button on a new form, set its OnClick property to [Event Procedure], and click the Build button to view the form's module. Microsoft Access inserts the following code for you in the module.
Private Sub Command0_Click End Sub

You can then enter the code that you want to execute when that button's Click event occurs. Example This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.
' Sub procedure definition. ' Sub procedure with two arguments. Sub SubComputeArea(Length, TheWidth) Dim Area As Double If Length = 0 Or TheWidth = 0 Then ' If either argument = 0. Exit Sub End If Area = Length * TheWidth Debug.Print Area End Sub

' Declare local variable. ' Exit Sub immediately. ' Calculate area of rectangle. ' Print Area to Debug window.

Switch Function
Description Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True. Syntax Switch(expr-1, value-1[, expr-2, value-2 [, expr-n, value-n]]) The Switch function syntax has these parts: Part Description

expr

Required. Variant expression you want to evaluate.

value

Required. Value or expression to be returned if the corresponding expression is True.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 330 of 1081

Remarks The Switch function argument list consists of pairs of expressions and values. The expressions are evaluated from left to right, and the value associated with the first expression to evaluate to True is returned. If the parts aren't properly paired, a run-time error occurs. For example, if expr-1 is True, Switch returns value-1. If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on. Switch returns a Null value if: None of the expressions is True. The first True expression has a corresponding value that is Null. Switch evaluates all of the expressions, even though it returns only one of them. For this reason, you should watch for undesirable side effects. For example, if the evaluation of any expression results in a division by zero error, an error occurs. See Also Choose function, IIf function, Select Case statement. Specifics (Microsoft Access) You can also use the Switch function in a calculated control on a Microsoft Access form or report. For example, you can use the Switch function to set the value of a control based on the value of another field. Set the ControlSource property of the control to an expression containing the Switch function. In the following example, the Switch function returns a string that is the name of a shipper based on the value of the Freight field. If the value of the Freight field is less than $25, the Switch function returns "Speedy"; if it is greater than or equal to $25 but less than or equal to $50, the Switch function returns "United"; if it is greater than $50, the Switch function returns "Federal".
=Switch([Freight] < 25, "Speedy", ([Freight] >= 25 and [Freight] <= 50), _ "United", [Freight] > 50, "Federal")

Note In Visual Basic code, you may want to use the more full-featured Select Case statement to return a value from a set of several choices. Example This example uses the Switch function to return the name of a language that matches the name of a city.
Function MatchUp (CityName As String) Matchup = Switch(CityName = "London", "English", CityName _ = "Rome", "Italian", CityName = "Paris", "French") End Function

Example (Microsoft Access) The following example uses the Switch function to determine the appropriate language for a specified city based on the values of the ShipCountry and ShipCity fields in an Orders table. You

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 331 of 1081

can enter the following expression in a calculated control on a form or report. The expression is shown on multiple lines for clarity; you can also enter it on a single line.
=Switch([ShipCity] = "Madrid", "Spanish", _ [ShipCity] = "Berlin", "German", _ [ShipCity] = "Torino", "Italian", _ [ShipCountry] = "France", "French", _ True, "English")

If the city is Madrid, the Switch function returns "Spanish"; if it is Berlin, it returns "German"; and so on. If the city is not one of those listed, but the country is France, it returns "French". If the city in question is not in the list, the Switch function returns "English".

SYD Function
Description Returns a Double specifying the sum-of-years' digits depreciation of an asset for a specified period. Syntax SYD(cost, salvage, life, period) The SYD function has these named arguments: Part Description

cost

Required. Double specifying initial cost of the asset.

salvage

Required. Double specifying value of the asset at the end of its useful life.

life

Required. Double specifying length of the useful life of the asset.

period

Required. Double specifying period for which asset depreciation is calculated.

Remarks The life and period arguments must be expressed in the same units. For example, if life is given in months, period must also be given in months. All arguments must be positive numbers. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 332 of 1081

DDB function, FV function, IPmt function, IRR function, MIRR function, NPer function, NPV function, Pmt function, PPmt function, PV function, Rate function, SLN function. Example This example uses the SYD function to return the depreciation of an asset for a specified period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime). The period in years for which the depreciation is calculated is PDepr.
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, PDepr Const YEARMONTHS = 12 ' Number of months in a year. Fmt = "###,##0.00" ' Define money format. InitCost = InputBox("What's the initial cost of the asset?") SalvageVal = InputBox("What's the asset's value at the end of its life?") MonthLife = InputBox("What's the asset's useful life in months?") Do While MonthLife < YEARMONTHS ' Ensure period is >= 1 year. MsgBox "Asset life must be a year or more." MonthLife = InputBox("What's the asset's useful life in months?") Loop LifeTime = MonthLife / YEARMONTHS ' Convert months to years. If LifeTime <> Int(MonthLife / YEARMONTHS) Then LifeTime = Int(LifeTime + 1) ' Round up to nearest year. End If DepYear = CInt(InputBox("For which year do you want depreciation?")) Do While DepYear < 1 Or DepYear > LifeTime MsgBox "You must enter at least 1 but not more than " & LifeTime DepYear = CInt(InputBox("For what year do you want depreciation?")) Loop PDepr = SYD(InitCost, SalvageVal, LifeTime, DepYear) MsgBox "The depreciation for year " & DepYear & " is " _ & Format(PDepr, Fmt) & "."

Tab Function
Description Used with the Print # statement or the Print method to position output. Syntax Tab[(n)] The optional n argument is the column number moved to before displaying or printing the next expression in a list. If omitted, Tab moves the insertion point to the beginning of the next print zone. This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator. Remarks If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line. If n is less than 1, Tab moves the print position to column 1. If n is greater than the output line width, Tab calculates the next print position using the formula: n Mod width For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 333 of 1081

remainder of 90/80). If n is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line. The leftmost print position on an output line is always 1. When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement. Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns. The width of each column is an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter i occupies less than one fixed-width column. See Also Mod operator, Print # statement, Print method, Space function, Spc function, Width # statement. Example This example uses the Tab function to position output in a file and in the Debug window.
' The Tab function can be used with the Print # statement. Open "TESTFILE" For Output As #1 ' Open file for output. ' The second word prints at column 20. Print #1, "Hello"; Tab(20); "World." ' If the argument is omitted, cursor is moved to the next print zone. Print #1, "Hello"; Tab; "World" Close #1 ' Close file.

The Tab function can also be used with the Print method. The following statement prints text starting at column 10.
Debug.Print Tab(10); "10 columns from start."

Tan Function
Description Returns a Double specifying the tangent of an angle. Syntax Tan(number) The required number argument is a Double or any valid numeric expression that expresses an angle in radians. Remarks

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 334 of 1081

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. See Also Atn function, Cos function, Sin function. Example This example uses the Tan function to return the tangent of an angle.
Dim MyAngle, MyCotangent MyAngle = 1.3 MyCotangent = 1 / Tan(MyAngle) ' Define angle in radians. ' Calculate cotangent.

Terminate Event
Applies To UserForm object. Description Occurs when all references to an instance of an object are removed from memory by setting all variables that refer to the object to Nothing or when the last reference to the object goes out of scope. Syntax Private Sub object_Terminate( ) The object placeholder represents an object expression that evaluates to an object in the Applies To list. Remarks The Terminate event occurs after the object is unloaded. The Terminate event isn't triggered if the instances of the UserForm or class are removed from memory because the application terminated abnormally. For example, if your application invokes the End statement before removing all existing instances of the class or UserForm from memory, the Terminate event isn't triggered for that class or UserForm. Example The following event procedures cause a UserForm to beep for a few seconds after the user clicks the client area to dismiss the form.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 335 of 1081

Private Sub UserForm_Activate() UserForm1.Caption = "Click me to kill me!" End Sub Private Sub UserForm_Click() Unload Me End Sub Private Sub UserForm_Terminate() Dim Count As Integer For Count = 1 To 100 Beep Next End Sub

Time Function
Description Returns a Variant (Date) indicating the current system time. Syntax Time Remarks To set the system time, use the Time statement. See Also Date function, Date statement, Time statement, Timer function. Specifics (Microsoft Access) You can insert the current time on a form or report by clicking Date And Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to an expression containing the Time function. This expression will vary according to the format you have chosen to display the time. This command is available only in form Design view and report Design view. You can also use the Time function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than in a Visual Basic module, as in the expression Time(). Example This example uses the Time function to return the current system time.
Dim MyTime MyTime = Time ' Return current system time.

Example (Microsoft Access)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 336 of 1081

You can use the Time function in a calculated control to return the current system time. For example, you can create a text box and set its ControlSource property to the following expression.
=Time()

Time Statement
Description Sets the system time. Syntax Time = time The required time argument is any numeric expression, string expression, or any combination, that can represent a time. Remarks If time is a string, Time attempts to convert it to a time using the time separators you specified for your system. If it can't be converted to a valid time, an error occurs. See Also Date function, Date statement, Time function. Example This example uses the Time statement to set the computer system time to a user-defined time.
Dim MyTime MyTime = #4:35:17 PM# Time = MyTime ' Assign a time. ' Set system time to MyTime.

Timer Function
Description Returns a Single representing the number of seconds elapsed since midnight. Syntax Timer See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 337 of 1081

Randomize statement, Time function. Example This example uses the Timer function to pause the application. The example also uses DoEvents to yield to other processes during the pause.
Dim PauseTime, Start, Finish, TotalTime If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then PauseTime = 5 ' Set duration. Start = Timer ' Set start time. Do While Timer < Start + PauseTime DoEvents ' Yield to other processes. Loop Finish = Timer ' Set end time. TotalTime = Finish - Start ' Calculate total time. MsgBox "Paused for " & TotalTime & " seconds" Else End End If

Example (Microsoft Access) You can use the Timer function to time operations and events in your Microsoft Access application by placing the Timer function immediately before and after the operation in your code that you wish to time. The following example uses the name of a query as its argument, then calculates how long it takes the query to run.
Sub QueryTimer (strQueryName As String) Dim sngStart As Single, sngEnd As Single Dim sngElapsed As Single sngStart = Timer ' Get start time. DoCmd.OpenQuery strQueryName, acNormal ' Run query. sngEnd = Timer ' Get end time. sngElapsed = Format(sngEnd - sngStart, "Fixed") ' Elapsed time. MsgBox ("The query " & strQueryName & " took " & sngElapsed _ & " seconds to run.") End Sub

TimeSerial Function
Description Returns a Variant (Date) containing the time for a specific hour, minute, and second. Syntax TimeSerial(hour, minute, second) The TimeSerial function syntax has these named arguments:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 338 of 1081

Part

Description

hour

Required; Variant (Integer). Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

minute

Required; Variant (Integer). Any numeric expression.

second

Required; Variant (Integer). Any numeric expression.

Remarks To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normal range for the unit; that is, 0 23 for hours and 0 59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time. The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (15) six hours before noon (12 6), or 5:45:00 A.M.
TimeSerial(12 - 6, -15, 0)

When any argument exceeds the normal range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. If any single argument is outside the range 32,768 to 32,767, an error occurs. If the time specified by the three arguments causes the date to fall outside the acceptable range of dates, an error occurs. See Also DateSerial function, DateValue function, Hour function, Minute function, Now function, Second function, TimeValue function. Example This example uses the TimeSerial function to return a time for the specified hour, minute, and second.
Dim MyTime MyTime = TimeSerial(16, 35, 17) ' MyTime contains serial ' representation of 4:35:17 PM.

TimeValue Function
file://C:\temporary\~hhE561.htm 3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 339 of 1081

Description Returns a Variant (Date) containing the time. Syntax TimeValue(time) The required time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains Null, Null is returned. Remarks You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments. If the time argument contains date information, TimeValue doesn't return it. However, if time includes invalid date information, an error occurs. See Also DateSerial function, DateValue function, Hour function, Minute function, Now function, Second function, TimeSerial function. Example This example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant or Date variable, for example, MyTime = #4:35:17 PM#.
Dim MyTime MyTime = TimeValue("4:35:17 PM") ' Return a time.

Trim Function
See LTrim, RTrim, and Trim Functions.

Type Conversion Functions


Description Each function coerces an expression to a specific data type. Syntax CBool(expression)

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 340 of 1081

CByte(expression) CCur(expression) CDate(expression) CDbl(expression) CDec(expression) CInt(expression) CLng(expression) CSng(expression) CVar(expression) CStr(expression) The required expression argument is any string expression or numeric expression. Return Types The function name determines the return type as shown in the following: Function Return type Range for expression argument

CBool

Boolean

Any valid string or numeric expression.

CByte

Byte

0 to 255.

CCur

Currency

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

CDate

Date

Any valid date expression.

CDbl

Double

1.79769313486232E308 to 4.94065645841247E324 for negative values; 4.94065645841247E324 to 1.79769313486232E308 for positive values.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 341 of 1081

CDec

Decimal

+/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers with no decimal places. For numbers with 28 decimal places, the range is +/-7.9228162514264337593543950335. The smallest possible non-zero number is 0.0000000000000000000000000001.

(continued) Function Return type Range for expression argument

CInt

Integer

32,768 to 32,767; fractions are rounded.

CLng

Long

2,147,483,648 to 2,147,483,647; fractions are rounded.

CSng

Single

3.402823E38 to 1.401298E 45 for negative values; 1.401298E45 to 3.402823E38 for positive values.

CVar

Variant

Same range as Double for numerics. Same range as String for non-numerics.

CStr

String

Returns for CStr depend on the expression argument.

Remarks If the expression passed to the function is outside the range of the data type being converted to, an error occurs. In general, you can document your code using the data-type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where singleprecision, double-precision, or integer arithmetic normally would occur. You should use the data-type conversion functions instead of Val to provide internationally aware conversions from one data type to another. For example, when you use CCur, different decimal separators, different thousand separators, and various currency options are properly recognized depending on the locale setting of your computer.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 342 of 1081

When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. CInt and CLng differ from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as is passed in. Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight. CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string. A CVDate function is also provided for compatibility with previous versions of Visual Basic. The syntax of the CVDate function is identical to the CDate function, however, CVDate returns a Variant whose subtype is Date instead of an actual Date type. Since there is now an intrinsic Date type, there is no further need for CVDate. The same effect can be achieved by converting an expression to a Date, and then assigning it to a Variant. This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes. Note The CDec function does not return a discrete data type; instead, it always returns a Variant whose value has been converted to a Decimal subtype. Example This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.
Dim A, B, Check A = 5: B = 5 Check = CBool(A = B) A = 0 Check = CBool(A) ' Initialize variables. ' Check contains True. ' Define variable. ' Check contains False.

Example This example uses the CByte function to convert an expression to a Byte.
Dim MyDouble, MyByte MyDouble = 125.5678 MyByte = CByte(MyDouble) ' MyDouble is a Double. ' MyByte contains 126.

Example This example uses the CCur function to convert an expression to a Currency.
Dim MyDouble, MyCurr MyDouble = 543.214588 MyCurr = CCur(MyDouble * 2) ' MyDouble is a Double. ' Convert result of MyDouble * 2 ' (1086.429176) to a ' Currency (1086.4292).

Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 343 of 1081

This example uses the CDate function to convert a string to a Date. In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #2/12/1969# and #4:45:23 PM#, instead.
Dim MyDate, MyShortDate, MyTime, MyShortTime MyDate = "February 12, 1969" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" MyShortTime = CDate(MyTime) ' Define time. ' Convert to Date data type.

Example This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble MyCurr = CCur(234.456784) MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' MyCurr is a Currency. ' Convert result to a Double.

Example This example uses the CInt function to convert a value to an Integer.
Dim MyDouble, MyInt MyDouble = 2345.5678 MyInt = CInt(MyDouble) ' MyDouble is a Double. ' MyInt contains 2346.

Example This example uses the CLng function to convert a value to a Long.
Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 MyLong1 = CLng(MyVal1) MyLong2 = CLng(MyVal2) ' MyVal1, MyVal2 are Doubles. ' MyLong1 contains 25427. ' MyLong2 contains 25428.

Example This example uses the CSng function to convert a value to a Single.
Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.

Example This example uses the CStr function to convert a numeric value to a String.
Dim MyDouble, MyString MyDouble = 437.324 MyString = CStr(MyDouble) ' MyDouble is a Double. ' MyString contains "437.324".

Example This example uses the CVar function to convert an expression to a Variant.
Dim MyInt, MyVar MyInt = 4534 ' MyInt is an Integer.

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 344 of 1081

MyVar = CVar(MyInt & "000")

' MyVar contains the string ' 4534000.

Type Statement
Description Used at module level to define a user-defined data type containing one or more elements. Syntax [Private | Public] Type varnameelementname [([subscripts])] As type[elementname [([subscripts])] As type]. . . End Type The Type statement syntax has these parts: Part Description

Public

Optional. Used to declare user-defined types that are available to all procedures in all modules in all projects.

Private

Optional. Used to declare user-defined types that are available only within the module where the declaration is made.

varname

Required. Name of the user-defined type; follows standard variable naming conventions.

elementname

Required. Name of an element of the user-defined type. Element names also follow standard variable naming conventions, except that keywords can be used.

subscripts

Optional. Dimensions of an array element. Use only parentheses when declaring an array whose size can change. The subscripts argument uses the following syntax:

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 345 of 1081

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

type

Required. Data type of the element; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String(for variable-length strings), String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks The Type statement can be used only at module level. Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration. Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type. In standard modules, user-defined types are public by default. This visibility can be changed using the Private keyword. In class modules, however, user-defined types can only be private and the visibility can't be changed using the Public keyword. Line numbers and line labels aren't allowed in Type...End Type blocks. User-defined types are often used with data records, which frequently consist of a number of related elements of different data types. The following example shows the use of fixed-size arrays in a user-defined type:
Type StateData CityCode (1 To 100) As Integer County As String * 30 End Type Dim Washington(1 To 100) As StateData ' Declare a static array.

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData. When you declare a fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables. The setting of the Option Base statement determines the lower bound for arrays within userdefined types. See Also

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 346 of 1081

Data type summary, Dim statement, Option Base statement, Private statement, Public statement, ReDim statement, Static statement. Specifics (Microsoft Access) In Microsoft Access, user-defined types are public by default. You cannot define a public userdefined type within a class module. To declare a user-defined type within a class module, precede the Type statement with the Private keyword. If you fail to include the Private keyword, Microsoft Access generates a compile-time error. Example This example uses the Type statement to define a user-defined data type. The Type statement is used at the module level only. If it appears in a class module, a Type statement must be preceded by the keyword Private.
Type EmployeeRecord ID As Integer Name As String * 20 Address As String * 30 Phone As Long HireDate As Date End Type Sub CreateRecord() Dim MyRecord As EmployeeRecord ' Create user-defined type. ' Define elements of data type.

' Declare variable.

' Assignment to EmployeeRecord variable must occur in a procedure. MyRecord.ID = 12003 ' Assign a value to an element. End Sub

TypeName Function
Description Returns a String that provides information about a variable. Syntax TypeName(varname) The required varname argument is a Variant containing any variable except a variable of a userdefined type. Remarks The string returned by TypeName can be any one of the following: String returned Variable

object type

An object whose type is objecttype

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 347 of 1081

Byte

Byte value

Integer

Integer

Long

Long integer

Single

Single-precision floating-point number

Double

Double-precision floating-point number

Currency

Currency value

Decimal

Decimal value

Date

Date value

String

String

Boolean

Boolean value

Error

An error value

Empty

Uninitialized

Null

No valid data

Object

An object

Unknown

An object whose type is unknown

Nothing

Object variable that doesn't refer to an object

If varname is an array, the returned string can be any one of the possible returned strings (or

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 348 of 1081

Variant) with empty parentheses appended. For example, if varname is an array of integers, TypeName returns "Integer()". See Also Data type summary, IsArray function, IsDate function, IsEmpty function, IsError function, IsMissing function, IsNull function, IsNumeric function, IsObject function, Variant data type, VarType function. Example This example uses the TypeName function to return information about a variable.
' Declare variables. Dim NullVar, MyType, StrVar As String, IntVar As Integer, CurVar As Currency Dim ArrayVar (1 To 5) As Integer NullVar = Null ' Assign Null value. MyType = TypeName(StrVar) ' Returns "String". MyType = TypeName(IntVar) ' Returns "Integer". MyType = TypeName(CurVar) ' Returns "Currency". MyType = TypeName(NullVar) ' Returns "Null". MyType = TypeName(ArrayVar) ' Returns "Integer()".

Example (Microsoft Access) The following example creates several object variables and passes them to the TypeName function.
Sub ObjectTypes() Dim dbs As Database, tdf As TableDef Dim fld As Field ' Get current database. Set dbs = CurrentDb ' Return TableDef object pointing to Orders table. Set tdf = dbs.TableDefs("Orders") ' Return Field object pointing to OrderDate field. Set fld = tdf.Fields("OrderDate") ' Print value returned by TypeName for each object. Debug.Print TypeName(dbs) Debug.Print TypeName(tdf) Debug.Print TypeName(fld) End Sub

Example (Microsoft Excel) This example displays the Visual Basic object type of the selection. You can run this example with cells selected, with a single oval selected, or with several different graphic objects selected.
Worksheets("Sheet1").Activate MsgBox "The selection object type is " & TypeName(Selection)

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

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 349 of 1081

Syntax UBound(arrayname[, dimension]) The UBound function syntax has these parts: Part Description

arrayname

Required, Name of the array variable; follows standard variable naming conventions.

dimension

Optional; Variant (Long). Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension. UBound returns the following values for an array with these dimensions:
Dim A(1 To 100, 0 To 3, -3 To 4)

Statement

Return Value

UBound(A, 1)

100

UBound(A, 2)

UBound(A, 3)

See Also Dim statement, LBound function, Option Base statement, Public statement, ReDim statement. Example

file://C:\temporary\~hhE561.htm

3/20/2000

Microsoft Visual Basic for Applications Language Reference

Page 350 of 1081

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.
Dim Upper Dim MyArray(1 To 10, 5 To 15, 10 To 20) Dim AnyArray(10) Upper = UBound(MyArray, 1) Upper = UBound(MyArray, 3) Upper = UBound(AnyArray) ' Declare array variables. ' Returns 10. ' Returns 20. ' Returns 10.

Example (Microsoft Excel) This example writes the elements of the first custom list in column one on Sheet1.
listArray = Application.GetCustomListContents(1) For i = LBound(listArray, 1) To UBound(listArray, 1) Worksheets("sheet1").Cells(i, 1).Value = listArray(i) Next i

This example assumes that you used an external data source to create a PivotTable on Sheet1. The example inserts the SQL connection string and query string into a new worksheet.
Set newSheet = ActiveWorkbook.Worksheets.Add sdArray = Worksheets("S