Alphabetical Keyword List

The following list contains keywords intrinsic to Visual Basic, Visual Basic for Applications, and Visual Basic, Scripting Edition, that are not directly related to forms, controls, or objects.

' Comment Operator

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeBegins a source code comment line or line section.
Typical Syntax' comment
See AlsoRem Statement

Use the comment operator ( ' ) as needed within your Visual Basic source code. When adding comments to your source code, always use the single quote comment operator; discontinue use of the Rem statement.

The syntax of Visual Basic allows you to continue any line, including a comment line, with a line continuation character ( _ ). Do not use this method to join adjacent comment lines together.

Incorrect
' ----- It is very important that you read this full _
'       comment so that you can be fully informed.

Correct
' ----- It is very important that you read this full
'       comment so that you can be fully informed.

For full information on the use and style of comments within your source code, see Chapter 3, Commenting and Style.

- Operator (Binary)

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeSubtracts one value from another.
Typical Syntaxexpression1 - expression2
See Also- Operator (Unary), & Operator, * Operator, / Operator, Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment), Mod Operator

Use the subtraction operator ( - ) as needed within your Visual Basic source code. When subtracting date or time values, use the DateAdd function instead of the subtraction operator.

- Operator (Unary)

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates the negative value of an expression.
Typical Syntax- expression
See Also- Operator (Binary), & Operator, * Operator, / Operator, Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment), Mod Operator

Use the negation operator ( - ) as needed within your Visual Basic source code. Visual Basic allows you to use the negation operator before a wide variety of expressions, including numeric literals, variables, or parenthesized expressions. In complex expressions or code, the negation operator may become visibly insignificant, making it difficult to debug a section of code. In such cases, you may wish to discontinue use of the negation operator, and instead multiply the expression by āˆ’1.

#Const Directive

CategoryCompiler Directives
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDefines a conditional compiler constant.
Typical Syntax#Const constname = expression
See Also#If...Then...#Else Directive, Const Statement

Use the #Const directive as needed within the Declarations section of your Visual Basic source code. While Visual Basic allows you to define a compiler constant anywhere within a source code file, restrict the use of the #Const directive to the Declarations section. You can also declare compiler constants through the Project Properties form within the Visual Basic development environment. Additionally, you can define these constants with command-line arguments when compiling an application through the Visual Basic shell command.

Use constant names that include only upper-case letters, digits, and underscore characters. For more information about using compiler directives, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

#If...Then...#Else Directive

CategoryCompiler Directives
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIncludes or excludes source code based on compiler-level conditions.
Typical Syntax#If expression Then [statements]
 [#ElseIf expression-n Then [statements]]
 [#Else [statements]]
 #End If
See Also#Const Directive, If...Then...Else Statement

Use the #If...Then...#Else directive as needed within your Visual Basic source code. Even if the #If condition is met, all of the #ElseIf and #Else expressions are evaluated. Therefore, any compiler constants used in those expressions must be defined at compile time.

For more information about using compiler directives, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

& Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConcatenates two expressions.
Typical Syntaxexpression1 & expression2
See Also- Operator (Binary), - Operator (Unary), * Operator, / Operator, Operator, ^ Operator, + Operator, = Operator (Assignment), Mod Operator

Use the concatenation operator ( & ) as needed within your Visual Basic source code. Although Visual Basic permits it, do not use the addition operator ( + ) to concatenate two string expressions together. Use the concatenation operator instead to remove any ambiguity in the functionality of the addition operator.

Always leave at least one character of whitespace between the concatenation operator and the expression that precedes it or follows it. If you immediately follow a Long variable or a numeric literal with the & character without introducing whitespace between them, the & character will act as a type declaration character for the Long data type. Placing the & character immediately before an expression tells Visual Basic to treat the expression as a non-decimal value, such as a hexadecimal or octal value.

* Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeMultiplies two values together.
Typical Syntaxexpression1 * expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, / Operator, Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment), Mod Operator

Use the multiplication operator ( * ) as needed within your Visual Basic source code.

/ Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDivides one number into another, and returns a floating point value.
Typical Syntaxexpression1 / expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, * Operator, Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment), Mod Operator

Use the division operator ( / ) as needed within your Visual Basic source code. The second expression cannot be 0 (zero). If the second expression is supplied by the user, or if you think that the second expression may be zero, include appropriate code to test the second expression, and take corrective action when needed.

Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDivides one number into another, and returns only the integer portion of the result.
Typical Syntaxexpression1 expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, * Operator, / Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment), Fix Function, Int Function, Mod Operator, Round Function

Use the integer division operator ( ) as needed within your Visual Basic source code. The second expression cannot be 0 (zero). If the second expression is supplied by the user, or if you think that the second expression may be zero, include appropriate code to test the second expression, and take corrective action when needed.

The integer division operator rounds the expressions before the division takes place. After the division operation, any fractional value is truncated, not rounded. If you need to use a different system of rounding or fractional truncation, consider using the division operator combined with the Fix function, the Int function, or the Round function.

^ Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeRaises one value to the power of another value.
Typical Syntaxexpression1 ^ expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, * Operator, / Operator, Operator, + Operator (Assignment), = Operator (Assignment), Mod Operator

Use the exponentiation operator ( ^ ) as needed within your Visual Basic source code.

+ Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeAdds one value to another.
Typical Syntaxexpression1 + expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, * Operator, / Operator, Operator, ^ Operator, = Operator (Assignment), Mod Operator

Use the addition operator ( + ) as needed within your Visual Basic source code. Although Visual Basic permits it, do not use the addition operator to concatenate two string expressions together. Use the concatenation operator ( & ) instead to remove any ambiguity in the functionality of the addition operator. When adding date or time values, use the DateAdd function instead of the addition operator.

Visual Basic does permit the use of the addition operator as a unary prefix to indicate that a value is positive. However, this syntax is redundant. Do not use the addition operator as a unary prefix.

< Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value is less than another value.
Typical Syntaxexpression1 < expression2
See Also<= Operator, <> Operator, = Operator (Comparison), > Operator, >= Operator, Is Operator, Like Operator, Option Compare Statement

Use the less than operator ( < ) as needed within your Visual Basic source code. The use of the Option Compare statement can affect comparisons performed with the less than operator.

<= Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value is less than or equal to another value.
Typical Syntaxexpression1 <= expression2
See Also< Operator, <> Operator, = Operator (Comparison), > Operator, >= Operator, Is Operator, Like Operator, Option Compare Statement

Use the less than or equal to operator ( <= ) as needed within your Visual Basic source code. Visual Basic allows you to reverse the two characters that make up the <= symbol. However, always use this operator in its documented fashion.

Incorrect
If (nFirst =< nSecond) Then

Correct
If (nFirst <= nSecond) Then

The use of the Option Compare statement can affect comparisons performed with the less than or equal to operator.

<> Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value does not equal another value.
Typical Syntaxexpression1 <> expression2
See Also< Operator, <= Operator, = Operator (Comparison), > Operator, >= Operator, Is Operator, Like Operator, Not Operator, Option Compare Statement

Use the not equal operator ( <> ) as needed within your Visual Basic source code. Visual Basic allows you to reverse the two characters that make up the <> symbol. However, always use this operator in its documented fashion.

Incorrect
If (nFirst >< nSecond) Then

Correct
If (nFirst <> nSecond) Then

The use of the Option Compare statement can affect comparisons performed with the not equal operator.

= Operator (Assignment)

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeAssigns an expression to a variable.
Typical Syntaxvariable = expression
See Also= Operator (Comparison), Let Statement, Property Get Statement, Property Let Statement, Property Set Statement, Set Statement

Use the assignment operator ( = ) as needed within your Visual Basic source code. If the user is supplying the expression, or if you think that the expression might fall outside the valid range for the destination variable, include appropriate code to test the expression, and take corrective action when needed.

= Operator (Comparison)

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value equals another value.
Typical Syntaxexpression1 = expression2
See Also< Operator, <= Operator, <> Operator (Comparison), > Operator, >= Operator, Is Operator, Like Operator, Not Operator, Option Compare Statement

Use the equal operator ( = ) as needed within your Visual Basic source code. The use of the Option Compare statement can affect comparisons performed with the equal operator. If the user is supplying one or both of the expressions, or if you think that the expressions might be incompatible in a comparison, include appropriate code to test the expressions, and take corrective action when needed.

When comparing the return value of a function that takes no arguments to another expression, always follow the function name with an empty set of parentheses. This makes the use of the function visually distinct from the use of a variable.

Correct
If (DoWork() = True) Then

Incorrect
If (DoWork = True) Then

> Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value is greater than another value.
Typical Syntaxexpression1 > expression2
See Also< Operator, <= Operator, <> Operator, = Operator (Comparison), >= Operator, Is Operator, Like Operator, Option Compare Statement

Use the greater than operator ( > ) as needed within your Visual Basic source code. The use of the Option Compare statement can affect comparisons performed with the greater than operator.

>= Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if one value is greater than or equal to another value.
Typical Syntaxexpression1 >= expression2
See Also< Operator, <= Operator, <> Operator, = Operator (Comparison), > Operator, Is Operator, Like Operator, Option Compare Statement

Use the greater than or equal to operator ( >= ) as needed within your Visual Basic source code. Visual Basic allows you to reverse the two characters that make up the >= symbol. However, always use this operator in its documented fashion.

Incorrect
If (nFirst => nSecond) Then

Correct
If (nFirst >= nSecond) Then

The use of the Option Compare statement can affect comparisons performed with the greater than or equal to operator.

Abs Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the passed value, converting negative values to positive if needed.
Typical SyntaxAbs(expression)
See AlsoFix Function, Int Function, Round Function, Sgn Function

Use the Abs function as needed within your Visual Basic source code.

AddressOf Operator

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeObtains the address of a Visual Basic procedure for use as a callback function supplied through an API call.
Typical SyntaxAddressOf procedurename
See AlsoDeclare Statement, Function Statement, GetRef Function, Procedure Get Statement, Procedure Let Statement, Procedure Set Statement, Sub Statement

Use the AddressOf operator as needed within your Visual Basic source code. The use of the AddressOf operator assumes a more advanced level of Visual Basic programming. Take great care in declaring the callback function, its arguments, and its return type. When defining your callback function, use either the ByRef or ByVal keyword with each argument.

And Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise conjunction operation.
Typical Syntaxexpression1 And expression2
See AlsoEqv Operator, Imp Operator, Not Operator, Or Operator, Xor Operator.

Use the And operator as needed within your Visual Basic source code. When writing complex statements that involve more than one logical or bitwise operator, use parentheses to indicate the proper precedence and grouping within the calculation.

App Object

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:No, VBScript:No
PurposeObject that supplies information about the application.
Typical SyntaxApp
VariationsGlobal.App Object
See AlsoDebug Object, Global Object, Screen Object

Use the App object as needed within your Visual Basic source code. Do not use the Global.App variation of this object; refer to the App object directly. When using Visual Basic for Applications, there may be an object available that is contextually similar to the Visual Basic App object.

AppActivate Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeActivates an application's window.
Typical SyntaxAppActivate title[, wait]
See AlsoSendKeys Statement, Shell Function

Use the AppActivate statement as needed within your Visual Basic source code. When specifying the application window title to activate, verify that there is no ambiguity between multiple windows with the same name. If an exact title match is not found, the AppActivate statement matches the beginning of a window title with the supplied title. If possible, use the return value from the Shell function as the title argument to the AppActivate statement.

The AppActivate statement accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the AppActivate statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Array Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeBuilds and returns a Variant array.
Typical SyntaxArray(arglist)
See AlsoIsArray Function, Option Base Statement

Use the Array function as needed within your Visual Basic source code. If possible, use standard arrays instead of Variant arrays in your source code. Because Variant arrays are not as self-documenting as true arrays (although, how self-documenting is a true array), describe the purpose and structure of each Variant array in your source code comments. The Option Base statement affects the use of the Array statement.

Asc Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the ANSI character code of a character.
Typical SyntaxAsc(string)
VariationsAscB Function, AscW Function
See AlsoChr Function

Use the Asc function as needed within your Visual Basic source code. If you need to work with the underlying bytes contained within a string, use the AscB function. If you need to work with Unicode characters, use the AscW function. When using the AscW function, verify that your application is running on a platform that supports Unicode.

Atn Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the arctangent of a number.
Typical SyntaxAtn(number)
See AlsoCos Function, Sin Function, Tan Function

