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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Begins a source code comment line or line section. |
Typical Syntax | ' comment |
See Also | Rem 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.
' ----- It is very important that you read this full _ ' comment so that you can be fully informed.
' ----- 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Subtracts one value from another. |
Typical Syntax | expression1 - 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates 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.
Category | Compiler Directives |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Defines 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.
Category | Compiler Directives |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Includes 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Concatenates two expressions. |
Typical Syntax | expression1 & 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Multiplies two values together. |
Typical Syntax | expression1 * 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Divides one number into another, and returns a floating point value. |
Typical Syntax | expression1 / 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Divides one number into another, and returns only the integer portion of the result. |
Typical Syntax | expression1 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Raises one value to the power of another value. |
Typical Syntax | expression1 ^ 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Adds one value to another. |
Typical Syntax | expression1 + 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value is less than another value. |
Typical Syntax | expression1 < 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value is less than or equal to another value. |
Typical Syntax | expression1 <= 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.
If (nFirst =< nSecond) Then
If (nFirst <= nSecond) Then
The use of the Option Compare statement can affect comparisons performed with the less than or equal to operator.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value does not equal another value. |
Typical Syntax | expression1 <> 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.
If (nFirst >< nSecond) Then
If (nFirst <> nSecond) Then
The use of the Option Compare statement can affect comparisons performed with the not equal operator.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Assigns an expression to a variable. |
Typical Syntax | variable = 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value equals another value. |
Typical Syntax | expression1 = 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.
If (DoWork() = True) Then
If (DoWork = True) Then
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value is greater than another value. |
Typical Syntax | expression1 > 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if one value is greater than or equal to another value. |
Typical Syntax | expression1 >= 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.
If (nFirst => nSecond) Then
If (nFirst >= nSecond) Then
The use of the Option Compare statement can affect comparisons performed with the greater than or equal to operator.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the passed value, converting negative values to positive if needed. |
Typical Syntax | Abs(expression) |
See Also | Fix Function, Int Function, Round Function, Sgn Function |
Use the Abs function as needed within your Visual Basic source code.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Obtains the address of a Visual Basic procedure for use as a callback function supplied through an API call. |
Typical Syntax | AddressOf procedurename |
See Also | Declare 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Performs a logical or bitwise conjunction operation. |
Typical Syntax | expression1 And expression2 |
See Also | Eqv 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:No, VBScript:No |
Purpose | Object that supplies information about the application. |
Typical Syntax | App |
Variations | Global.App Object |
See Also | Debug 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Activates an application's window. |
Typical Syntax | AppActivate title[, wait] |
See Also | SendKeys 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Builds and returns a Variant array. |
Typical Syntax | Array(arglist) |
See Also | IsArray 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the ANSI character code of a character. |
Typical Syntax | Asc(string) |
Variations | AscB Function, AscW Function |
See Also | Chr 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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the arctangent of a number. |
Typical Syntax | Atn(number) |
See Also | Cos 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Produces a "beep" sound. |
Typical Syntax | Beep |
See Also | MsgBox 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Identifies a procedure argument as being passed by reference. |
Typical Syntax | ByRef argument [ As type] |
See Also | AddressOf 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Identifies a procedure argument as being passed by value. |
Typical Syntax | ByVal argument [ As type] |
See Also | ByRef 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calls a function or subroutine, either locally or through an API call. |
Typical Syntax | [Call] name [([argumentlist])] |
See Also | Declare 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calls a procedure indirectly. |
Typical Syntax | CallByName(object, procedurename, calltype[, arguments()]) |
See Also | Declare 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Boolean data type. |
Typical Syntax | CBool(expression) |
See Also | CByte 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Byte data type. |
Typical Syntax | CByte(expression) |
See Also | CBool 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Currency data type. |
Typical Syntax | CCur(expression) |
Variations | @ Type Declaration Character |
See Also | CBool 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.
fcStartAmount = CCur(125.5)
fcStartAmount = 125.5@
Category | Conversion Functions, Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Date data type. |
Typical Syntax | CDate(expression) |
Variations | CVDate Function |
See Also | CBool 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Double data type. |
Typical Syntax | CDbl(expression) |
Variations | # Type Declaration Character |
See Also | CBool 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.
fdOffset = CDbl(15)
fdOffset = 15#
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Converts an expression to the Variant (Decimal) data type. |
Typical Syntax | CDec(expression) |
See Also | CBool 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Changes the current directory to a new location. |
Typical Syntax | ChDir path |
See Also | ChDrive 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.
ChDir " emp"
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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Changes the current drive to a new drive. |
Typical Syntax | ChDrive drive |
See Also | ChDir 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns one of a set of values based on an index. |
Typical Syntax | Choose(index, choice-1[, choice-2, ...[, choice-n]]) |
See Also | IIf 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a character based on an ANSI character code. |
Typical Syntax | Chr(charcode) |
Variations | Chr$ Function, ChrB Function, ChrB$ Function, ChrW Function, ChrW$ Function. |
See Also | Chr 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Integer data type. |
Typical Syntax | CInt(expression) |
Variations | % Type Declaration Character |
See Also | CBool 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Long data type. |
Typical Syntax | CLng(expression) |
Variations | & Type Declaration Character |
See Also | CBool 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.
lInitialLimit = CLng(1500)
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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Closes the specified open file. |
Typical Syntax | Close [#]filenumber |
See Also | Open 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the command-line arguments of the application session. |
Typical Syntax | Command |
Variations | Command$ Function |
See Also | App 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.
sParse = Command
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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Defines 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Provides a generic object type for controls. |
Typical Syntax | Dim varname As Control |
See Also | Dim 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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the cosine of an angle. |
Typical Syntax | Cos(number) |
See Also | Atn 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Creates a reference to an ActiveX object. |
Typical Syntax | CreateObject(class[, servername]) |
See Also | GetObject 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the Single data type. |
Typical Syntax | CSng(expression) |
Variations | ! Type Declaration Character |
See Also | CBool 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.
fdScale = CSng(39.39)
fdScale = 39.39!
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts an expression to the String data type. |
Typical Syntax | CStr(expression) |
See Also | CBool 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the current directory on the default or specified drive. |
Typical Syntax | CurDir[(drive)] |
Variations | CurDir$ Function |
See Also | ChDir 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Converts an expression to the Variant data type. |
Typical Syntax | CVar(expression) |
See Also | CBool 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.
Category | Conversion Functions |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Converts an expression to the Variant (Error) data type. |
Typical Syntax | CVErr(expression) |
See Also | CBool 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the current system date. |
Typical Syntax | Date |
Variations | Date$ Function |
See Also | Date 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Sets the current system date. |
Typical Syntax | Date = date |
See Also | Date 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a new date value based on an adjustment of another date. |
Typical Syntax | DateAdd(interval, number, date) |
See Also | CDate 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)
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a specified time interval between two dates or times. |
Typical Syntax | DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]]) |
See Also | DatePart 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating a portion of a given date or time. |
Typical Syntax | DatePart(interval, date[, firstdayofweek[, firstweekofyear]]) |
See Also | DateDiff 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.
To Return | Use the Function |
---|---|
Day | Day(date) |
Hour | Hour(date) |
Minute | Minute(date) |
Month | Month(date) |
Second | Second(date) |
Weekday | Weekday(date[,firstdayofweek]) |
Year | Year(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")
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a date based on individual year, month, and day values. |
Typical Syntax | DateSerial(year, month, day) |
See Also | DateAdd 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Converts a date expression to a Variant (Date) value. |
Typical Syntax | DateValue(date) |
See Also | CDate 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the day for a given date. |
Typical Syntax | Day(date) |
See Also | DatePart 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")
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the depreciation of an asset for a specific time period. |
Typical Syntax | DDB(cost, salvage, life, period[, factor]) |
See Also | FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Object that supplies debugging features. |
Typical Syntax | Debug |
See Also | App 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | References 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 Also | ByRef 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Assigns a default data type to declared objects that begin with a specific letter. |
Typical Syntax | DefBool 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 Also | Dim 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Removes application information from the Windows registry. |
Typical Syntax | DeleteSetting appname, section[, key] |
See Also | GetAllSettings 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a variable that is local in scope. |
Typical Syntax | Dim [WithEvents] varname[([subscripts] )] [As [New] type] |
See Also | Global 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns a file name that matches a pattern. |
Typical Syntax | Dir[(pathname[, attributes])] |
Variations | Dir$ Function |
See Also | ChDir 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Repeats a block of code until a specified condition is met. |
Typical Syntax | Do [{While | Until} condition] [statements] |
Loop | |
Do [statements] | |
Loop [{While | Until} condition] | |
See Also | Exit 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes (with limitations), VBScript:No |
Purpose | Yields execution to the operating system so that other application events can be processed. |
Typical Syntax | DoEvents |
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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates that a variable or value is uninitialized. |
Typical Syntax | Nothing |
See Also | IsEmpty 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.
If (vntBuild = Empty) Then
If (IsEmpty(vntBuild)) Then
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Halts program execution immediately. |
Typical Syntax | End |
See Also | End 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Ends a subordinate block of code. |
Typical Syntax | End Function |
End If | |
End Property | |
End Select | |
End Sub | |
End Type | |
End With | |
See Also | End 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Defines an enumerated data type. |
Typical Syntax | [Private | Public] Enum enumname membername [ = constantexpression] |
. . . | |
End Enum | |
See Also | Const 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Return the value of a system environment variable. |
Typical Syntax | Environ(envstring | number) |
Variations | Environ$ 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")
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Indicates whether or not the end of the specified file has been reached. |
Typical Syntax | EOF(filenumber) |
See Also | Loc 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Performs a logical or bitwise equivalence operation. |
Typical Syntax | expression1 Eqv expression2 |
See Also | And 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Clears the elements of an array, freeing memory if the array is dynamic. |
Typical Syntax | Erase arraylist |
See Also | Array 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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Identifies the approximate line number where an error occurred. |
Typical Syntax | Erl |
See Also | Debug 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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Object that contains properties and methods for error processing. |
Typical Syntax | Err |
See Also | Debug 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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the message of an error for a given error code. |
Typical Syntax | Error[(errornumber)] |
Variations | Error$ Function |
See Also | Debug 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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Simulates the generation of an error. |
Typical Syntax | Error errornumber |
See Also | Debug 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.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Evaluates a VBScript expression that is stored in a string. |
Typical Syntax | Eval(expression) |
See Also | Execute 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Declares an event. |
Typical Syntax | [Public] Event name [(arglist)] |
See Also | RaiseEvent 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.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Executes one or more statements stored in a string. |
Typical Syntax | Execute statement |
See Also | Eval 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.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Executes one or more statements stored in a string. |
Typical Syntax | ExecuteGlobal statement |
See Also | Eval 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Exits a loop or routine immediately. |
Typical Syntax | Exit Do |
Exit For | |
Exit Function | |
Exit Property | |
Exit Sub | |
See Also | Do...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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates e (the base of natural logarithms) raised to a power. |
Typical Syntax | Exp(number) |
See Also | Log 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Provides an intrinsic constant for the False Boolean value. |
Typical Syntax | False |
See Also | True 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the attributes of an open file. |
Typical Syntax | FileAttr(filenumber, returntype) |
See Also | FreeFile 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Copies a file from one location to another. |
Typical Syntax | FileCopy source, destination |
See Also | Kill 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the modification date and time of a file. |
Typical Syntax | FileDateTime(pathname) |
See Also | FileLen 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the number of bytes in a file. |
Typical Syntax | FileLen(pathname) |
See Also | FileDateTime 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns an array of strings that match or do not match a substring. |
Typical Syntax | Filter(inputstrings, value[, include[, compare]]) |
See Also | InStr 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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Truncates the fractional portion of an expression. |
Typical Syntax | Fix(expression) |
See Also | Abs 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Repeats a block of code for each element in a collection or array. |
Typical Syntax | For Each element In group [statements] |
Next [element] | |
See Also | Do...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.
For Each vntOuter In nOutArray For Each vntInner In nInArray Debug.Print vntOuter, vntInner Next vntInner, vntOuter
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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Repeats a block of code a specified number of times. |
Typical Syntax | For counter =start To end [ Step step] [statements] |
Next [counter] | |
See Also | Do...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.
For nOuter = 1 To 5 For nInner = 1 To 5 MsgBox nOuter, nInner Next nInner, nOuter
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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Formats an expression based on a description. |
Typical Syntax | Format(expression[, format[, firstdayofweek[, firstweekofyear]]]) |
Variations | Format$ Function |
See Also | FormatCurrency 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Formats an expression to look like a currency amount. |
Typical Syntax | FormatCurrency(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]]) |
See Also | Format 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Formats an expression to look like a date or time. |
Typical Syntax | FormatDateTime(expression[, format]) |
See Also | Format 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Formats an expression to look like a number. |
Typical Syntax | FormatNumber(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]]) |
See Also | Format 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Formats an expression to look like a percent. |
Typical Syntax | FormatPercent(expression[, decimaldigits[, leadingdigit[, negativeparens[, groupdigits]]]]) |
See Also | Format 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns an available number for use by the Open statement. |
Typical Syntax | FreeFile[(rangenumber)] |
See Also | Open 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.
' ----- Open the source file Open sSourceFile For Input As #1
Instead, use the FreeFile function to ensure a valid and available file number.
' ----- 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
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a function procedure. |
Typical Syntax | [Private | Public | Friend] [Static] Function name [(arglist)] [ As type] [statements] |
End Function | |
See Also | ByRef 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.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the future value of an annuity. |
Typical Syntax | FV(rate, nper, pmt[, pv[, type]]) |
See Also | DDB Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Reads data from a file and assigns the result to a variable. |
Typical Syntax | Get [#]filenumber, [recnumber], varname |
See Also | Open 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns an array of application settings from the Windows registry. |
Typical Syntax | GetAllSettings(appname, section) |
See Also | DeleteSetting 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the attributes of a file. |
Typical Syntax | GetAttr(pathname) |
See Also | FileAttr 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.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Identifies the current locale. |
Typical Syntax | GetLocale() |
See Also | SetLocale 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Retrieves a reference to an ActiveX object. |
Typical Syntax | GetObject([pathname] [, class]) |
See Also | CreateObject 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.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Gets a procedure reference for use with DHTML events. |
Typical Syntax | GetRef(procname) |
See Also | AddressOf Operator |
Use the GetRef function as needed within your Visual Basic source code.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns an application value from the Windows registry. |
Typical Syntax | GetSetting(appname, section, key[, default]) |
See Also | DeleteSetting 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Declares a variable that is global in scope. |
Typical Syntax | Global varname [ As type] |
See Also | Dim 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:No, VBScript:No |
Purpose | Object that supplies global methods and properties. |
Typical Syntax | Global |
See Also | App 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.
Global.Printer.EndDoc
Printer.EndDoc
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Continues execution at a specified line number or label, then returns to resume the original path of execution. |
Typical Syntax | GoSub line |
. . . | |
line: | |
. . . | |
Return | |
See Also | GoTo 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Continues execution at a specified line number or label. |
Typical Syntax | GoTo line |
See Also | GoSub...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.
Category | Conversion Functions, String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a hexadecimal representation of an expression, in string format. |
Typical Syntax | Hex(expression) |
Variations | Hex$ Function |
See Also | Oct 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the hour for a given date or time. |
Typical Syntax | Hour(time) |
See Also | DatePart 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")
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Executes blocks of code based on a condition. |
Typical Syntax | If 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.
If (nResult < RESULT_LIMIT) Then Else MsgBox "You went over the limit.", _ vbOKOnly + vbExclamation, "Notice" End If
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.
If (bGoodCredit) Then ' ----- Process order Else If (bLongTimeCustomer) Then ' ----- Process with warnings End If End If
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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns one of a set of values based on a Boolean expression. |
Typical Syntax | IIf(expression, truepart, falsepart) |
See Also | Choose 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Identifies the current Input Method Editor (IME) mode. |
Typical Syntax | IMEStatus |
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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Performs a logical or bitwise implication operation. |
Typical Syntax | expression1 Imp expression2 |
See Also | And 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Indicates that a specific interface or class will be implemented in a class module. |
Typical Syntax | Implements [interface | class] |
See Also | Class 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Reads data from a file and assigns the results to variables. |
Typical Syntax | Input #filenumber, varlist |
See Also | Input 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Reads characters from an open file. |
Typical Syntax | Input(number, [ #]filenumber) |
Variations | Input$ Function, InputB Function, InputB$ Function |
See Also | Get 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Prompts the user for data input. |
Typical Syntax | InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context]) |
Variations | InputBox$ Function |
See Also | MsgBox 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)
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the location of a sub-string within a larger string. |
Typical Syntax | InStr([start, ]string1, string2[, compare]) |
Variations | InStrB Function |
See Also | Filter 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the location of a sub-string within a larger string, searching from the end of the larger string. |
Typical Syntax | InStrRev(string1, string2[, start[, compare]) |
See Also | Filter 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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Truncates the fractional portion of an expression. |
Typical Syntax | Int(expression) |
See Also | Abs 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.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the interest payment for a given period of an annuity. |
Typical Syntax | IPmt(rate, per, nper, pv[, fv[, type]]) |
See Also | DDB 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.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the internal rate of return for a series of periodic cash flows. |
Typical Syntax | IRR(values()[, guess]) |
See Also | DDB Function, FV Function, IPmt Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Determines if two object variables refer to the same underlying object. |
Typical Syntax | object1 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether a variable is an array. |
Typical Syntax | IsArray(varname) |
See Also | Array 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether an expression is a valid date or time. |
Typical Syntax | IsDate(expression) |
See Also | CDate 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether a variable or expression is not yet initialized. |
Typical Syntax | IsEmpty(expression) |
See Also | Empty 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.
If (vntUserData = Empty) Then
If (IsEmpty(vntUserData)) Then
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Indicates whether an expression is an error value. |
Typical Syntax | IsError(expression) |
See Also | CVErr 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Indicates whether an optional argument was passed to the procedure. |
Typical Syntax | IsMissing(argument) |
See Also | IsArray 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.
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
Private Sub DoWork(Optional bWithEffort _ As Boolean = False) ' ----- Do a lot of work, or just a little
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether an expression is Null. |
Typical Syntax | IsNull(expression) |
See Also | IsArray 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.
If (rsInfo!OptionalInformation = Null) Then
If (IsNull(rsInfo!OptionalInformation)) Then
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether an expression is a valid number. |
Typical Syntax | IsNumeric(expression) |
See Also | CCur 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates whether a variable is an object. |
Typical Syntax | IsObject(varname) |
See Also | CreateObject 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Joins an array of strings together to form a single string. |
Typical Syntax | Join(list[, delimiter]) |
Variations | Join$ 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)
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Deletes a file. |
Typical Syntax | Kill pathname |
See Also | Dir 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the lower numeric bound of an array dimension. |
Typical Syntax | LBound(arrayname[, dimension]) |
See Also | Erase 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string converted to lower case. |
Typical Syntax | LCase(string) |
Variations | LCase$ Function |
See Also | UCase 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 & "")
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the left portion of a string. |
Typical Syntax | Left(string, length) |
Variations | Left$ Function, LeftB Function, LeftB$ Function |
See Also | Mid 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)
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the length of a string or string variable. |
Typical Syntax | Len(string | varname) |
Variations | LenB 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 & "")
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Assigns 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Determines if one string matches a pattern. |
Typical Syntax | string 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Reads a single line from an open sequential file. |
Typical Syntax | Line Input #filenumber, varname |
See Also | Input # 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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Creates an instance of a form or control. |
Typical Syntax | Load object |
See Also | Unload Statement |
Use the Load statement as needed within your Visual Basic source code.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Loads a graphic into a picture-bearing object. |
Typical Syntax | LoadPicture([filename], [size], [colordepth], [x, y] ) |
See Also | LoadResData 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Loads data from a resource file. |
Typical Syntax | LoadResData(index, format) |
See Also | LoadPicture 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.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Loads a bitmap, icon, or cursor from a resource file. |
Typical Syntax | LoadResPicture(index, format) |
See Also | LoadPicture 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.
Category | Miscellaneous Features, String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Loads a string from a resource file. |
Typical Syntax | LoadResString(index) |
See Also | LoadPicture 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the current position in an open file. |
Typical Syntax | Loc(filenumber) |
See Also | EOF 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Locks a portion or all of an open file. |
Typical Syntax | Lock [#]filenumber[, recordrange] |
See Also | Open 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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the length in bytes of an open file. |
Typical Syntax | LOF(filenumber) |
See Also | EOF 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.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the natural logarithm of a number. |
Typical Syntax | Log(number) |
See Also | Exp 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Left 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 Syntax | LSet stringvar = string |
LSet varname1 = varname2 | |
See Also | Left 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.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string with leading spaces removed. |
Typical Syntax | LTrim(string) |
Variations | LTrim$ Function |
See Also | RTrim 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 & "")
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Refers to the local instance of a class. |
Typical Syntax | Me |
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.
sFormName = Me.Name Me.MousePointer = vbHourglass Me.Show vbModal txtName.SetFocus
sFormName = Name MousePointer = vbHourglass Show vbModal Me.txtName.SetFocus
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the middle portion of a string. |
Typical Syntax | Mid(string, start[, length]) |
Variations | Mid$ Function, MidB Function, MidB$ Function |
See Also | Left 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.
sAreaCode = Mid$(sPhone, 1, 3)
sAeaCode = Left$(sPhone, 3)
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Sets the middle portion of a string. |
Typical Syntax | Mid(stringvar, start[, length]) = string |
Variations | Mid$ Statement, MidB Statement, MidB$ Statement |
See Also | Left 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the minute for a given date or time. |
Typical Syntax | Minute(time) |
See Also | DatePart 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")
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the modified internal rate of return for a series of periodic cash flows. |
Typical Syntax | MIRR(values(), financerate, reinvestrate) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Creates a new directory. |
Typical Syntax | MkDir path |
See Also | ChDir 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Divides one number into another, and returns the remainder. |
Typical Syntax | expression1 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.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the month for a given date. |
Typical Syntax | Month(date) |
See Also | DatePart 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")
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the name of the month for a given date. |
Typical Syntax | MonthName(month[, abbreviate]) |
Variations | MonthName$ Function |
See Also | Weekday 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)
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Displays a message to the user. |
Typical Syntax | MsgBox(prompt[, buttons] [, title] [, helpfile, context] ) |
Variations | MsgBox Statement |
See Also | Beep 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
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Renames a file or directory. |
Typical Syntax | Name oldpathname As newpathname |
See Also | FileCopy 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.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Performs a logical or bitwise negation operation. |
Typical Syntax | Not expression |
See Also | And 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.
If Not (nFirst = nSecond) Then
If (nFirst <> nSecond) Then
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates that an object variable is not associated with an instance of an object. |
Typical Syntax | Nothing |
See Also | Empty 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.
If (objStatus = Nothing) Then
If (objStatus Is Nothing) Then
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the current system date and time. |
Typical Syntax | Now |
See Also | Date 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.
dtCurrentTime = Date + Time
dtCurrentTime = Now
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the number of periods for an annuity. |
Typical Syntax | NPer(rate, pmt, pv[, fv[, type]]) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the net present value of an investment. |
Typical Syntax | NPV(rate, values()) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
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.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Indicates that a variable or expression contains no valid data. |
Typical Syntax | Null |
See Also | Empty 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.
If (rsInfo!OptionalInformation = Null) Then
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 & "")
Category | Conversion Functions, String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns an octal representation of an expression, in string format. |
Typical Syntax | Oct(expression) |
Variations | Oct$ Function |
See Also | Hex 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.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Enables error handling within a procedure. |
Typical Syntax | On Error GoTo line |
On Error Resume Next | |
On Error GoTo 0 | |
See Also | Erl 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.
18.219.239.118