Use the Atn function as needed within your Visual Basic source code. This function returns a Double value, and accepts a Double value for its parameter. Double floating point values are subject to minor rounding errors. Take care to check the accuracy of the return values when using the Visual Basic intrinsic math functions.

Beep Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeProduces a "beep" sound.
Typical SyntaxBeep
See AlsoMsgBox Function

Use the Beep statement as needed within your Visual Basic source code. However, an overuse of the statement will irritate your users. Be frugal in the use of the Beep statement.

Be aware that this statement will be useless on some systems as either sound is disabled, or the user is unable to hear the sound. If you need to communicate important conditions to the user, do not use the Beep statement as the primary method. Use visual cues to communicate such conditions.

ByRef Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIdentifies a procedure argument as being passed by reference.
Typical SyntaxByRef argument [ As type]
See AlsoAddressOf Operator, ByVal Keyword, Declare Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Use the ByRef keyword as needed within your Visual Basic source code. By default, all procedure arguments are passed by reference. Use of the ByRef keyword in Visual Basic procedure arguments is optional. However, when including pass-by-reference arguments in a Declare statement, you must use the ByRef keyword. Also, when defining a procedure that will be used as an argument to the AddressOf operator, use the ByRef or ByVal keyword with every argument.

For more information on the use of the ByRef keyword, and the statements in which it appears, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

ByVal Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIdentifies a procedure argument as being passed by value.
Typical SyntaxByVal argument [ As type]
See AlsoByRef Keyword, Declare Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Use the ByVal keyword as needed within your Visual Basic source code. By default, all procedure arguments are passed by reference. Use of the ByVal keyword in Visual Basic procedure arguments is required to have an argument always passed by value. Also, when including pass-by-value arguments in a Declare statement, you must use the ByVal keyword.

For more information on the use of the ByVal keyword, and the statements in which it appears, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

Call Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalls a function or subroutine, either locally or through an API call.
Typical Syntax[Call] name [([argumentlist])]
See AlsoDeclare Statement, Function Statement, Procedure Get Statement, Procedure Let Statement, Procedure Set Statement

The Call keyword is implied every time you call a subroutine within Visual Basic. In general, you should omit the Call keyword in procedure calls. However, there are two exceptions. First, if you need to call a function, but wish to ignore its return value, use the Call keyword.

Call MyFunction(sArg1, nArg2)

The second exception occurs when you call a subroutine that has no parameters, and you wish to include additional statements on the same physical source code line by using the ":" statement separator. The Visual Basic development environment will visibly display such lines as though the subroutine call was a line label. Use the Call keyword to defeat this interpretation.

Call MySubroutine: lblResult.Caption = "Done"

For more information on the use of procedures within Visual Basic, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

CallByName Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalls a procedure indirectly.
Typical SyntaxCallByName(object, procedurename, calltype[, arguments()])
See AlsoDeclare Statement, Function Statement, Procedure Get Statement, Procedure Let Statement, Procedure Set Statement

Use the CallByName function as needed within your Visual Basic source code. However, its use should be restricted to special cases where no other language construct will suffice. When using this statement, include a reasonable defense of your use of the statement in the adjacent source code comments.

The calltype argument to the CallByName function accepts an Integer value, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

The CallByName function accesses Visual Basic features in a non-standard way. Therefore, you must always use proper error handling in any procedure that uses the CallByName function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

CBool Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Boolean data type.
Typical SyntaxCBool(expression)
See AlsoCByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, False Keyword, True Keyword

Use the CBool function as needed within your Visual Basic source code. All non-zero numeric expressions are converted to True, while zero becomes False. All dates and all times other than midnight are True, while a value of midnight without a date is False. The CBool function considers an Empty expression to be False.

CByte Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Byte data type.
Typical SyntaxCByte(expression)
See AlsoCBool Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CByte function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Byte data type, include appropriate code to test the expression, and take corrective action when needed.

CCur Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Currency data type.
Typical SyntaxCCur(expression)
Variations@ Type Declaration Character
See AlsoCBool Function, CByte Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CCur function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Currency data type, include appropriate code to test the expression, and take corrective action when needed.

Never use the CCur function to convert a numeric literal to the Currency data type. Use the @ type declaration character instead.

Incorrect
fcStartAmount = CCur(125.5)

Correct
fcStartAmount = 125.5@

CDate Function

CategoryConversion Functions, Date and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Date data type.
Typical SyntaxCDate(expression)
VariationsCVDate Function
See AlsoCBool Function, CByte Function, CCur Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsDate Function

Use the CDate function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might contain an invalid date or time, include appropriate code to test the expression, and take corrective action when needed. The IsDate function is useful for testing a potential date or time expression.

Visual Basic also includes the CVDate conversion function for compatibility with previous versions of the language. Do not use the CVDate function, as it does not generate a true Date value. Always use the CDate function for date conversions.

CDbl Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Double data type.
Typical SyntaxCDbl(expression)
Variations# Type Declaration Character
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CDbl function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Double data type, include appropriate code to test the expression, and take corrective action when needed.

Never use the CDbl function to convert a numeric literal to the Double data type. Use the # type declaration character instead.

Incorrect
fdOffset = CDbl(15)

Correct
fdOffset = 15#

CDec Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts an expression to the Variant (Decimal) data type.
Typical SyntaxCDec(expression)
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CDec function as needed within your Visual Basic source code. Note that the Decimal data type is not a true data type. It exists only as a subtype to the Variant data type.

If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Decimal data type, include appropriate code to test the expression, and take corrective action when needed.

ChDir Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeChanges the current directory to a new location.
Typical SyntaxChDir path
See AlsoChDrive Statement, CurDir Function, Dir Function, MkDir Function, RmDir Function

Use the ChDir statement as needed within your Visual Basic source code. While the syntax of the ChDir statement permits the drive letter to be absent from the path string, always include the drive letter for clarity.

Incorrect
ChDir "	emp"

Correct
ChDir "c:	emp"

The ChDir statement only works with paths that reside on a local drive or a mapped drive letter. Do not pass a UNC (Universal Naming Convention) pathā€”one that begins with "\" characters ā€”to the ChDir statement. If the user supplies the path name, make sure that the path exists on a valid local drive or mapped drive.

The ChDir statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the ChDir statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

ChDrive Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeChanges the current drive to a new drive.
Typical SyntaxChDrive drive
See AlsoChDir Statement, CurDir Function, Dir Function, MkDir Function, RmDir Function

Use the ChDrive statement as needed within your Visual Basic source code. It is permissible to pass an entire path as an argument to the ChDrive statement; only the first letter of the argument is used by the ChDrive statement.

The ChDrive statement only works with paths that reside on a local drive or a mapped drive letter. Do not pass a UNC (Universal Naming Convention) pathā€”one that begins with "\" characters ā€”to the ChDrive statement. If the user supplies the path name, make sure that the path exists on a valid local drive or mapped drive.

The ChDrive statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the ChDrive statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Choose Function

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns one of a set of values based on an index.
Typical SyntaxChoose(index, choice-1[, choice-2, ...[, choice-n]])
See AlsoIIf Function, Select Case Statement, Switch Function

Use the Choose function as needed within your Visual Basic source code. Always include source code comments that describe the purpose and results of this statement. Always supply an integer value as the index argument. While the Choose function will round the value you supply, it is better to deal with the fractional value yourself.

If you supply a value less than 1, or greater than the number of choice elements, the Choose function returns a Null value. Be sure to check the return value for a legitimate result if there is any chance that an invalid index may be supplied. Although only one element will be returned based on the index, all choice elements are evaluated. Make sure that the choices do not contain any code that will fail on invalid conditions, or that should execute with only certain index values.

Chr Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a character based on an ANSI character code.
Typical SyntaxChr(charcode)
VariationsChr$ Function, ChrB Function, ChrB$ Function, ChrW Function, ChrW$ Function.
See AlsoChr Function

Use the Chr function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Chr(argument)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Chr$(argument)

If you need to work with the underlying bytes contained within a string, use the ChrB function, or the ChrB$ function. If you need to work with Unicode characters, use the ChrW function, or the ChrW$ function. When using the ChrW function or the ChrW$ function, verify that your application is running on a platform that supports Unicode.

Visual Basic contains several intrinsic constants that, if they were not present, would require the use of the Chr function to create those values. For example, the "vbNullChar" constant is equivalent to "Chr(0)." The "vbCrLf" function is equivalent to "Chr(13) & Chr(10)." When available, always use the intrinsic constants instead of building the values with the Chr function.

CInt Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Integer data type.
Typical SyntaxCInt(expression)
Variations% Type Declaration Character
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CLng Function, CSng Function, CStr Function, CVar Function, CVErr Function, Int Function, IsNumeric Function

Use the CInt function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Integer data type, include appropriate code to test the expression, and take corrective action when needed.

Never use the CInt function to convert a non-decimal numeric literal to the Integer data type. While you could use the % type declaration character to coerce the literal to an integer, all numeric literals in Visual Basic that fall within the range of the Integer data type are automatically cast as Integer.

The Int function cannot be used to convert a value to the Integer data type. Use the Int function to truncate the decimal portion of a numeric expression. Use the CInt function to convert values in the Integer range to the Integer data type.

CLng Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Long data type.
Typical SyntaxCLng(expression)
Variations& Type Declaration Character
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CSng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CLng function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outs range for the Long data type, include appropriate code to test the expression, and take corrective action when needed.

Never use the CLng function to convert a numeric literal to the Long data type. Use the & type declaration character instead.

Incorrect
lInitialLimit = CLng(1500)

Correct
lInitialLimit = 1500&

By default, all non-decimal numeric literals that fall outside the range of the Integer data type, but inside the range of the Long data type, are cast as Long.

Close Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCloses the specified open file.
Typical SyntaxClose [#]filenumber
See AlsoOpen Statement, Reset Statement

Use the Close statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Close statement. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.

The syntax of the Close statement allows multiple comma-separated file numbers to be closed at once with a single statement. For increased clarity, only close a single file with each Close statement in your source code.

The Close statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Close statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Command Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the command-line arguments of the application session.
Typical SyntaxCommand
VariationsCommand$ Function
See AlsoApp Object

Use the Command function as needed within your Visual Basic source code. Do not use the Command version of this function in your source code. Instead, use the Command$ function.

Incorrect
sParse = Command

Correct
sParse = Command$

By convention, Windows command-line options begin with a slash ("/") character. You may also, in addition to the Windows standard, wish to support the UNIX standard, beginning options with a hyphen ("-").

Do not assume that the user supplied valid options through the application command line. Always verify the arguments supplied by the user to confirm that they are valid.

Const Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDefines a named constant for local or global use.
Typical Syntax[Public | Private] Const constname [As type] = expression
See Also#Const Directive, Dim Statement, Global Statement, Private Statement, Public Statement, Static Statement

Use the Const statement as needed within the Declarations section of your Visual Basic source code. While Visual Basic allows you to define a constant anywhere within your application, restrict the use of the Const statement to the Declarations section. Never use this statement within a routine. In VBScript, use the Const statement at the beginning of your script page, but not inside any procedure.

Always precede the Const statement with either the Public or Private keyword, attempting to limit the scope where possible. Include only a single constant declaration on each source code line.

Use constant names that include only upper-case letters, digits, and underscore characters. If you have several constants that work together as a set of constants, prefix them with the same first few letters.

Private Const BASE NONE = āˆ’1
Private Const BASE FIRST = 1
Private Const BASE SECOND = 2
Private Const BASE THIRD = 3
Private Const BASE HOME = 4

To make your constant declaration more specific within your source code, use the As clause to define the type of a constant. Type declaration characters can also be used to identify the data type of a constant. For more information about constants and type declaration characters, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

Control Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeProvides a generic object type for controls.
Typical SyntaxDim varname As Control
See AlsoDim Statement, Private Statement, Public Statement

Use the Control keyword as needed within your Visual Basic source code. However, its use should be greatly restricted to only those instances where a more specific solution cannot be clearly or efficiently provided. Supply adequate documentation in the source code comments as to any assumptions about the types of controls that will be assigned to the generic object.

Cos Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the cosine of an angle.
Typical SyntaxCos(number)
See AlsoAtn Function, Sin Function, Tan Function

Use the Cos function as needed within your Visual Basic source code. This function returns a Double value, and accepts a Double value for its parameter. Double floating point values are subject to minor rounding errors. Take care to check the accuracy of the return values when using the Visual Basic intrinsic math functions.

CreateObject Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCreates a reference to an ActiveX object.
Typical SyntaxCreateObject(class[, servername])
See AlsoGetObject Function, Set Statement

Use the CreateObject function as needed within your Visual Basic source code. The CreateObject function accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the CreateObject function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

CSng Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the Single data type.
Typical SyntaxCSng(expression)
Variations! Type Declaration Character
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CStr Function, CVar Function, CVErr Function, IsNumeric Function

Use the CSng function as needed within your Visual Basic source code. If the user is supplying the expression, or if you think the expression might fall outside the valid range for the Single data type, include appropriate code to test the expression, and take corrective action when needed.

Never use the CSng function to convert a numeric literal to the Single data type. Use the ! type declaration character instead.

Incorrect
fdScale = CSng(39.39)

Correct
fdScale = 39.39!

CStr Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts an expression to the String data type.
Typical SyntaxCStr(expression)
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CVar Function, CVErr Function, Str Function, StrConv Function

Use the CStr function as needed within your Visual Basic source code. Avoid the Str function when converting numbers to strings. Use the CStr function instead.

CurDir Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the current directory on the default or specified drive.
Typical SyntaxCurDir[(drive)]
VariationsCurDir$ Function
See AlsoChDir Statement, ChDrive Statement, Dir Function, MkDir Function, RmDir Function

Use the CurDir function as needed within your Visual Basic source code. If you do not require a Variant result, use the CurDir$ function instead of the CurDir function.

vntActiveDir = CurDir
sActiveDir = CurDir$

The CurDir function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the CurDir function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

CVar Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts an expression to the Variant data type.
Typical SyntaxCVar(expression)
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVErr Function, TypeName Function, VarType Function

Use the CVar function as needed within your Visual Basic source code.

CVErr Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts an expression to the Variant (Error) data type.
Typical SyntaxCVErr(expression)
See AlsoCBool Function, CByte Function, CCur Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, CStr Function, CVar Function, IsError Function

Use the CVErr function as needed within your Visual Basic source code. Note that the Error data type is not a true data type. It exists only as a subtype to the Variant data type.

Date Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the current system date.
Typical SyntaxDate
VariationsDate$ Function
See AlsoDate Statement, Now Function, Time Function, Time Statement

Use the Date function as needed within your Visual Basic source code. A string version of this function, Date$, returns the same information as the standard Date function, but as a true String value. (The Date$ function is not available in VBScript.) In general, you should use the Date version of this function. If you need a date stored or displayed as a string, use the Format function or the FormatDateTime function to properly format the date before use.

Date Statement

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSets the current system date.
Typical SyntaxDate = date
See AlsoDate Function, Now Function, Time Function, Time Statement

Use the Date statement as needed within your Visual Basic source code. However, you must make it clear to the user, either in the documentation or through application notification, that you will be modifying the system clock. On some secure Windows systems, you may be restricted from modifying the system clock.

DateAdd Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a new date value based on an adjustment of another date.
Typical SyntaxDateAdd(interval, number, date)
See AlsoCDate Function, DateSerial Function

Use the DateAdd function as needed within your Visual Basic source code. Although Visual Basic permits it, do not use standard math operators to modify a date value. For example, Visual Basic allows you to add a day to an existing date using the following syntax:

dtTomorrow = Date + 1

Always use the DateAdd function to perform such date calculations.

dtTomorrow = DateAdd("d", 1, Date)

DateDiff Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a specified time interval between two dates or times.
Typical SyntaxDateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])
See AlsoDatePart Function, Day Function, Hour Function, Minute Function, Month Function, Second Function, Year Function

Use the DateDiff function as needed within your Visual Basic source code. Do not use standard arithmetic operators to calculate the difference between two date values. Use the DateDiff function instead.

The firstdayofweek and firstweekofyear arguments to the DateDiff function accept Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

DatePart Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating a portion of a given date or time.
Typical SyntaxDatePart(interval, date[, firstdayofweek[, firstweekofyear]])
See AlsoDateDiff Function, Day Function, Hour Function, Minute Function, Month Function, Second Function, Weekday Function, Year Function

Use the DatePart function to return the quarter, day of year, or week of year for a given date. The DatePart function allows other date components to be retrieved. However, those values should be retrieved using their respective functions as listed in Table 10.1.

Table 10.1. Date Component Functions
To ReturnUse the Function
DayDay(date)
HourHour(date)
MinuteMinute(date)
MonthMonth(date)
SecondSecond(date)
WeekdayWeekday(date[,firstdayofweek])
YearYear(date)

The firstdayofweek and firstweekofyear arguments to the DatePart function accept Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

If you are using either Visual Basic or Visual Basic for Applications, and you will be using the value returned from this function as a string (for example, to concatenate the date component onto an existing string), consider using the Format$ function instead.

sInfo = "This is quarter " & Format$(Date, "q")

DateSerial Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a date based on individual year, month, and day values.
Typical SyntaxDateSerial(year, month, day)
See AlsoDateAdd Function, DatePart Function, Day Function, Month Function, TimeSerial Function, Year Function

Use the DateSerial function as needed within your Visual Basic source code. Be aware that if you supply a month or day value that is too large for a valid date, the DateSerial function will increment the value appropriately to compensate for the extra months or days.

dtAction = DateSerial(1999, 12, 31)   ' --> 12/31/1999
dtAction = DateSerial(1999, 12, 32)   ' --> 1/1/2000

You can also supply negative values for the year, month, or day, and the resulting date will decrement as needed. If you supply values that are either negative or too large for a date element, provide a suitable explanation in the source code comments.

DateValue Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts a date expression to a Variant (Date) value.
Typical SyntaxDateValue(date)
See AlsoCDate Function, Date Function, DateSerial Function, Time Function

To convert a date, time, or date/time expression to a Variant (Date) or true Date value, use the CDate function. Avoid the DateValue function for general date conversions. However, if you have an expression that contains both a date and a time, and you wish to retrieve only the date portion of the expression, use the DateValue function. Passing a date and time expression to the CDate function will retain both the date and time portions of the expression. The DateValue function discards the time portion of the original expression. If you are using the DateValue function to remove the time portion of a date/time expression, make it clear in your source code comments that the time portion will be lost.

If you supply a date that contains only digits and valid date separators, ambiguity may occur. For example, the date "12/10/1999" can be interpreted as December 10, 1999, or October 12, 1999, depending on the regional settings of the local system. To interpret such a value, Visual Basic uses the order specified by the Short Date format as set in the Control Panel of the local system. If you will be storing string date expressions in an ambiguous format, or if the user will be permitted to enter values in an ambiguous format, make it clear in both the technical documentation and the user's printed and on-line documentation how you will handle such ambiguous dates in your application.

Day Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the day for a given date.
Typical SyntaxDay(date)
See AlsoDatePart Function, Hour Function, Minute Function, Month Function, Second Function, Year Function

Use the Day function as needed within your Visual Basic source code. If you are using either Visual Basic or Visual Basic for Applications, and you will be using the day returned from this function as a string (for example, to concatenate the day onto an existing string), consider using the Format$ function instead.

sInfo = "Day number " & Format$(dtAction, "d")

DDB Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the depreciation of an asset for a specific time period.
Typical SyntaxDDB(cost, salvage, life, period[, factor])
See AlsoFV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the DDB function as needed within your Visual Basic source code. This function returns a Double value, and accepts several Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the DDB function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the DDB function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

Debug Object

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeObject that supplies debugging features.
Typical SyntaxDebug
See AlsoApp Object, Global Object, Screen Object

Use the Debug object as needed within your Visual Basic source code. This object supplies two primary methods: Assert and Print. The Print method is not available in VBScript.

Declare Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReferences a procedure stored in a dynamic link library (DLL) for use in your source code.
Typical Syntax[Private | Public] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]
 [Private | Public] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]
See AlsoByRef Keyword, ByVal Keyword, Function Statement, Optional Keyword, ParamArray Keyword, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Use the Declare statement as needed within your Visual Basic source code. In general, all Declare statements should appear in a single module, although there are times when you may wish to encapsulate functionality within a single module by using private Declare statements. Always start the declaration with the Public or Private keyword. If no arguments are used with the function or subroutine, still follow the procedure name with an empty set of parentheses. When arguments are included, supply the appropriate data type with the As clause on each argument. Also, when declaring functions, end the declaration with the data type of the return value, using the final As clause.

Every argument must include the appropriate ByRef or ByVal keyword. Each argument must also include the appropriate data type, which may be the generic Any data type.

Procedure names appear in mixed case with an initial capital letter. Digits may be included, but underscores should be limited to event procedure names.

For more information about declaring procedures in your Visual Basic source code, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

DefType Statements

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeAssigns a default data type to declared objects that begin with a specific letter.
Typical SyntaxDefBool letterrange[, letterrange]...
 DefByte letterrange[, letterrange]...
 DefInt letterrange[, letterrange]...
 DefLng letterrange[, letterrange]...
 DefCur letterrange[, letterrange]...
 DefSng letterrange[, letterrange]...
 DefDbl letterrange[, letterrange]...
 DefDec letterrange[, letterrange]...
 DefDate letterrange[, letterrange]...
 DefStr letterrange[, letterrange]...
 DefObj letterrange[, letterrange]...
 DefVar letterrange[, letterrange]...
See AlsoDim Statement, Function Statement, Private Statement, Property Get Statement, Public Statement

Do not use the DefType statements within your Visual Basic source code. Every declared variable needs its own As clause to define its data type. Also, return values from functions and Property Get procedures must have the data type of their return values indicated with an appropriate As clause.

DeleteSetting Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRemoves application information from the Windows registry.
Typical SyntaxDeleteSetting appname, section[, key]
See AlsoGetAllSettings Function, GetSetting Function, SaveSetting Function

Use the DeleteSetting statement as needed within your Visual Basic source code. Document all registry settings used by your application in the technical documentation or user documentation, as appropriate.

The DeleteSetting statement accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the DeleteSetting statement. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

Dim Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a variable that is local in scope.
Typical SyntaxDim [WithEvents] varname[([subscripts] )] [As [New] type]
See AlsoGlobal Statement, Private Statement, Public Statement, ReDim Statement, Static Statement

Use the Dim statement as needed within the routines of your Visual Basic application. Always include the appropriate As clause in the declaration. Do not place more than one variable declaration within a single Dim statement. Place each variable declaration on a separate source code line. In VBScript, it is permissible to place more than one variable with the same Hungarian prefix within the same Dim statement.

Local variables use the Hungarian naming conventions. Local variables do not begin with a Hungarian scope prefix, but start immediately with the Hungarian type identifier.

For more information about local variables and the Hungarian naming conventions, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

Beginning with Visual Basic 4, the Private statement replaced the Dim statement within the Declarations section of a Visual Basic module. Do not use the Dim statement to declare module-level variables; use the Private statement to make a variable visible in scope to the module. Continue to use the Dim statement to declare local variables within routines.

Dir Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns a file name that matches a pattern.
Typical SyntaxDir[(pathname[, attributes])]
VariationsDir$ Function
See AlsoChDir Statement, ChDrive Statement, CurDir Function

Use the Dir function as needed within your Visual Basic source code. If you do not require a Variant result, use the Dir$ function instead of the Dir function.

vntFileMatch = Dir("*.*")
sFileMatch = Dir$("*.*")

The pathname argument supplied to the Dir function may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory. The attributes argument accepts an Integer value, or one or more of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

The Dir function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Dir function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Do...Loop Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeRepeats a block of code until a specified condition is met.
Typical SyntaxDo [{While | Until} condition] [statements]
 Loop
 Do [statements]
 Loop [{While | Until} condition]
See AlsoExit Block Statement, For Each...Next Statement, For...Next Statement, While...Wend Statement

Use the Do...Loop statement as needed within your Visual Basic source code. When forming the condition of your statement, make it as clear as possible, using parentheses to group values when ambiguity (for the reader) is possible. Enclosing the condition in a set of parentheses also improves readability.

Do While (condition)

The condition can appear at the beginning of the loop (with the Do keyword) or at the end of the loop (with the Loop keyword). Visual Basic allows you to leave the condition off entirely to create an infinite loop. However, you should always include a condition. If you wish to create an infinite loop, use While True as the condition.

Do While True
    ' ----- Statements appear here
Loop

If you need to exit such an infinite loop, use the Exit Do statement. However, it is better to use a valid condition with the loop's While or Until keyword.

Never jump to a line label in the middle of a loop using a GoTo statement found outside of the loop. Also, do not jump out of a loop using a GoTo statement; use the Exit Do statement instead. If you have nested Do...Loop statements, the Exit Do statement only exits the loop immediately containing the Exit Do statement.

DoEvents Function

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes (with limitations), VBScript:No
PurposeYields execution to the operating system so that other application events can be processed.
Typical SyntaxDoEvents

Although most programmers treat the DoEvents function like a statement, it is actually a function that returns the number of open forms when running within a true Visual Basic application (but not within a Visual Basic for Applications program).

The use of the DoEvents function can lead to subtle errors within your application. When you give up processing time to the operating system, it may allow the user of your application to perform additional user interface activities within your application, circumventing the natural flow of your event-driven source code. Consider a printing form with a Print command button on it, and the following event code.

Private Sub cmdPrint Click()
    ' ----- Print the data, then close the form
    Call PreparePrintJob
    DoEvents
    Call PrintThePrintJob
    Unload Me
End Sub

If the user attempts to click the Print button twice, it is possible for the printing code to run twice, because the DoEvents temporarily suspends control of the cmdPrint_Click event so that other events (including a new call to cmdPrint_Click) can occur. If you need to prevent a second print from occurring in this instance, you should avoid the use of the DoEvents function. You may also wish to disable the Print button, and other relevant controls, so that the user cannot disrupt the printing process.

If you need to perform periodic processing within your application, consider the use of a timer. While a timer may also interrupt a routine to perform its processing, you can control the interval at which the timer operates.

Never use the DoEvents function simply to allow the forms or controls of your application to redraw themselves. If you need a form or a control to be visually refreshed, use the form or control's Refresh method instead.

Empty Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates that a variable or value is uninitialized.
Typical SyntaxNothing
See AlsoIsEmpty Function, Nothing Keyword, Null Keyword

Use the Empty keyword as needed within your Visual Basic source code. Never test an expression by comparing it with the Empty keyword. Always use the IsEmpty function instead.

Incorrect
If (vntBuild = Empty) Then

Correct
If (IsEmpty(vntBuild)) Then

End Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeHalts program execution immediately.
Typical SyntaxEnd
See AlsoEnd Block Statement, Stop Statement

Your application should include no more than one or two End statements, each located within a centralized cleanup or termination routine. Never use the End statement to abort an application in response to an error. If you encounter a "fatal" error within your application, save as much of the user's data and state information as possible, close all acquired resources, and then use the End statement through a centralized procedure.

In a compiled application, use the End statement instead of the Stop statement to halt application execution.

End Block Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeEnds a subordinate block of code.
Typical SyntaxEnd Function
 End If
 End Property
 End Select
 End Sub
 End Type
 End With
See AlsoEnd Statement, Function Statement, If...Then...Else Statement, Property Get Statement, Property Let Statement, Property Set Statement, Select Statement, Sub Statement, Type Statement, With Statement

Use the End Block statements as needed within your Visual Basic source code. Note that the End Type statement is not available within Visual Basic, Scripting Edition. Also, the End If statement is not needed when an If statement and all of its subordinate statements are fully defined on a single source code line.

Enum Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDefines an enumerated data type.
Typical Syntax[Private | Public] Enum enumname membername [ = constantexpression]
 . . .
 End Enum
See AlsoConst Statement, Type Statement

Use the Enum statement as needed within your Visual Basic source code. Always begin the statement with either the Private or Public keyword, Include a mixed-case enumname ending in the word "Enum." Each element within the enumeration should be mixed case, beginning with a common lower-case enumeration prefix.

For more information about enumerated data types, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

Environ Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturn the value of a system environment variable.
Typical SyntaxEnviron(envstring | number)
VariationsEnviron$ Function

Use the Environ function as needed within your Visual Basic source code. If you do not require a Variant result, use the Environ$ function instead of the Environ function.

vntTempDir = Environ("TEMP")
sTempDir = Environ$("TEMP")

EOF Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates whether or not the end of the specified file has been reached.
Typical SyntaxEOF(filenumber)
See AlsoLoc Function, LOF Function, Open Statement, Seek Function, Seek Statement

Use the EOF function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the EOF function.

If you open a file for Binary access, and then use the Input function to retrieve values, the EOF function will not be a sufficient indicator of when the end of file has been reached. When using the Input function, use the LOF function and the Loc function together to determine when the end of file has been reached. If you instead retrieve records from a Binary file using the Get Statement, the EOF function is a valid method for determining the end of file status. The EOF function is useless when used on files opened for Output.

The EOF function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the EOF function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Eqv Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise equivalence operation.
Typical Syntaxexpression1 Eqv expression2
See AlsoAnd Operator, Imp Operator, Not Operator, Or Operator, Xor Operator

Use the Eqv operator as needed within your Visual Basic source code. When writing complex statements that involve more than one logical or bitwise operator, use parentheses to indicate the proper precedence and grouping within the calculation.

Erase Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeClears the elements of an array, freeing memory if the array is dynamic.
Typical SyntaxErase arraylist
See AlsoArray Statement, Dim Statement, Private Statement, Public Statement, ReDim Statement, Static Statement

Use the Erase statement as needed within your Visual Basic source code. The syntax of the Erase statement allows more than one array variable to be specified in the same statement. In order to improve the clarity of your code, do not use this syntax. Always issue a separate Erase statement for each array to be erased.

When erasing dynamic arrays (those resized with the ReDim statement), take care not to reuse the array until you have issued another ReDim statement on the array.

Erl Function

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIdentifies the approximate line number where an error occurred.
Typical SyntaxErl
See AlsoDebug Object, Err Object, Err Function, Error Function, Error Statement

The Erl function is only valid when you employ numeric line numbers within your source code. In general, alphanumeric line labels should be used instead of numeric line numbers for clarity. Without these numeric line numbers, the Erl function is useless. However, it may be useful to temporary add numeric line numbers to a routine in which an elusive error appears. When you have successfully located and removed the source of the problem, you can also remove the numeric line numbers, and the Erl function, from the code.

The Erl function returns the line number that is approximately near to the location of the error. Its use does not guarantee that you will detect the closest line number. Therefore, you may wish to employ additional conditions to help you narrow down the source of an error.

Err Object

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeObject that contains properties and methods for error processing.
Typical SyntaxErr
See AlsoDebug Object, Error Function, Error Statement

Use the Err object as needed within your Visual Basic source code. The default property of the Err object is the Number property. To obtain the error number of the most recent error, use either the "Err" syntax or the "Err.Number" syntax.

Error Function

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the message of an error for a given error code.
Typical SyntaxError[(errornumber)]
VariationsError$ Function
See AlsoDebug Object, Err Object, Error Statement

Use the Error function as needed within your Visual Basic source code. If you do not require a Variant result, use the Error$ function instead of the Error function.

vntErrorText = Error(nRecentError)
MsgBox Error$, vbOKOnly + vbExclamation, "Error"

When presenting errors to the user, consider the Err.Description property as well.

Error Statement

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSimulates the generation of an error.
Typical SyntaxError errornumber
See AlsoDebug Object, Err Object, Error Function

Do not use the Error statement within your Visual Basic source code. Use the Err object's Raise method instead.

Eval Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeEvaluates a VBScript expression that is stored in a string.
Typical SyntaxEval(expression)
See AlsoExecute Statement, ExecuteGlobal Statement

Avoid the use of the Eval function in your VBScript source code unless no other solution can be clearly or efficiently provided. If you will be ignoring the return value of the Eval function, consider the Execute statement or the ExecuteGlobal Statement instead.

Event Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDeclares an event.
Typical Syntax[Public] Event name [(arglist)]
See AlsoRaiseEvent Statement

Use the Event statement as needed within your Visual Basic source code. Always start the declaration with the Public keyword. If no arguments are used with the function, still follow the event name with an empty set of parentheses. When arguments are included, supply the appropriate data type with the As clause on each argument. Also, identify the passing method of each argument by supplying either the ByRef or ByVal keyword.

Event names appear in mixed case with an initial capital letter. Digits may be included, but underscores are not allowed. An underscore will be automatically added in an event name when an event procedure is written.

Execute Statement

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeExecutes one or more statements stored in a string.
Typical SyntaxExecute statement
See AlsoEval Function, ExecuteGlobal Statement

Avoid the use of the Execute function in your VBScript source code unless no other solution can be clearly or efficiently provided. If you need to evaluate the return value from the statement, consider the Eval function instead.

ExecuteGlobal Statement

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeExecutes one or more statements stored in a string.
Typical SyntaxExecuteGlobal statement
See AlsoEval Function, Execute Statement

Avoid the use of the ExecuteGlobal function in your VBScript source code unless no other solution can be clearly or efficiently provided. If you need to evaluate the return value from the statement, consider the Eval function instead.

Exit Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeExits a loop or routine immediately.
Typical SyntaxExit Do
 Exit For
 Exit Function
 Exit Property
 Exit Sub
See AlsoDo...Loop Statement, End Block Statement, For...Next Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Use the Exit statements as needed within your Visual Basic source code. If you find yourself using an abundance of these statements, it may indicate a poorly designed procedure or loop construct. For example, if you have several Exit For statements within a single For...Next loop, it may be better to convert the loop to a Do...Loop statement, and test for the exit conditions at the top or bottom of the loop construct. Consider the following For...Next statement:

For nCounter = 1 To 10
    If (OutOfSpace() = True) Then Exit For
    ' ----- Perform regular processing here
Next nCounter

You can convert this series of statements into a Do...Loop construct, removing the need for the Exit For statement altogether.

nCounter = 1
Do While (nCounter <= 10) And  
        (OutOfSpace() = False)
    ' ----- Perform regular processing here
    nCounter = nCounter + 1
Loop

If a procedure contains GoSub and On Error statements, all of the destinations should appear at the end of the routine. The last statement in the main body of the routine before the GoSub and On Error destinations should be an Exit Function, Exit Property, or Exit Sub statement.

When handling an error trapped with an On Error statement, you must choose either to exit the procedure using Exit Function, Exit Property, or Exit Sub, or return to the main body of the routine with a Resume statement. If you choose to exit the routine immediately with one of the Exit statements, make sure that you release all resources opened within the routine. Perform as orderly a cleanup as possible before returning to the calling procedure, even if an error prevents you from doing a perfect and complete cleanup.

Exp Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates e (the base of natural logarithms) raised to a power.
Typical SyntaxExp(number)
See AlsoLog Function, Sqr Function

Use the Exp function as needed within your Visual Basic source code. This function returns a Double value, and accepts a Double value for its parameter. Double floating point values are subject to minor rounding errors. Take care to check the accuracy of the return values when using the Visual Basic intrinsic math functions.

The argument to the Exp function can be no greater than 709.78212893. If the expression you pass to the Exp function is supplied by the user, and if that expression is out of the valid range for the Exp function, either correctly handle the error raised by the Exp function, or reject the value entered by the user.

False Keyword

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeProvides an intrinsic constant for the False Boolean value.
Typical SyntaxFalse
See AlsoTrue Keyword

Use the False keyword as needed within your Visual Basic source code. Although the False keyword has a value equal to 0 (zero), it is not always interpreted as 0 when coerced into other data types. Consider the following statements:

Dim sWork As String
Dim nWork As Integer
nWork = False
sWork = nWork & " = " & False
MsgBox sWork

Processing this code within a Visual Basic application will display a message box with the text "0 = False" instead of the expected "0 = 0." The False keyword, and all true Boolean values that equate to False, result in the text "False" when converted to a String.

Never use 0 when you mean False. Also, never use False when you mean 0 (zero). When you are testing the value of a Boolean variable, or the result of a Boolean expression, always compare the variable or expression to True or False, never to āˆ’1 or 0.

FileAttr Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the attributes of an open file.
Typical SyntaxFileAttr(filenumber, returntype)
See AlsoFreeFile Statement, GetAttr Function, SetAttr Statement, Open Statement

Use the FileAttr function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as the first argument to the FileAttr function.

The FileAttr function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the FileAttr function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

FileCopy Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCopies a file from one location to another.
Typical SyntaxFileCopy source, destination
See AlsoKill Statement, Name Statement

Use the FileCopy statement as needed within your Visual Basic source code. The arguments supplied to the FileCopy statement may be local or mapped drive paths, UNC (Universal Naming Convention) paths, or paths relative to the current drive and directory.

Be aware that the FileCopy statement will replace any existing file at the destination with a copy of the source file. If the destination is a user file, make sure you sufficiently inform the user that the file will be overwritten, either through documentation or through application notification.

The FileCopy statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the FileCopy statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

FileDateTime Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the modification date and time of a file.
Typical SyntaxFileDateTime(pathname)
See AlsoFileLen Function, GetAttr Function, SetAttr Statement

Use the FileDateTime function as needed within your Visual Basic source code. The argument supplied to the FileDateTime statement may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory.

The FileDateTime function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the FileDateTime function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

FileLen Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the number of bytes in a file.
Typical SyntaxFileLen(pathname)
See AlsoFileDateTime Function, GetAttr Function, LOF Function, SetAttr Statement

Use the FileLen function as needed within your Visual Basic source code. The argument supplied to the FileLen function may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory.

While you can use the FileLen function on an open file, the number of bytes returned is the file size at the time the file was opened. To more accurately determine the size of an open file, use the LOF function.

The FileLen function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the FileLen function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Filter Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns an array of strings that match or do not match a substring.
Typical SyntaxFilter(inputstrings, value[, include[, compare]])
See AlsoInStr Function, InStrRev Function, Option Compare Statement, Replace Function

Use the Filter function as needed within your Visual Basic source code. The compare argument of the Filter function accepts Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. The use of the Option Compare statement can affect the results of the Filter function.

Fix Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeTruncates the fractional portion of an expression.
Typical SyntaxFix(expression)
See AlsoAbs Function, Int Function, Round Function, Sgn Function

Use the Fix function as needed within your Visual Basic source code. For positive numbers, the Fix and Int functions are identical. For negative values, the Fix function truncates the fractional portion of the number, leaving the whole number intact. The Int function returns the next larger negative value when a fractional component is non-zero. If you are sure that you will pass positive values only as arguments, use the Int function instead of the Fix function.

For Each...Next Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeRepeats a block of code for each element in a collection or array.
Typical SyntaxFor Each element In group [statements]
 Next [element]
See AlsoDo...Loop Statement, Exit Block Statement, For...Next Statement, While...Wend Statement

Use the For Each...Next statement as needed within your Visual Basic source code. Never resize the group of elements within the loop. Although Visual Basic does not require element in the Next clause, always include it for clarity. In VBScript, you cannot include element in the Next clause.

Visual Basic and Visual Basic for Applications allow you to combine multiple element variables into a single Next clause. Never use this syntax, as it reduces readability and increases the chance for errors.

Incorrect
For Each vntOuter In nOutArray
    For Each vntInner In nInArray
        Debug.Print vntOuter, vntInner
Next vntInner, vntOuter

Correct
For Each vntOuter In nOutArray
    For Each vntInner In nInArray
        Debug.Print vntOuter, vntInner
    Next vntInner
Next vntOuter

Never jump to a line label in the middle of a loop using a GoTo statement found outside of the loop. Also, do not jump out of a loop using a GoTo statement; use the Exit For statement instead. If you have nested For Each...Next statements, the Exit For statement exits only the loop immediately containing the Exit For statement.

For...Next Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeRepeats a block of code a specified number of times.
Typical SyntaxFor counter =start To end [ Step step] [statements]
 Next [counter]
See AlsoDo...Loop Statement, Exit Block Statement, For Each...Next Statement, While...Wend Statement

Use the For...Next statement as needed within your Visual Basic source code. Never change the value of counter within the loop. Consider counter to be a read-only variable between the For and Next clauses. If you need to change the counter value inside of the loop, convert the loop to a Do...Loop statement instead.

Although Visual Basic does not require counter in the Next clause, always include it for clarity. In VBScript, you cannot include counter in the Next clause.

The start, end, and step values are calculated only once upon entry into the loop. Modifying these values in the middle of the loop has no effect on the loop itself. Consider the following block of code:

nUpper = 5
For nCounter = 1 To nUpper
    MsgBox nCounter
    nUpper = nUpper - 1
Next nCounter

Although the end value (nUpper) is modified in the loop, this loop still executes five times.

Visual Basic and Visual Basic for Applications allow you to combine multiple counter variables into a single Next clause. Never use this syntax, as it reduces readability and increases the chance for errors.

Incorrect
For nOuter = 1 To 5
    For nInner = 1 To 5
        MsgBox nOuter, nInner
Next nInner, nOuter

Correct
For nOuter = 1 To 5
    For nInner = 1 To 5
        MsgBox nOuter, nInner
    Next nInner
Next nOuter

Never jump to a line label in the middle of a loop using a GoTo statement found outside of the loop. Also, do not jump out of a loop using a GoTo statement; use the Exit For statement instead. If you have nested For...Next statements, the Exit For statement only exits the loop immediately containing the Exit For statement.

Format Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeFormats an expression based on a description.
Typical SyntaxFormat(expression[, format[, firstdayofweek[, firstweekofyear]]])
VariationsFormat$ Function
See AlsoFormatCurrency Function, FormatDateTime Function, FormatNumber Function, FormatPercent Function

Use the Format function as needed within your Visual Basic source code. Always include the format argument, even if you will be using the default formatting method for an expression. If you do not require a Variant result, use the Format$ function instead of the Format function.

vntDisplay = Format(fcCost, "$#,##0.00")
sDisplay = Format$(fcCost, "$#,##0.00")

The firstdayofweek and firstweekofyear arguments to the Format function accept Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

FormatCurrency Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeFormats an expression to look like a currency amount.
Typical SyntaxFormatCurrency(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]])
See AlsoFormat Function, FormatDateTime Function, FormatNumber Function, FormatPercent Function

Use the FormatCurrency function as needed within your Visual Basic source code. The leadingdigit, negativeparens, and groupdigits arguments to the FormatCurrency function each accept an Integer value, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. These arguments also accept the values True and False, although the intrinsic literals are preferred.

In VBScript, the FormatCurrency function is one of a family of functions that replaces the Format function. These functions exist in standard Visual Basic, and are quite useful. The FormatCurrency function was designed to provide a common method of formatting currency values in a Visual Basic application or script. However, you may find that the FormatCurrency function has too many restrictions to meet your formatting needs. If you need more flexibility, and you are working with either Visual Basic or Visual Basic for Applications, use the Format function.

FormatDateTime Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeFormats an expression to look like a date or time.
Typical SyntaxFormatDateTime(expression[, format])
See AlsoFormat Function, FormatCurrency Function, FormatNumber Function, FormatPercent Function

Use the FormatDateTime function as needed within your Visual Basic source code. The format argument to the FormatDateTime function accepts an Integer value, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

In VBScript, the FormatDateTime function is one of a family of functions that replaces the Format function. These functions exist in standard Visual Basic, and are quite useful. The FormatDateTime function was designed to provide a common method of formatting date values in a Visual Basic application or script. However, you may find that the FormatDateTime function has too many restrictions to meet your formatting needs. If you need more flexibility, and you are working with either Visual Basic or Visual Basic for Applications, use the Format function.

FormatNumber Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeFormats an expression to look like a number.
Typical SyntaxFormatNumber(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]])
See AlsoFormat Function, FormatCurrency Function, FormatDateTime Function, FormatPercent Function

Use the FormatNumber function as needed within your Visual Basic source code. The leadingdigit, negativeparens, and groupdigits arguments to the FormatNumber function each accept an Integer value, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. These arguments also accept the values True and False, although the intrinsic literals are preferred.

In VBScript, the FormatNumber function is one of a family of functions that replaces the Format function. These functions exist in standard Visual Basic, and are quite useful. The FormatNumber function was designed to provide a common method of formatting numeric values in a Visual Basic application or script. However, you may find that the FormatNumber function has too many restrictions to meet your formatting needs. If you need more flexibility, and you are working with either Visual Basic or Visual Basic for Applications, use the Format function.

FormatPercent Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeFormats an expression to look like a percent.
Typical SyntaxFormatPercent(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]])
See AlsoFormat Function, FormatCurrency Function, FormatDateTime Function, FormatNumber Function

Use the FormatPercent function as needed within your Visual Basic source code. The leadingdigit, negativeparens, and groupdigits arguments to the FormatPercent function each accept an Integer value, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. These arguments also accept the values True and False, although the intrinsic literals are preferred.

The FormatPercent function multiplies the original value by 100 before formatting the final output. Consider the following statement:

MsgBox FormatPercent(25)

This statement displays a message box with the following text:

2,500.00%

In VBScript, the FormatPercent function is one of a family of functions that replaces the Format function. These functions exist in standard Visual Basic, and are quite useful. The FormatPercent function was designed to provide a common method of formatting percent values in a Visual Basic application or script. However, you may find that the FormatPercent function has too many restrictions to meet your formatting needs. If you need more flexibility, and you are working with either Visual Basic or Visual Basic for Applications, use the Format function.

FreeFile Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns an available number for use by the Open statement.
Typical SyntaxFreeFile[(rangenumber)]
See AlsoOpen Statement

Use the FreeFile function as needed within your Visual Basic source code. In general, you should not need to supply the optional rangenumber argument. However, if your application will use file numbers in the 256ā€“511 range (accessed by using 1 as the rangenumber argument), then supply the rangenumber argument on every call to FreeFile within your application.

The Open statement allows you to use any valid unused file number as a file identifier. Visual Basic permits you to supply these numbers yourself. However, conflicts may result in large applications if central control of the available numbers is not enforced. Therefore, always obtain a valid file number using the FreeFile statement. Never use numeric literals for the file number.

Incorrect
' ----- Open the source file
Open sSourceFile For Input As #1

Instead, use the FreeFile function to ensure a valid and available file number.

Correct
' ----- Open the source file
nSourceFileID = FreeFile
Open sSourceFile For Input As #nSourceFileID

The FreeFile function returns the next available number. If you call the function two times in a row without opening or closing a file, you will receive the same value. Consider the following statements:

' ----- Open the source and destination files
nSourceFileID = FreeFile
nDestFileID = FreeFile
Open sSourceFile For Input As #nSourceFileID
Open sDestFile For Output As #nDestFileID

This block of code will fail when the destination file is opened because the file number (nDestFileID) is already in use by the source file (through nSourceFileID). To make this code work properly, rewrite it in this manner:

' ----- Open the source and destination files
nSourceFileID = FreeFile
Open sSourceFile For Input As #nSourceFileID
nDestFileID = FreeFile
Open sDestFile For Output As #nDestFileID

Function Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a function procedure.
Typical Syntax[Private | Public | Friend] [Static] Function name [(arglist)] [ As type] [statements]
 End Function
See AlsoByRef Keyword, ByVal Keyword, Optional Keyword, ParamArray Keyword, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Use the Function statement as needed within your Visual Basic source code. Always start the declaration with the Friend, Public, or Private keyword. If no arguments are used with the function, still follow the function name with an empty set of parentheses. When arguments are included, supply the appropriate data type with the As clause on each argument. Also, end the function declaration with the data type of the return value, using the final As clause. (These last two rules do not apply to VBScript functions.)

Procedure names appear in mixed case with an initial capital letter. Digits may be included, but underscores should be limited to event procedure names.

Never include the Static keyword in the Function statement. If you want to include static local variables within your function, declare each variable using the Static statement. The Static keyword is not available in VBScript.

For more information about declaring procedures in your Visual Basic source code, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

FV Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the future value of an annuity.
Typical SyntaxFV(rate, nper, pmt[, pv[, type]])
See AlsoDDB Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the FV function as needed within your Visual Basic source code. This function returns a Double value, and accepts several Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the FV function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the FV function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

Get Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReads data from a file and assigns the result to a variable.
Typical SyntaxGet [#]filenumber, [recnumber], varname
See AlsoOpen Statement, Put Statement, Seek Statement

Use the Get statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Get statement. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.

Data written with the Put statement is read with the Get statement. In general, the structure of the data written with the Put statement must be known to the code that will read the file with the Get statement. You may wish to include, at the beginning of your file data, identification values (sometimes called "magic numbers") that prove the file was written with the expected application, and with the appropriate version of that application.

The Get statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Get statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

GetAllSettings Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns an array of application settings from the Windows registry.
Typical SyntaxGetAllSettings(appname, section)
See AlsoDeleteSetting Statement, GetSetting Function, SaveSetting Statement

Use the GetAllSettings function as needed within your Visual Basic source code. Document all registry settings used by your application in the technical documentation or user documentation, as appropriate.

The GetAllSettings function accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the GetAllSettings function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

GetAttr Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the attributes of a file.
Typical SyntaxGetAttr(pathname)
See AlsoFileAttr Function, SetAttr Statement

Use the GetAttr function as needed within your Visual Basic source code. The argument supplied to the GetAttr function may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory.

The return value of the GetAttr function is an integer value, represented by a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

The GetAttr function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the GetAttr function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

GetLocale Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeIdentifies the current locale.
Typical SyntaxGetLocale()
See AlsoSetLocale Function

Use the GetLocale function as needed within your Visual Basic source code. Visual Basic does not define a set of constants for the Locale ID, which is returned by this function. However, you may wish to declare a constant for the Locale IDs that you use within your application.

GetObject Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeRetrieves a reference to an ActiveX object.
Typical SyntaxGetObject([pathname] [, class])
See AlsoCreateObject Function

Use the GetObject function as needed within your Visual Basic source code. The GetObject function accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the GetObject function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

GetRef Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeGets a procedure reference for use with DHTML events.
Typical SyntaxGetRef(procname)
See AlsoAddressOf Operator

Use the GetRef function as needed within your Visual Basic source code.

GetSetting Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns an application value from the Windows registry.
Typical SyntaxGetSetting(appname, section, key[, default])
See AlsoDeleteSetting Statement, GetAllSettings Function, SaveSetting Statement

Use the GetSetting function as needed within your Visual Basic source code. Document all registry settings used by your application in the technical documentation or user documentation, as appropriate.

The GetSetting function accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the GetSetting function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

Global Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDeclares a variable that is global in scope.
Typical SyntaxGlobal varname [ As type]
See AlsoDim Statement, Private Statement, Public Statement, Static Statement

Beginning with Visual Basic 4, the Public statement replaced the Global statement. Do not use the Global statement to declare global variables; use the Public statement to make a variable global to the application.

Global Object

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:No, VBScript:No
PurposeObject that supplies global methods and properties.
Typical SyntaxGlobal
See AlsoApp Object, Debug Object, Screen Object

Use the Global object as needed within your Visual Basic source code. When using Visual Basic for Applications or Visual Basic, Scripting Edition, there may be an object available that is contextually similar to the Visual Basic Global object.

It is not necessary to prefix the properties and methods of the Global object with the Global keyword, unless other objects made available within your application make such references ambiguous.

Incorrect
Global.Printer.EndDoc

Correct
Printer.EndDoc

GoSub...Return Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeContinues execution at a specified line number or label, then returns to resume the original path of execution.
Typical SyntaxGoSub line
 . . .
 line:
 . . .
 Return
See AlsoGoTo Statement, On Error Statement, On...GoSub Statement, On...GoTo Statement

Use the GoSub...Return statement as needed within your Visual Basic source code. While GoSub statements are useful, their overuse can indicate a problem in the logic of a procedure. Most procedures in your source code should be free of GoSub statements, and if one routine contains more than about four such statements, the procedure should be rewritten in a more structured or procedure-driven manner. For larger blocks of code found within a GoSub destination, you may wish to consider moving them to separate procedures.

Chapter 2, Using Declaration, and Chapter 9, Declaration Standards, discuss line labels and their use within Visual Basic procedures.

GoTo Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeContinues execution at a specified line number or label.
Typical SyntaxGoTo line
See AlsoGoSub...Return Statement, On Error Statement, On...GoSub Statement, On...GoTo Statement

Use the GoTo statement as needed within your Visual Basic source code. While GoTo statements are useful, their overuse can indicate a problem in the logic of a procedure. Most procedures in your source code should be free of GoTo statements, and if one routine contains more than about four such statements, the procedure should probably be rewritten in a more structured or procedure-driven manner.

Chapter 2, Using Declaration, and Chapter 9, Declaration Standards, discuss line labels and their use within Visual Basic procedures.

Hex Function

CategoryConversion Functions, String Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a hexadecimal representation of an expression, in string format.
Typical SyntaxHex(expression)
VariationsHex$ Function
See AlsoOct Function

Use the Hex function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Hex(argument)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Hex$(argument)

When using the Hex$ version of this function, the argument cannot be Null. If you think that your code will allow a Null value to be passed to the Hex$ function, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

sDisplayKey = Hex$(rsInfo!EncryptKey & "")

It is permissible to use the Empty value as an argument to either the Hex function or the Hex$ function.

Hour Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the hour for a given date or time.
Typical SyntaxHour(time)
See AlsoDatePart Function, Day Function, Minute Function, Month Function, Second Function, Year Function

Use the Hour function as needed within your Visual Basic source code. If you are using either Visual Basic or Visual Basic for Applications, and you will be using the hour returned from this function as a string (for example, to concatenate the hour onto an existing string), consider using the Format$ function instead.

sInfo = "Hour number " & Format$(dtAction, "h")

If...Then...Else Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeExecutes blocks of code based on a condition.
Typical SyntaxIf conditionThen [statements] [Else statements]
 If conditionThen [statements]
 [ElseIf condition-nThen [statements]]...
 [Else [statements]]
 End If
See Also#If...Then...#Else Directive, IIf Function, Select Case Statement

Use the If...Then...Else statement as needed within your Visual Basic source code. When forming the condition sections of your statement, make them as clear as possible, using parentheses to group values when ambiguity (for the reader) is possible. Enclosing each condition in a set of parentheses also improves readability.

If (condition) Then

Although Visual Basic allows you to leave the Then section of statements blank, do not use this syntax. If you find that you need only the Else section, reverse the condition so that the Else condition becomes a Then section.

Incorrect
If (nResult < RESULT_LIMIT) Then
Else
    MsgBox "You went over the limit.", _
        vbOKOnly + vbExclamation, "Notice"
End If

Correct
If (nResult >= RESULT_LIMIT) Then
    MsgBox "You went over the limit.", _
        vbOKOnly + vbExclamation, "Notice"
End If

If your Else section contains only an If statement (even when that If statement contains subordinate statements), change it to an ElseIf section instead.

Incorrect
If (bGoodCredit) Then
    ' ----- Process order
Else
    If (bLongTimeCustomer) Then
        ' ----- Process with warnings
    End If
End If

Correct
If (bGoodCredit) Then
    ' ----- Process order
ElseIf (bLongTimeCustomer) Then
    ' ----- Process with warnings
End If

Limit your If statement to three ElseIf sections. If you need more ElseIf sections, consider using the Select Case statement instead.

IIf Function

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns one of a set of values based on a Boolean expression.
Typical SyntaxIIf(expression, truepart, falsepart)
See AlsoChoose Function, If...Then...Else Statement, Switch Function

Use the IIf function as needed within your Visual Basic source code. Although only one of the result arguments will be returned based on the expression, both result arguments are evaluated. Make sure that the arguments do not contain any code that will fail on invalid conditions, or that should execute only with certain Boolean results.

IMEStatus Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIdentifies the current Input Method Editor (IME) mode.
Typical SyntaxIMEStatus

Use the IMEStatus function as needed within your Visual Basic source code. This function is available only in the Far East versions of Visual Basic. If you use a common source code base for multiple language versions of your application, use #Const statements and #If...Then...#Else statements to separate Far East source code from non-Far East source code. Also, make it clear in your source code comments, and your technical documentation, how the different language versions of the application differ from the source code point of view.

Imp Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise implication operation.
Typical Syntaxexpression1 Imp expression2
See AlsoAnd Operator, Eqv Operator, Not Operator, Or Operator, Xor Operator.

Use the Imp operator as needed within your Visual Basic source code. When writing complex statements that involve more than one logical or bitwise operator, use parentheses to indicate the proper precedence and grouping within the calculation.

Implements Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates that a specific interface or class will be implemented in a class module.
Typical SyntaxImplements [interface | class]
See AlsoClass Statement

Use the Implements statement as needed within your Visual Basic source code. Include in your technical documentation a description of the interface or class to be implemented. Also note in your source code comments for the Implements statement the location in your technical documentation where the interface or class is documented.

Input # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReads data from a file and assigns the results to variables.
Typical SyntaxInput #filenumber, varlist
See AlsoInput Function, Line Input # Statement, Open Statement, Print # Statement, Write # Statement

Use the Input # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Input # statement. If you wish to retrieve text written with the Print # statement, consider the Line Input # statement instead.

Data written with the Write # statement is read with the Input # statement. In general, the structure of the data written with the Write # statement must be known to the code that will read the file with the Input # statement. You may wish to include, at the beginning of your file data, identification values (sometimes called "magic numbers") that prove the file was written with the expected application, and with the appropriate version of that application.

The Input # statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Input # statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Input Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReads characters from an open file.
Typical SyntaxInput(number, [ #]filenumber)
VariationsInput$ Function, InputB Function, InputB$ Function
See AlsoGet Statement, Input # Statement, Line Input # Statement, Open Statement, Print # Statement, Put Statement, Write # Statement

Use the Input function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as the second argument to the Input function. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.

If you do not require a Variant result, use the Input$ function instead of the Input function.

vntSampleText = Input(50, #nSourceFile)
sSampleText = Input$(50, #nSourceFile)

If you need to work with the underlying bytes contained within the file, use either the InputB function or the InputB$ function.

The Input function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Input function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

InputBox Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposePrompts the user for data input.
Typical SyntaxInputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])
VariationsInputBox$ Function
See AlsoMsgBox Function

The InputBox function is useful for simple input of minor user data. However, its use should be restricted due to the limited amount of data it can collect. A user-initiated event (such as a command button click) should never result in more than two uses of the InputBox function. If you need to prompt the user for more than two pieces of information, create a new form that contains all of the input fields. Even when you need only a single text field's worth of input, creating a new form is often better than the InputBox function. With a true form, you can verify the user's input on the OK button's Click event without hiding the form. The InputBox form must be removed from the screen before the data can be verified, giving your application a rough feel. Still, for the simplest input needs, the InputBox function is useful.

The user cannot enter an empty string as a valid response through the InputBox function. InputBox returns an empty string when the user clicks the Cancel button. If you need to allow the user to enter an empty string as valid input, create a new form instead of using the InputBox function.

When calling the InputBox function, always supply both the prompt and title arguments. If possible, supply a reasonable default argument as well.

Because the InputBox function contains no error checking, make sure you validate the return value of the function. This is especially true if you are prompting the user for numeric or date information.

Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

InputBox(arguments)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

InputBox$(arguments)

InStr Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the location of a sub-string within a larger string.
Typical SyntaxInStr([start, ]string1, string2[, compare])
VariationsInStrB Function
See AlsoFilter Function, InStrRev Function, Join Function, Option Compare Statement, Replace Function, Split Function

Use the InStr function as needed within your Visual Basic source code. If you need to work with the underlying bytes contained within the original string, use the InStrB function.

It is permissible to omit the start argument of the InStr function when searching from the beginning of the string. You can also include this argument, and set it to a value of 1. Both of the following statements are valid, and produce the same result.

nPos = InStr(sLargeString, sSubString)
nPos = InStr(1, sLargeString, sSubString)

The compare argument of the InStr function accepts Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. The use of the Option Compare statement can affect the results of the InStr function.

InStrRev Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the location of a sub-string within a larger string, searching from the end of the larger string.
Typical SyntaxInStrRev(string1, string2[, start[, compare])
See AlsoFilter Function, InStr Function, Join Function, Option Compare Statement, Replace Function, Split Function

Use the InStrRev function as needed within your Visual Basic source code. The compare argument of the InStrRev function accepts Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. The use of the Option Compare statement can affect the results of the InStrRev function.

Int Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeTruncates the fractional portion of an expression.
Typical SyntaxInt(expression)
See AlsoAbs Function, Fix Function, Round Function, Sgn Function

Use the Int function as needed within your Visual Basic source code. For positive numbers, the Int and Fix functions are identical. For negative values, the Fix function truncates the fractional portion of the number, leaving the whole number intact. The Int function returns the next larger negative value when a fractional component is non-zero. If you are sure that you will pass only positive values as arguments, use the Int function instead of the Fix function.

IPmt Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the interest payment for a given period of an annuity.
Typical SyntaxIPmt(rate, per, nper, pv[, fv[, type]])
See AlsoDDB Function, FV Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the IPmt function as needed within your Visual Basic source code. This function returns a Double value, and accepts several Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the IPmt function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the IPmt function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

IRR Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the internal rate of return for a series of periodic cash flows.
Typical SyntaxIRR(values()[, guess])
See AlsoDDB Function, FV Function, IPmt Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the IRR function as needed within your Visual Basic source code. This function returns a Double value, and accepts an array of Double values for one of its parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the IRR function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the IRR function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

Is Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDetermines if two object variables refer to the same underlying object.
Typical Syntaxobject1 Is object2
See Also< Operator, <= Operator, <> Operator (Comparison), = Operator (Comparison), > Operator, >= Operator, Like Operator, Not Operator, Nothing Keyword

Use the Is operator as needed within your Visual Basic source code. Note that object2 can be replaced with the Nothing keyword to test if an object is undefined.

IsArray Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether a variable is an array.
Typical SyntaxIsArray(varname)
See AlsoArray Function, Dim Statement, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, ReDim Statement, TypeName Function, VarType Function

Use the IsArray function as needed within your Visual Basic source code. In general, you should not have to use this function on variables that were specifically created as arrays, or those that will never be arrays. This function is most useful when testing Variant variables that may be storing values created with the Array function.

IsDate Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether an expression is a valid date or time.
Typical SyntaxIsDate(expression)
See AlsoCDate Function, IsArray Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, VarType Function

Use the IsDate function as needed within your Visual Basic source code. The IsDate function does not check a date value for Year 2000 compliance.

IsEmpty Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether a variable or expression is not yet initialized.
Typical SyntaxIsEmpty(expression)
See AlsoEmpty Keyword, IsArray Function, IsDate Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, VarType Function

Use the IsEmpty function as needed within your Visual Basic source code. Never test a variable by comparing it with the Empty keyword. Always use the IsEmpty function instead.

Incorrect
If (vntUserData = Empty) Then

Correct
If (IsEmpty(vntUserData)) Then

IsError Function

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates whether an expression is an error value.
Typical SyntaxIsError(expression)
See AlsoCVErr Function, Err Object, IsArray Function, IsDate Function, IsEmpty Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, VarType Function

Use the IsError function as needed within your Visual Basic source code.

IsMissing Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates whether an optional argument was passed to the procedure.
Typical SyntaxIsMissing(argument)
See AlsoIsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsNull Function, IsNumeric Function, IsObject Function, Optional Keyword, TypeName Function, VarType Function

Use the IsMissing function as needed within your Visual Basic source code. In order for the IsMissing argument to work correctly, the argument must be defined as a Variant. If your only purpose for testing an argument is to supply it with a default value, include the default value in the declaration of the procedure instead.

Incorrect
Private Sub DoWork(Optional vntWithEffort As Variant)
    ' ----- Do a lot of work, or just a little
    Dim bWithEffort As Boolean
    
    ' ----- Start by checking the effort value
    If (IsMissing(vntWithEffort)) Then
        bWithEffort = False
    Else
        bWithEffort = CBool(vntWithEffort)
    End If

Correct
Private Sub DoWork(Optional bWithEffort _
        As Boolean = False)
    ' ----- Do a lot of work, or just a little

IsNull Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether an expression is Null.
Typical SyntaxIsNull(expression)
See AlsoIsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNumeric Function, IsObject Function, TypeName Function, VarType Function

Use the IsNull function as needed within your Visual Basic source code. Never test an expression by comparing it with the Null keyword. Always use the IsNull function instead.

Incorrect
If (rsInfo!OptionalInformation = Null) Then

Correct
If (IsNull(rsInfo!OptionalInformation)) Then

IsNumeric Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether an expression is a valid number.
Typical SyntaxIsNumeric(expression)
See AlsoCCur Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsObject Function, TypeName Function, VarType Function

Use the IsNumeric function as needed within your Visual Basic source code. The IsNumeric function considers Empty expressions to be numeric. It also recognizes as numeric strings containing hexadecimal and octal values in the Visual Basic format, as in the "&H1B" hexadecimal expression.

IsObject Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates whether a variable is an object.
Typical SyntaxIsObject(varname)
See AlsoCreateObject Function, GetObject Function, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, TypeName Function, VarType Function

Use the IsObject function as needed within your Visual Basic source code. The IsObject function considers Variant variables set to Nothing to be objects.

Join Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeJoins an array of strings together to form a single string.
Typical SyntaxJoin(list[, delimiter])
VariationsJoin$ Function
See Also& Operator, Replace Function, Split Function

Use the Join function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Join$(arguments)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Join$(arguments)

Kill Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDeletes a file.
Typical SyntaxKill pathname
See AlsoDir Function, FileCopy Statement, Name Statement

Use the Kill statement as needed within your Visual Basic source code. The argument supplied to the Kill statement may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory.

The pathname supplied to the Kill statement may contain wildcard characters ("*" and "?"). If you need to delete several files that match a pattern, and you are sure that no other user files will be removed in the process, include the wildcard characters as needed. You may also find it useful to determine the name of each file matching the wildcard pattern using the Dir function, then delete each file individually with the Kill statement.

If the file to be removed is a user file, make sure you sufficiently inform the user that the file will be deleted, either through documentation or through application notification.

The Kill statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Kill statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

LBound Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the lower numeric bound of an array dimension.
Typical SyntaxLBound(arrayname[, dimension])
See AlsoErase Statement, ReDim Statement, UBound Function

Use the LBound function as needed within your Visual Basic source code. You cannot use the LBound function on an array that has not yet been dimensioned, or on a redimensioned array that has been cleared with the Erase statement. In VBScript, the lower bound of every array dimension is 0 (zero).

If you are attempting to ascertain the lower bound of a one-dimensional array, do not include the dimension argument of the LBound function. If you are using the LBound function on a multi-dimensional array, even if you are testing the first dimension, always include the dimension argument.

LCase Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string converted to lower case.
Typical SyntaxLCase(string)
VariationsLCase$ Function
See AlsoUCase Function

Use the LCase function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

LCase(argument)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

LCase$(argument)

When using the LCase$ version of this function, the argument cannot be Null. If you think that your code will allow a Null value to be passed to the LCase$ function, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

sPanel = LCase$(rsInfo!Panel & "")

Left Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the left portion of a string.
Typical SyntaxLeft(string, length)
VariationsLeft$ Function, LeftB Function, LeftB$ Function
See AlsoMid Function, Right Function

Use the Left function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Left(arguments)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Left$(arguments)

If you need to work with the underlying bytes contained within the original string, use the LeftB function or the LeftB$ function.

When using the Left$ and LeftB$ versions of this function, the first argument cannot be Null. If you think that your code will allow a Null value to be passed to the Left$ or LeftB$ functions, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

' ----- Extract area code from xxx-xxx-xxxx
sAreaCode = Left$(rsInfo!Phone & "", 3)

Len Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the length of a string or string variable.
Typical SyntaxLen(string | varname)
VariationsLenB Function

Use the Len function as needed within your Visual Basic source code. If you need to count the underlying bytes of a variable or string expression, use the LenB function.

The argument to the Len function can be Null, but a Null value will be returned as the result. If you think that your code will allow a Null value to be passed to the Len function, and you require a numeric return value, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

' ----- Determine the name size requirements
nNameLength = Len(rsInfo!CustomerName & "")

Let Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeAssigns an expression to a variable.
Typical Syntax[Let] variable = expression
See Also= Operator (Assignment), Property Get Statement, Property Let Statement, Property Set Statement, Set Statement

Use assignment as needed within your Visual Basic source code. However, do not include the Let keyword in the assignment statement. It exists as a holdover from older versions of the BASIC language.

Like Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDetermines if one string matches a pattern.
Typical Syntaxstring Like pattern
See Also< Operator, <= Operator, <> Operator (Comparison), = Operator (Comparison), > Operator, >= Operator, Is Operator, Not Operator, Option Compare Statement

Use the Like operator as needed within your Visual Basic source code. The use of the Option Compare statement can affect comparisons performed with the Like operator.

Line Input # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReads a single line from an open sequential file.
Typical SyntaxLine Input #filenumber, varname
See AlsoInput # Statement, Open Statement, Print # Statement, Write # Statement

Use the Line Input # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Line Input # statement. If you wish to retrieve values written with the Write # statement, use the Input # statement instead.

The Line Input # statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Line Input # statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Load Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCreates an instance of a form or control.
Typical SyntaxLoad object
See AlsoUnload Statement

Use the Load statement as needed within your Visual Basic source code.

LoadPicture Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeLoads a graphic into a picture-bearing object.
Typical SyntaxLoadPicture([filename], [size], [colordepth], [x, y] )
See AlsoLoadResData Function, LoadResPicture Function, LoadResString Function, SavePicture Statement

Use the LoadPicture function as needed within your Visual Basic source code. The size and colordepth arguments of the LoadPicture function accept Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. Visual Basic, Scripting Edition uses only the filename argument.

The LoadPicture function accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the LoadPicture function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.

LoadResData Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeLoads data from a resource file.
Typical SyntaxLoadResData(index, format)
See AlsoLoadPicture Function, LoadResPicture Function, LoadResString Function, SavePicture Statement

Use the LoadResData function as needed within your Visual Basic source code. If you need to load a cursor, bitmap, or icon, and you do not need the loaded resource stored as a Byte array, use the LoadResPicture function instead. If you need to load a string, and you do not need the loaded resource stored as a Byte array, use the LoadResString function instead.

If you know in advance the arrangement of the resource file, define a set of constants, one constant for each indexed item in the file that you will load into the application.

The format argument of the LoadResData function accepts an Integer value. Visual Basic does not include a set of constants for use with this argument. When using this function, define your own constants for use with the format argument, or sufficiently define the use of the second argument in the source code comments that accompany the use of the LoadResData function.

LoadResPicture Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeLoads a bitmap, icon, or cursor from a resource file.
Typical SyntaxLoadResPicture(index, format)
See AlsoLoadPicture Function, LoadResData Function, LoadResString Function, SavePicture Statement

Use the LoadResPicture function as needed within your Visual Basic source code. If you know in advance the arrangement of the resource file, define a set of constants, one constant for each indexed item in the file that you will load into the application.

The format argument of the LoadResPicture function accepts Integer values, or one of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals.

LoadResString Function

CategoryMiscellaneous Features, String Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeLoads a string from a resource file.
Typical SyntaxLoadResString(index)
See AlsoLoadPicture Function, LoadResData Function, LoadResPicture Function, SavePicture Statement

Use the LoadResString function as needed within your Visual Basic source code. If you know in advance the arrangement of the resource file, define a set of constants, one constant for each indexed item in the file that you will load into the application.

Loc Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the current position in an open file.
Typical SyntaxLoc(filenumber)
See AlsoEOF Function, LOF Function, Open Statement, Seek Function, Seek Statement

Use the Loc function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Loc function.

The Loc function is primarily used with files opened in Random or Binary mode. Using the Loc function on a file opened in Input mode, or another sequential mode, will not return expected results. For such files, use the Seek function instead.

The Loc function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Loc function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Lock # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeLocks a portion or all of an open file.
Typical SyntaxLock [#]filenumber[, recordrange]
See AlsoOpen Statement, Unlock # Statement

Use the Lock # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Lock # statement. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.

The Lock # statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Lock # statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

LOF Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the length in bytes of an open file.
Typical SyntaxLOF(filenumber)
See AlsoEOF Function, FileLen Function, Loc Function, Open Statement, Seek Function, Seek Statement

Use the LOF function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the LOF function. To determine the length of a file that has not yet been opened, use the FileLen function.

The LOF function (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the LOF function. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Log Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the natural logarithm of a number.
Typical SyntaxLog(number)
See AlsoExp Function, Sqr Function

Use the Log function as needed within your Visual Basic source code. This function returns a Double value, and accepts a Double value for its parameter. Double floating point values are subject to minor rounding errors. Take care to check the accuracy of the return values when using the Visual Basic intrinsic math functions.

The argument to the Log function must be greater than 0 (zero). If the value you pass to the Log function is supplied by the user, and the user enters a value outside of the valid range, either correctly handle the error raised by the Log function, or reject the value entered by the user.

LSet Statement

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeLeft aligns a string within a string variable. Another syntax copies the bytes of one user-defined type variable into another user-defined type variable.
Typical SyntaxLSet stringvar = string
 LSet varname1 = varname2
See AlsoLeft Function, RSet Statement, Space Function

Use the LSet function as needed within your Visual Basic source code. If you use the second syntax of the LSet statement to copy one user-defined type variable to another, and the variables are not based on the same Type statement, fully document the purpose and impact of the copy in the source code comments.

LTrim Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string with leading spaces removed.
Typical SyntaxLTrim(string)
VariationsLTrim$ Function
See AlsoRTrim Function, Trim Function

Use the LTrim function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

LTrim(argument)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

LTrim$(argument)

Some Visual Basic programmers originally learned programming in languages that included functions equivalent to LTrim and RTrim, but did not have an equivalent to the Trim function. In such languages, you could perform a Trim by combining the LTrim and RTrim statements.

sClean = LTrim$(RTrim$(sOriginal))

Avoid this usage in Visual Basic; always use the Trim function to remove both leading and trailing spaces.

sClean = Trim$(sOriginal)

When using the LTrim$ version of this function, the argument cannot be Null. If you think that your code will allow a Null value to be passed to the LTrim$ function, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

sTitle = LTrim$(rsInfo!Title & "")

Me Keyword

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRefers to the local instance of a class.
Typical SyntaxMe

Use the Me keyword as needed within your Visual Basic source code. When you are working with multiple instances of a class, and you need to refer to the instance of the class from which the current code is executing, use Me to remove any instance ambiguity.

When writing code within a class module, such as a Form, use the Me keyword when referring to properties or methods of the class. However, avoid using the Me keyword when referring to subordinate objects or controls of the class.

Correct
sFormName = Me.Name
Me.MousePointer = vbHourglass
Me.Show vbModal
txtName.SetFocus

Incorrect
sFormName = Name
MousePointer = vbHourglass
Show vbModal
Me.txtName.SetFocus

Mid Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the middle portion of a string.
Typical SyntaxMid(string, start[, length])
VariationsMid$ Function, MidB Function, MidB$ Function
See AlsoLeft Function, Mid Statement, Right Function

Use the Mid function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Mid(arguments)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Mid$(arguments)

If you need to work with the underlying bytes contained within the original string, use the MidB function or the MidB$ function.

When using the Mid$ and MidB$ versions of this function, the first argument cannot be Null. If you think that your code will allow a Null value to be passed to the Mid$ or MidB$ function, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

' ----- Extract area code from (xxx) xxx-xxxx
sAreaCode = Mid$(rsInfo!Phone & "", 2, 3)

Never use the Mid function to obtain the leftmost or rightmost characters in a string. Use the Left function to extract the leftmost characters, or the Right function to extract the rightmost characters.

Incorrect
sAreaCode = Mid$(sPhone, 1, 3)

Correct
sAeaCode = Left$(sPhone, 3)

Mid Statement

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSets the middle portion of a string.
Typical SyntaxMid(stringvar, start[, length]) = string
VariationsMid$ Statement, MidB Statement, MidB$ Statement
See AlsoLeft Function, Mid Function, Right Function

In general, avoid the use of the Mid statement and its variants. The movement of the primary expression processing of a statement to the left side of the assignment is distracting at its best, and error-prone at its worst. If you feel that the use of the Mid statement is warranted in a specific coding situation, sufficiently document its use and purpose in the source code comments.

Be aware that the interpretation of the third argument in the Mid statement (the length argument) differs slightly from that of the Mid function's third argument. If you omit the third argument in the Mid statement, you are not indicating that the remainder of the string should be replaced (as you would expect from the use of the Mid function). Instead, you are saying, "replace characters with the new string up to the length of the new string, leaving trailing characters intact." The new string will also not be extended to accommodate a longer modification string. Including the third argument states that at most, length characters will be replaced.

If you need to work with the underlying bytes contained within the original string, use the MidB and MidB$ statements.

Minute Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the minute for a given date or time.
Typical SyntaxMinute(time)
See AlsoDatePart Function, Day Function, Hour Function, Month Function, Second Function, Year Function

Use the Minute function as needed within your Visual Basic source code. If you are using either Visual Basic or Visual Basic for Applications, and you will be using the minute returned from this function as a string (for example, to concatenate the minute onto an existing string), consider using the Format$ function instead.

sInfo = "Minute number " & Format$(dtAction, "n")

MIRR Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the modified internal rate of return for a series of periodic cash flows.
Typical SyntaxMIRR(values(), financerate, reinvestrate)
See AlsoDDB Function, FV Function, IPmt Function, IRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the MIRR function as needed within your Visual Basic source code. This function returns a Double value, and accepts several Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the MIRR function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the MIRR function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

MkDir Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCreates a new directory.
Typical SyntaxMkDir path
See AlsoChDir Statement, ChDrive Statement, CurDir Function, Dir Function, RmDir Function

Use the MkDir statement as needed within your Visual Basic source code. The argument supplied to the MkDir statement may be a local or mapped drive path, a UNC (Universal Naming Convention) path, or a path relative to the current drive and directory.

The MkDir statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the MkDir statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Mod Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDivides one number into another, and returns the remainder.
Typical Syntaxexpression1 Mod expression2
See Also- Operator (Binary), - Operator (Unary), & Operator, * Operator, / Operator, Operator, ^ Operator, + Operator (Assignment), = Operator (Assignment)

Use the Mod operator as needed within your Visual Basic source code. The second expression cannot be 0 (zero). If the second expression is supplied by the user, or if you think that the second expression may be zero, include appropriate code to test the second expression, and take corrective action when needed.

The Mod operator rounds the expressions before the division takes place. If you need to use a different system of rounding or fractional truncation, use the Fix function, the Int function, or the Round function on the expressions before passing those expressions to the Mod operator.

Month Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the month for a given date.
Typical SyntaxMonth(date)
See AlsoDatePart Function, Day Function, Hour Function, Minute Function, Second Function, Year Function

Use the Month function as needed within your Visual Basic source code. If you are using either Visual Basic or Visual Basic for Applications, and you will be using the month returned from this function as a string (for example, to concatenate the month onto an existing string), consider using the Format$ function instead.

sInfo = "Month number " & Format$(dtAction, "m")

MonthName Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the name of the month for a given date.
Typical SyntaxMonthName(month[, abbreviate])
VariationsMonthName$ Function
See AlsoWeekday Function, WeekdayName Function

Use the MonthName function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

MonthName(arguments)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

MonthName$(arguments)

MsgBox Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeDisplays a message to the user.
Typical SyntaxMsgBox(prompt[, buttons] [, title] [, helpfile, context] )
VariationsMsgBox Statement
See AlsoBeep Statement, InputBox Function

Use the MsgBox function as needed within your Visual Basic source code. Although the syntax of the MsgBox function allows most of the arguments to be excluded, always include the first three arguments (prompt, buttons, title). Use the same title text in every MsgBox function call throughout your application. You may wish to create a global constant with a short version of the application name to be used in the title of each message box.

Public Const PROGRAM TITLE = "Info Manager"

The buttons argument of the MsgBox function accepts Integer values, or combinations of a set of intrinsic Visual Basic constants. The return value also comes from a set of intrinsic constants. When available, always use the supplied constants instead of numeric literals. When combining constants, use the addition operator ( + ) to add the values together. Do not use the Or operator to combine the constants.

It is permissible to alter the syntax of the MsgBox function so that it becomes a MsgBox statement. The MsgBox statement has no return value, and never uses buttons other than the OK button.

nResult = MsgBox("I am the MsgBox function, all right?",  _
    vbYesNo + vbQuestion, PROGRAM TITLE)

MsgBox "I am the MsgBox statement.",  _
    vbOKOnly + vbInformation, PROGRAM_TITLE

Some of the constants used in the buttons argument indicate the names of the buttons that should appear on the message box. Always include at least one of these constants. Also, there are constants to indicate the icon that should display on the message box. One of these constants must also be included. All other constants are optional. In the simplest, least important message box, display the OK button and an informational icon.

MsgBox "All fields are up to date.",  
    vbOKOnly + vbInformation, PROGRAM TITLE

Name Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRenames a file or directory.
Typical SyntaxName oldpathname As newpathname
See AlsoFileCopy Statement, Kill Statement, MkDir Statement, RmDir Statement

Use the Name statement as needed within your Visual Basic source code. The arguments supplied to the Name statement may be local or mapped drive paths, UNC (Universal Naming Convention) paths, or paths relative to the current drive and directory.

The file or directory specified by the newpathname argument must not exist. If you think that the destination name may exist, remove it first with the Kill statement or the RmDir statement.

The Name statement (and all other File System features) accesses information that resides outside of the control of the Visual Basic application. Therefore, you must always use proper error handling in any procedure that uses the Name statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.

Not Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise negation operation.
Typical SyntaxNot expression
See AlsoAnd Operator, Eqv Operator, Imp Operator, Or Operator, Xor Operator.

Use the Not operator as needed within your Visual Basic source code. When writing complex statements that involve more than one logical or bitwise operator, use parentheses to indicate the proper precedence and grouping within the calculation.

When performing simple one-operator comparisons between two expressions, do not negate the result with the Not operator. Instead, use the inverse of the comparison operator to achieve the same result.

Incorrect
If Not (nFirst = nSecond) Then

Correct
If (nFirst <> nSecond) Then

Nothing Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates that an object variable is not associated with an instance of an object.
Typical SyntaxNothing
See AlsoEmpty Keyword, Is Operator, Null Keyword

Use the Nothing keyword as needed within your Visual Basic source code. Never test an expression by comparing it directly with the Nothing keyword. Always use the Is keyword of the If statement instead.

Incorrect
If (objStatus = Nothing) Then

Correct
If (objStatus Is Nothing) Then

Now Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the current system date and time.
Typical SyntaxNow
See AlsoDate Function, Date Statement, Time Function, Time Statement

Use the Now function as needed within your Visual Basic source code. Always use the Now function if you need to simultaneously retrieve both the date and time. Do not use the alternative method of adding the separate results of the Date function and the Time function.

Incorrect
dtCurrentTime = Date + Time

Correct
dtCurrentTime = Now

NPer Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the number of periods for an annuity.
Typical SyntaxNPer(rate, pmt, pv[, fv[, type]])
See AlsoDDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the NPer function as needed within your Visual Basic source code. This function returns a Double value, and accepts several Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

NPV Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the net present value of an investment.
Typical SyntaxNPV(rate, values())
See AlsoDDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function

Use the NPV function as needed within your Visual Basic source code. This function returns a Double value, and accepts Double values for parameters. While values based on the Currency data type are accurate to four decimal places, Double floating point values are subject to minor rounding errors. While you can convert the return value of the NPV function from Double to Currency using the CCur function, this result will be bound to the same rounding conditions of the value returned by the NPV function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.

Null Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIndicates that a variable or expression contains no valid data.
Typical SyntaxNull
See AlsoEmpty Keyword, IsNull Function, Nothing Keyword

Use the Null keyword as needed within your Visual Basic source code. Never test an expression by comparing it with the Null keyword. Always use the IsNull function instead.

Incorrect
If (rsInfo!OptionalInformation = Null) Then

Incorrect
If (IsNull(rsInfo!OptionalInformation)) Then

Commonly, database fields will contain Null values. However, many Visual Basic features, primarily string functions, do not accept Null values. Before using a potential Null value when a string is expected, concatenate an empty string onto the value.

sResponse = rsInfo!Response & ""

In Visual Basic and Visual Basic for Applications, you can use the Val function to convert potentially Null numeric values to a true numeric format.

nScore = Val(rsInfo!FinalScore & "")

Oct Function

CategoryConversion Functions, String Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns an octal representation of an expression, in string format.
Typical SyntaxOct(expression)
VariationsOct$ Function
See AlsoHex Function

Use the Oct function as needed within your Visual Basic source code. Visual Basic, Scripting Edition does not permit the use of the string version of this function. Within a VBScript code section, you must use the syntax

Oct(argument)

In all other versions of Visual Basic, if you do not require a Variant result, use the string version of this function instead of the Variant version.

Oct$(argument)

When using the Oct$ version of this function, the argument cannot be Null. If you think that your code will allow a Null value to be passed to the Oct$ function, force the argument to a string first. A quick way to convert a Null to a string is to concatenate an empty string onto the Null value.

sAccess = Oct$(rsInfo!AccessBits & "")

It is permissible to use the Empty value as an argument to either the Oct function or the Oct$ function.

On Error Statement

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeEnables error handling within a procedure.
Typical SyntaxOn Error GoTo line
 On Error Resume Next
 On Error GoTo 0
See AlsoErl Statement, Err Function, Err Object, Error Function, Error Statement, Resume Statement

Use the On Error statement as needed in your Visual Basic source code. In general, you should place an error handler in any procedure that accesses resources outside of the application itself. This includes access to file system objects, the Windows registry, databases, network connections, printers, and shared resources.

The On Error GoTo line version of this statement is not available within VBScript. To test for an error in VBScript, use the On Error Resume Next statement, then test the Err object after a statement that may cause an error.

On Error Resume Next

' ----- Query the database
Err.Clear
sSQL = "SELECT * FROM MyTable"
Set rsInfo = conData.Execute(sSQL)
If (Err <> 0) Then
    ' ----- An error occurred

For more information about error handlers, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.157