Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Branches to one or more code sections based on an expression. |
Typical Syntax | On expression GoSub destinationlist |
See Also | Choose Function, GoSub Statement, GoTo Statement, IIf Function, On...GoTo Statement, Resume Statement, Select Case Statement |
Do not use the On...GoSub statement within your Visual Basic source code. Usage of this statement can result in subtle errors, maintenance difficulties, and debugging nightmares. Use a Select Case statement instead to redirect your procedure based on an expression value.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Branches to one or more code sections based on an expression. |
Typical Syntax | On expression GoTo destinationlist |
See Also | Choose Function, GoSub Statement, GoTo Statement, IIf Function, On...GoSub Statement, Resume Statement, Select Case Statement |
Do not use the On...GoTo statement within your Visual Basic source code. Usage of this statement can result in subtle errors, maintenance difficulties, and debugging nightmares. Use a Select Case statement instead to redirect your procedure based on an expression value.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Opens a file for input or output. |
Typical Syntax | Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength] |
See Also | Close Statement, EOF Function, FileAttr Function, FreeFile Statement, Get Statement, Input Function, Input # Statement, Line Input # Statement, Loc Function, Lock # Statement, LOF Function, Print # Statement, Put Statement, Seek Function, Seek Statement, Unlock # Statement, Width # Statement, Write # Statement |
Use the Open statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Open statement. If you are opening a file for modification or replacement, make sure you sufficiently inform the user that the file will be changed, either through documentation or through application notification.
The Open 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 Open 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 | Indicates the default lower bound for all declared arrays. |
Typical Syntax | Option Base {0 | 1} |
See Also | Dim Statement, Option Compare Statement, Option Explicit Statement, Option Private Statement, Private Statement, Public Statement, ReDim Statement |
Do not use the Option Base statement within your Visual Basic source code. Instead, indicate the lower and upper bound of every declared array using the To clause of the Dim statement, the Private statement, the Public statement, and the ReDim statement. In Visual Basic, Scripting Edition, the lower bound of every array dimension is always 0 (zero).
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Indicates the type of comparison used within a source code module. |
Typical Syntax | Option Compare {Binary | Text | Database} |
See Also | Option Base Statement, Option Explicit Statement, Option Private Statement |
Use the Option Compare statement as needed within your Visual Basic source code. If you use this statement in one module, include the statement in all modules within your application, and specify the same option type in every module. If you need to have one module that varies from the other modules in the use of this statement, indicate clearly the reason for the deviation in the source code comments.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Requires all variables and constants to be declared before use. |
Typical Syntax | Option Explicit |
See Also | Option Base Statement, Option Compare Statement, Option Private Statement |
The Option Explicit statement must appear as the first non-comment statement in every module in your Visual Basic and Visual Basic for Applications source code. It must also appear as the first non-comment line of every Visual Basic script file, unless that file will be included or inserted into a parent VBScript file.
For more information about the Option Explicit statement, and declaration in general, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Category | Declaration Features |
Availability | VB:Yes (with restrictions), VBA:Yes, VBScript:No |
Purpose | Limits references to a module's contents from being accessed outside of the project. |
Typical Syntax | Option Private Module |
See Also | Option Base Statement, Option Compare Statement, Option Explicit Statement |
Use the Option Private statement as needed within your Visual Basic for Applications source code. Although this statement can be used within standard Visual Basic code, it has no effect on the application. Therefore, use it only within Visual Basic for Applications source code.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Identifies a procedure argument as optional. |
Typical Syntax | Optional [ByVal | ByRef] [ParamArray] varname[(þ)] [As type] [= defaultvalue] |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, IsMissing Function, ParamArray Keyword, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement |
Use the Optional keyword as needed within your Visual Basic source code. As with non-optional arguments, always supply the data type with the As clause, and include the ByVal keyword if needed. If you wish to use the IsMissing function with an optional argument, the data type of the argument must be declared as Variant.
Category | Operators |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Performs a logical or bitwise disjunction operation. |
Typical Syntax | expression1 Or expression2 |
See Also | And Operator, Eqv Operator, Imp Operator, Not Operator, Xor Operator. |
Use the Or 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 | Provides a mechanism for the caller of a procedure to send a variable number of arguments. |
Typical Syntax | ParamArray varname[ ( )] [As type] |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, LBound Function, Optional Keyword, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement, UBound Function |
Use the ParamArray keyword as needed within your Visual Basic source code. Only one ParamArray argument can appear in your argument list, and it must be the last argument. Include a description of the expected parameters that the calling routine might send as part of the initial procedure comment.
You cannot use the IsMissing function to test for the absence of any ParamArray arguments. Instead, test the upper and lower bounds of the array. When no parameters are sent for the ParamArray argument, the upper bound of the array will be lower than the lower bound.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Identifies the element in a series of ranges in which a value appears. |
Typical Syntax | Partition(number, start, stop, interval) |
Use the Partition function as needed within your Visual Basic source code. In general, the Partition function is used to perform grouping within a SQL query destined for the Microsoft Jet engine. When using the Partition function for other purposes, include sufficient documentation in your source code comments to explain your particular usage of the returned ranges.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the payment for an annuity. |
Typical Syntax | Pmt(rate, nper, pv[, fv[, type]]) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, PPmt Function, PV Function, Rate Function, SLN Function, SYD Function |
Use the Pmt 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 Pmt 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 Pmt 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 principal payment for an annuity. |
Typical Syntax | PPmt(rate, per, nper, pv[, fv[, type]]) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PV Function, Rate Function, SLN Function, SYD Function |
Use the PPmt 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 PPmt 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 PPmt 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 | Outputs text to a sequential file. |
Typical Syntax | Print #filenumber, [outputlist] |
See Also | Input Function, Line Input # Statement, Open Statement, Spc Function, Tab Function, Write # Statement |
Use the Print # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Print # statement. If you wish to output data in a delimited format to be read later by your application, use the Write # statement instead.
Do not forget to include the "#" character in the syntax of the Print statement. Omitting the "#" character is valid when the code appears in a form's code module. The statement will print all values onto the form background.
The Print # 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 Print # 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 (with restrictions) |
Purpose | Declares a variable that is "module-level" in scope. |
Typical Syntax | Private [WithEvents] varname[([subscripts])] [As [New] type] |
See Also | Dim Statement, Global Statement, Public Statement, Static Statement |
Use the Private statement as needed within the Declarations section 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 Private 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 Private statement.
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.
Private variables use the Hungarian naming conventions. All private variables begin with the "m" Hungarian prefix to indicate that they are module-level in scope.
For more information about private variables and the Hungarian naming conventions, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a property retrieval procedure. |
Typical Syntax | [Private | Public | Friend] [Static] Property Get name |
[(arglist)] [As type] | |
[statements] | |
End Property | |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, Optional Keyword, ParamArray Keyword, Property Let Statement, Property Set Statement, Sub Statement |
Use the Property Get 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 procedure, still follow the property 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 property declaration with the data type of the return value, using the final As clause. (These last two rules do not apply to VBScript procedures.)
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 Property Get statement. If you want to include static local variables within your procedure, 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 | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a property assignment procedure. |
Typical Syntax | [Private | Public | Friend] [Static] Property Letname |
([arglist,] value) | |
[statements] | |
End Property | |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, Optional Keyword, ParamArray Keyword, Property Get Statement, Property Set Statement, Sub Statement |
Use the Property Let statement as needed within your Visual Basic source code. Always start the declaration with the Friend, Public, or Private keyword. Supply the appropriate data type with the As clause on each argument. (This last rule does not apply to VBScript procedures.)
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 Property Let statement. If you want to include static local variables within your procedure, 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 | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares an object property assignment procedure. |
Typical Syntax | [Private | Public | Friend] [Static] Property Setname([arglist,] reference) [statements] |
End Property | |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, Optional Keyword, ParamArray Keyword, Property Get Statement, Property Let Statement, Sub Statement |
Use the Property Set statement as needed within your Visual Basic source code. Always start the declaration with the Friend, Public, or Private keyword. Supply the appropriate data type with the As clause on each argument in arglist. (This last rule does not apply to VBScript procedures.)
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 Property Set statement. If you want to include static local variables within your procedure, 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 | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a variable that is global in scope. |
Typical Syntax | Public [WithEvents] varname[([subscripts] )] [As [New] type] |
See Also | Dim Statement, Global Statement, Private Statement, Static Statement |
Use the Public statement as needed within the Declarations section 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 Public 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 Public statement. Generally, it will not be necessary to declare a Public variable in VBScript.
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.
Public variables use the Hungarian naming conventions. All public variables begin with the "g" Hungarian prefix to indicate that they are global in scope.
For more information about public variables and the Hungarian naming conventions, Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Writes data from a variable to an open file. |
Typical Syntax | Put [#] filenumbeyr, [recnumber], varname |
See Also | Get Statement, Open Statement, Seek Statement |
Use the Put statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Put 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 Put 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 Put statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the present value of an annuity. |
Typical Syntax | PV(rate, nper, pmt[, fv[, type]]) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, Rate Function, SLN Function, SYD Function |
Use the PV 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 PV 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 PV function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns an RGB color based on a "color number." |
Typical Syntax | QBColor(color) |
See Also | RGB Function |
Do not use the QBColor function within your Visual Basic source code. Visual Basic now provides intrinsic constants that represent many common colors, plus constants that identify user modifiable system colors. If you need to use one of the colors generated by the QBColor function for which Visual Basic does not provide a suitable constant, generate the color value with the RBG function instead.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Raises an event declared with the Event statement. |
Typical Syntax | RaiseEvent eventname [ (argumentlist)] |
See Also | Event Statement |
Use the RaiseEvent statement as needed within your Visual Basic source code. Document any special concerns or assumptions in the source code comments when using the RaiseEvent statement, especially if multiple event interactions can cause unpredictable results.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Initializes the random number generator with a seed value. |
Typical Syntax | Randomize [number] |
See Also | Rnd Function |
Use the Randomize statement as needed within your Visual Basic source code. Only use the number argument if you need to record or create a consistent "random" sequence. Without the argument, the default action of the Randomize statement is to use the system timer to provide the seed value. Do not initialize the random number generator with the system clock value.
Randomize Timer
Randomize
If you wish to repeat a specific series of random numbers, you must first use the Rnd function with a negative argument, then call the Randomize statement with a numeric argument that you will use each time. If you do not immediately precede the Randomize call with a call to the Rnd function using a negative argument, a new, unique random sequence will occur.
' ----- In the Declarations section Public Const STANDARD_SEED = 150 ' ----- Later, in a routine Call Rnd(-1) Randomize STANDARD_SEED
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the interest rate per period of an annuity. |
Typical Syntax | Rate(nper, pmt, pv[, fv[, type[, guess]]]) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, SLN Function, SYD Function |
Use the Rate 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 Rate 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 Rate 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 (with restrictions) |
Purpose | Reallocates an array dynamically to increase or decrease storage. |
Typical Syntax | ReDim [Preserve] varname(subscripts) [As type] |
See Also | Dim Statement, Global Statement, LBound Function, Private Statement, Public Statement, Static Statement, UBound Function |
Use the ReDim statement as needed within your Visual Basic source code. Do not place more than one variable declaration within a single ReDim statement. Place each variable declaration on a separate source code line.
When you create a dynamic array variable for use with the ReDim statement, decide how many array dimensions it will have, and never alter that number. If you use an array with two dimensions, never give it one, three, four, or more dimensions.
In Visual Basic and Visual Basic for applications, always use the To keyword when defining the ranges of each dimension in the array. Always specify both the lower and upper bounds for each dimension, both during the initial use of the ReDim statement, and on any subsequent uses. This rule does not apply to VBScript, since the lower bound is always 0 (zero) for every dimension.
ReDim maElements(nNewElement)
ReDim maElements(1 To nNewElement)
For more information about array variables and the Hungarian naming conventions, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Begins a source code comment line or line section. |
Typical Syntax | Rem comment |
See Also | ' Comment Operator |
Do not use the Rem statement in your source code. When adding comments to your source code, always use the comment operator (þ'þ).
For full information on the use and style of comments within your source code, see Chapter 3, Commenting and style.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Replaces one sub-string with another sub-string in a larger string. |
Typical Syntax | Replace(expression, find, replacewith[, start[, count[, compare]]] ) |
Variations | Replace$ Function |
See Also | Filter Function, InStr Function, InStrRev Function, Join Function, Option Compare Statement, Split Function |
Use the Replace 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
Replace(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.
Replace$(argument)
When using the Replace$ version 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 Replace$ 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.
sFields = Replace$(rsInfo!FieldTitles & "", ",", vbTab)
The compare argument of the Replace 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 Replace function.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Closes all open files. |
Typical Syntax | Reset |
See Also | Close Statement, Open Statement |
Do not use the Reset statement in your Visual Basic source code as a standard method for closing files. Always close each open file with a Close statement. However, if you need to immediately close all files in response to a fatal error in your application, it is permissible to use the Reset statement.
The Reset 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 Reset statement. Make use of the On Error statement to capture any file handling errors, and take the appropriate corrective action.
Category | Error Handling and Debugging Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Resumes execution of a procedure after error handling in an On Error statement. |
Typical Syntax | Resume [0] |
Resume Next | |
Resume line | |
See Also | Err Object, Exit Statement, On Error Statement |
Use the Resume statement as needed within your Visual Basic source code. When using the first syntax to resume execution with the line or procedure call that caused the error, exclude the optional "0" argument.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value for a color based on distinct red, green, and blue values. |
Typical Syntax | RGB(red, green, blue) |
See Also | QBColor Function |
Use the RBG function as needed within your Visual Basic source code. The Long value returned by this function stores each color value in a mathematically distinct section of the number, and each of the original values can be extracted from the new single value. Interestingly, the three color values are reversed in the combined Long value, so that they appear in blue, green, red order. Use the following calculations to extract the original red, green, and blue color values.
' ----- Extract red, green, and blue nRed = lColor Mod &H100 nGreen = (lColor &H100) Mod &H100 nBlue = lColor &H10000
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the right portion of a string. |
Typical Syntax | Right(string, length) |
Variations | Right$ Function, RightB Function, RightB$ Function |
See Also | Left Function, Mid Function |
Use the Right 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
Right(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.
Right$(arguments)
If you need to work with the underlying bytes contained within the original string, use the RightB and RightB$ functions.
When using the Right$ and RightB$ 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 Right$ or RightB$ 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 state abbreviation from City, ST sState = Right$(rsInfo!CityState & "", 2)
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Deletes a directory. |
Typical Syntax | RmDir path |
See Also | ChDir Statement, ChDrive Statement, CurDir Function, Dir Function, Kill Statement, MkDir Function |
Use the RmDir statement as needed within your Visual Basic source code. The argument supplied to the RmDir 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 directory to be removed by the RmDir statement must not contain any files or subordinate directories. If the directory to be removed is a user directory, make sure you sufficiently inform the user that the directory will be deleted, either through documentation or through application notification.
The RmDir 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 RmDir statement. 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 | Generates a pseudo-random number. |
Typical Syntax | Rnd[(number)] |
See Also | Randomize Statement |
Use the Rnd function as needed within your Visual Basic source code. To generate a random number between a specific lower and upper bound, inclusive, use the following formula:
Int((nUpper - nLower + 1) * Rnd + nLower)
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Rounds a value to a specific number of decimal places. |
Typical Syntax | Round(expression[, numdecimalplaces]) |
See Also | Abs Function, Fix Function, Int Function, Sgn Function |
Use the Round function as needed within your Visual Basic source code. To round a value to an integer (that is, no decimal places), omit the optional numdecimalplaces argument.
When the most significant decimal place to be truncated is a 5, and is followed by only zeros, the Round function rounds up when the next significant digit (the digit to the left) is odd, and rounds down when the next significant digit is even. That is, rounding 34.5 to zero decimal places results in 34, but rounding 35.5 results in 36. Rounding −34.5 similarly results in −34, while rounding −35.5 gives −36.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Right aligns a string within a string variable. |
Typical Syntax | RSet stringvar = string |
See Also | LSet Statement, Right Function, Space Function |
Use the RSet function as needed within your Visual Basic source code.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string with trailing spaces removed. |
Typical Syntax | RTrim(string) |
Variations | RTrim$ Function |
See Also | LTrim Function, Trim Function |
Use the RTrim 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
RTrim(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.
RTrim$(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 RTrim$ 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 RTrim$ 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.
sFlushRight = RTrim$(rsInfo!Message & "")
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Saves a graphic to a file. |
Typical Syntax | SavePicture picture, pathname |
See Also | LoadPicture Function, LoadResData Function, LoadResPicture Function, LoadResString Function |
Use the SavePicture statement as needed within your Visual Basic source code. The SavePicture 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 SavePicture statement. 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 | Saves application information in the Windows registry. |
Typical Syntax | SaveSetting appname, section, key, setting |
See Also | DeleteSetting Statement, GetAllSettings Function, GetSetting Function |
Use the SaveSetting 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 SaveSetting 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 SaveSetting statement. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:No, VBScript:No |
Purpose | Object that supplies screen and display related properties. |
Typical Syntax | Screen |
See Also | App Object, Debug Object, Global Object |
Use the Screen 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 Screen object.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Returns the name of the engine processing the VBScript code. |
Typical Syntax | ScriptEngine |
See Also | ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function |
Use the ScriptEngine function as needed within your VBScript source code.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Returns the build version number of the engine processing the VBScript code. |
Typical Syntax | ScriptEngineBuildVersion |
See Also | ScriptEngine Version, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function |
Use the ScriptEngineBuildVersion function as needed within your VBScript source code.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Returns the major version number of the engine processing the VBScript code. |
Typical Syntax | ScriptEngineMajorVersion |
See Also | ScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMinorVersion Function |
Use the ScriptEngineMajorVersion function as needed within your VBScript source code.
Category | Miscellaneous Features |
Availability | VB:No, VBA:No, VBScript:Yes |
Purpose | Returns the minor version number of the engine processing the VBScript code. |
Typical Syntax | ScriptEngineMinorVersion |
See Also | ScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function |
Use the ScriptEngineMinorVersion function as needed within your VBScript source code.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the second for a given date or time. |
Typical Syntax | Second(time) |
See Also | DatePart Function, Day Function, Hour Function, Minute Function, Month Function, Year Function |
Use the Second 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 seconds returned from this function as a string (for example, to concatenate the second onto an existing string), consider using the Format$ function instead.
sInfo = "Second number " & Format$(dtAction, "s")
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns the current position in an open file. |
Typical Syntax | Seek(filenumber) |
See Also | EOF Function, Loc Function, LOF Function, Open Statement, Seek Statement |
Use the Seek function as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Seek function.
Using the Seek function on a file opened in Append, Binary, Input, or Output mode returns the current byte position. However, the Seek function returns the current record number when used on a file opened in Random mode.
When determining the current location in a file opened in Append, Input, or Output mode, use the Seek function instead of the Loc function.
The Seek 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 Seek 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 | Sets the current position in an open file. |
Typical Syntax | Seek [#]filenumber, position |
See Also | EOF Function, Loc Function, LOF Function, Open Statement, Seek Function |
Use the Seek statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as the first argument to the Seek statement. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.
The minimum file position is 1 (one). If you specify a position that is greater than the current length of a writeable file, the next write operation will extend the file to that length.
The Seek 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 Seek 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:Yes (with restrictions) |
Purpose | Executes one of several blocks of code based on an expression. |
Typical Syntax | Select Case expression |
[Case expressionlist-n | |
[statements]]... | |
[Case Else | |
[statements]] | |
End Select | |
See Also | Choose Function, If...Then...Else Statement, Switch Function |
Use the Select Case statement as needed within your Visual Basic source code. Note that the VBScript version of the Select Case statement puts restrictions on the types of expressions that can occur in individual Case expression lists.
Do not use a GoTo statement to jump inside of the Select Case statement. Also, do not use a GoTo statement to jump from one Case section to another. If two Case sections need to share a section of code, include them in the same Case section, then use an If...Then...Else statement within the section to differentiate between the different process activities. You might also consider using the GoSub statement, or calling a procedure, to process the common parts of two or more Case sections.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Sends keystrokes to the active window. |
Typical Syntax | SendKeys string[, wait] |
See Also | AppActivate Statement, DoEvents Statement, Shell Function |
Do not use the SendKeys statement to perform actions on the forms of your application. Instead, implement the needed features using code logic.
' ----- Click on the action button cmdAction.SetFocus SendKeys "%A"
' ----- Click on the action button cmdAction_Click
Use the SendKeys statement to send keystrokes only to windows in other applications.
The SendKeys statement may access 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 SendKeys 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 |
Purpose | Assigns an object reference to an object variable. |
Typical Syntax | Set objectvar = {[ New] objectexpression | Nothing} |
See Also | = Operator (Assignment), Nothing Keyword, Property Set Statement |
Use the Set statement as needed within your Visual Basic source code. When you have many object variables referring to the same instance of an object, document any potential conflicts that may result from such multiple references in your source code comments.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Sets the attributes of a file. |
Typical Syntax | SetAttr pathname, attributes |
See Also | FileAttr Function, GetAttr Function |
Use the SetAttr statement as needed within your Visual Basic source code. The first argument supplied to the SetAttr 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 attributes argument to the SetAttr statement accepts an Integer value, or a combination of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. When combining multiple constants, use either the addition operator ( + ) or the Or operator.
The SetAttr 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 SetAttr 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:No, VBA:No, VBScript:Yes |
Purpose | Sets a new locale while identifying the previous locale. |
Typical Syntax | SetLocale(lcid) |
See Also | GetLocale Function |
Use the SetLocale function as needed within your Visual Basic source code. Visual Basic does not define a set of constants for the lcid (Locale ID). However, you may wish to declare a constant for the Locale IDs that you use within your application.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns -1, 0, or 1, depending on the sign of the passed expression. |
Typical Syntax | Sgn(expression) |
See Also | Abs Function, Fix Function, Int Function, Round Function |
Use the Sgn function as needed within your Visual Basic source code.
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Runs another program, and returns the task ID if successful. |
Typical Syntax | Shell(pathname[, windowstyle]) |
See Also | AppActivate Statement, SendKeys Statement |
Use the Shell function as needed within your Visual Basic source code. The pathname argument supplied to the Shell 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. You can also include command-line arguments accepted by the new program.
While the windowstyle argument is optional, it should always be supplied to avoid the default non-user-friendly "minimized with focus" startup method. The windowstyle argument to the Shell 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 Shell 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 Shell function. Make use of the On Error statement to capture any errors, and take the appropriate corrective action.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the sine of an angle. |
Typical Syntax | Sin(number) |
See Also | Atn Function, Cos Function, Tan Function |
Use the Sin 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 | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the straight-line depreciation of an asset for one period. |
Typical Syntax | SLN(cost, salvage, life) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SYD Function |
Use the SLN function as needed within your Visual Basic source code. This function returns a Double value, and accepts all 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 SLN 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 SLN function. Take care to check the accuracy of the return values when using the Visual Basic intrinsic financial functions.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string of space characters repeated a specified number of times. |
Typical Syntax | Space(number) |
Variations | Space$ Function |
See Also | Spc Function, String Function |
Use the Space 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
Space(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.
Space$(argument)
Do not use the Space function to generate extremely short runs of spaces (say, 1 to 5 characters in length). Use literal strings or constants instead.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Positions output when using the Print # statement. |
Typical Syntax | Spc(number) |
See Also | Print # Statement, Space Function, Tab Function |
Use the Spc function as needed within your Visual Basic source code. Depending on your usage of the Print # statement (and other similar Print methods), you may achieve better spacing results by using either the Space function or the Tab function.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns an array of strings extracted from a larger string based on a delimiter. |
Typical Syntax | Split(expression[, delimiter[, count[, compare]]] ) |
See Also | InStr Function, InStrRev Function, Join Function, Option Compare Statement |
Use the Split function as needed within your Visual Basic source code. The compare argument to the Split 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 use of the Option Compare statement can affect the Split function.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the square root of a number. |
Typical Syntax | Sqr(number) |
See Also | Exp Function, Log Function |
Use the Sqr 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 Sqr function must be greater than or equal to 0 (zero). If the value you pass to the Sqr function is supplied by the user, and the value falls outside of the valid range, either correctly handle the error raised by the Sqr function, or reject the value entered by the user.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Declares a variable that is local in scope, but maintains its data throughout the life of the application. |
Typical Syntax | Static varname[ ([subscripts])] [As [New] type] |
See Also | Dim Statement, Global Statement, Private Statement, Public Statement |
Use the Static 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 Static statement. Place each variable declaration on a separate source code line.
Static variables use the Hungarian naming conventions. All static variables begin with the "x" Hungarian prefix to indicate that they are local in scope and static in persistence.
For more information about static variables and the Hungarian naming conventions, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Visual Basic allows you to mark all variables local to a routine as static by including the optional Static keyword in the procedure definition. Do not use this feature to identify static variables. Instead, declare each static variable within a routine using the Static statement.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Pauses or halts program execution immediately. |
Typical Syntax | Stop |
See Also | End Statement |
In a compiled application, use the End statement instead of the Stop statement to halt application execution. In general, the Stop statement should never be used within your Visual Basic application. However, if you are performing some complex debugging, and it is too cumbersome to continually establish breakpoints throughout your source code, it is reasonable to include the Stop statement at key locations within the code.
The Stop statement is available in Visual Basic, Scripting Edition. However, it is only useful with debugging tools such as the Windows Script Debugger.
Always mark your Stop statements with an appropriate When comment. (When comments are discussed in Chapter 3, Commenting and Style.)
Stop ' !!! Remove after debugging
Category | Conversion Functions, String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Converts a number to the String data type. |
Typical Syntax | Str(number) |
Variations | Str$ Function |
See Also | CStr Function, StrConv Function, Val Function |
Do not use the Str function, or its Str$ variation, within your source code. Use the CStr function instead.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Compares two string values. |
Typical Syntax | StrComp(string1, string2[, compare]) |
See Also | < Operator, <= Operator, <> Operator (Comparison), = Operator (Comparison), > Operator, >= Operator, Is Operator, Like Operator, Not Operator, Option Compare Statement |
Use the StrComp function as needed within your Visual Basic source code. The use of the Option Compare statement can affect comparisons performed with the StrComp function. The compare argument to the StrComp 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.
Category | Conversion Functions, String Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Converts a string to a different format. |
Typical Syntax | StrConv(string, conversion[, lcid]) |
See Also | Chr Function, CStr Function, Str Function, Val Function |
Use the StrConv function as needed within your Visual Basic source code. However, if you only need to convert a single-byte character string in the local language to upper or lower case, use the UCase function or the LCase function instead.
The conversion argument to the StrConv function accepts an Integer value, or a combination of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. You may also wish to declare a constant for the lcid (Locale ID) argument.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string with a character repeated a specified number of times. |
Typical Syntax | String(number, character) |
Variations | String$ Function |
See Also | Space Function |
Use the String 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
String(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.
String$(arguments)
If you need to generate a string of only space characters, use the Space function instead. Do not use the String function to generate extremely short runs of characters (say, 1 to 5 characters in length). Use literal strings or constants instead.
The syntax of the String function permits you to pass an integer ASCII value for the character argument. If the character is a printable character, pass an example of the character instead. For non-printable characters, it is preferable to pass the ASCII value.
sWork = String$(25, 42) sWork = String$(15, Chr$(1)) ' Control-A
sWork = String$(25, "*") sWork = String$(15, 1) ' Control-A
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string with the characters of the original string reversed. |
Typical Syntax | StrReverse(string) |
Variations | StrReverse$ Function |
Use the StrReverse 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
StrReverse(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.
StrReverse$(argument)
When using the StrReverse$ 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 StrReverse$ 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.
sConfuse = StrReverse$(rsInfo!Password & "")
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Declares a subroutine procedure. |
Typical Syntax | [Private | Public | Friend] [Static] Sub name [(arglist)] [statements] |
End Sub | |
See Also | ByRef Keyword, ByVal Keyword, Function Statement, Optional Keyword, ParamArray Keyword, Property Get Statement, Property Let Statement, Property Set Statement |
Use the Sub 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 subroutine, still follow the subroutine name with an empty set of parentheses. When arguments are included, supply the appropriate data type with the As clause on each argument. (This rule does not apply to VBScript procedures.)
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 Sub statement. If you want to include static local variables within your subroutine, 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 | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Returns a value associated with the first True expression in a list of expressions. |
Typical Syntax | Switch(expr-1, value-1[, expr-2, value-2...[, expr-n, value-n]] ) |
See Also | Choose Function, IIf Function, If...Then...Else Statement, Partition Function, Select Case Statement |
Use the Switch function as needed within your Visual Basic source code. Always include source code comments that describe the purpose and results of the use of this statement.
If none of the evaluated expressions are True, the Switch function returns a Null value. Be sure to check the return value for a legitimate result if there is any chance one of the expressions will result in a True value. Although only one argument will be returned (or possibly none), and even if the first expression evaluates to True, all expressions and values are evaluated. Make sure that the expressions and values do not contain any code that will fail on invalid conditions, or that should execute only with certain condition values.
Category | Financial Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Calculates the sum-of-years' digits depreciation for an asset for one period. |
Typical Syntax | SYD(cost, salvage, life, period) |
See Also | DDB Function, FV Function, IPmt Function, IRR Function, MIRR Function, NPer Function, NPV Function, Pmt Function, PPmt Function, PV Function, Rate Function, SLN Function |
Use the SYD function as needed within your Visual Basic source code. This function returns a Double value, and accepts all 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 SYD 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 SYD 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 | Positions output when using the Print # statement. |
Typical Syntax | Tab[(number)] |
See Also | Print # Statement, Space Function, Spc Function |
Use the Tab function as needed within your Visual Basic source code. Depending on your usage of the Print # statement (and other similar Print methods), you may achieve better spacing results by using either the Space function or the Spc function.
Category | Math Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Calculates the tangent of an angle. |
Typical Syntax | Tan(number) |
See Also | Atn Function, Cos Function, Sin Function |
Use the Tan 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 | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns the current system time. |
Typical Syntax | Time |
Variations | Time$ Function |
See Also | Date Function, Date Statement, Now Function, Time Statement |
Use the Time function as needed within your Visual Basic source code. A string version of this function, Time$, returns the same information as the standard Time function, but as a true String value. (The Time$ function is not available in VBScript.) In general, you should use the Time version of this function. If you need a time stored or displayed as a string, use the Format function or the FormatDateTime function to properly format the time before use.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Sets the current system time. |
Typical Syntax | Time = time |
See Also | Date Function, Date Statement, Now Function, Time Function |
Use the Time 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 the number of seconds since midnight. |
Typical Syntax | Timer |
See Also | DateDiff Function, Time Function, Time Statement |
Use the Timer function as needed within your Visual Basic source code. When using the Timer function to compare start and stop times, recall that the return value of the Timer function will revert to 0 (zero) at midnight.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a time based on individual hour, minute, and second values. |
Typical Syntax | TimeSerial(hour, minute, second) |
See Also | DateAdd Function, DatePart Function, DateSerial Function, Hour Function, Minute Function, Second Function |
Use the TimeSerial function as needed within your Visual Basic source code. Be aware that if you supply hour, minute, or second values that are too large for a valid time, the TimeSerial function will increment the value appropriately to compensate for the extra time elements.
dtAction = TimeSerial(13, 59, 59) ' --> 1:59:59pm dtAction = TimeSerial(13, 59, 60) ' --> 2:00:00pm
You can also supply negative values for the hour, minute, or second, and the resulting time will decrement as needed. However, if you supply values that are either negative or too large for a time 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 time expression to a Variant (Date) value. |
Typical Syntax | TimeValue(date) |
See Also | CDate Function, Date Function, DateSerial Function, DateValue Function |
To convert a date, time, or date/time expression to a Variant (Date) or true Date value, use the CDate function. Avoid the TimeValue function for general time conversions. However, if you have an expression that contains both a date and a time, and you wish to retrieve only the time portion of the expression, use the TimeValue function. Passing a date and time expression to the CDate function will retain both the date and time portions of the expression. The TimeValue function discards the date portion of the original expression. If you are using the TimeValue function to remove the date portion of a date/time expression, make it clear in your source code comments that the date portion will be lost.
Category | String Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Returns a string with leading and trailing spaces removed. |
Typical Syntax | Trim(string) |
Variations | Trim$ Function |
See Also | LTrim Function, RTrim Function |
Use the Trim 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
Trim(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.
Trim$(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 Trim$ 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 Trim$ 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.
sFirstName = Trim$(rsInfo!FirstName & "")
Category | Miscellaneous Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Provides an intrinsic constant for the True Boolean value. |
Typical Syntax | True |
See Also | False Keyword |
Use the True keyword as needed within your Visual Basic source code. Although the True keyword has a value equal to −1, it is not always interpreted as −1 when coerced into other data types. Consider the following statements:
Dim sWork As String Dim nWork As Integer nWork = True sWork = nWork & " = " & True MsgBox sWork
Processing this code within a Visual Basic application will display a message box with the text "−1 = True" instead of the expected "−1 = −1." The True keyword, and all true Boolean values that equate to True, result in the text "True" when converted to a String.
Never use −1 when you mean True. 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.
When converted to a numeric value, True equates to −1. Many Windows applications are written in the C and C++ programming languages, which also include a TRUE value, either as an intrinsic constant, or as a declared constant. Within these programming languages, the numeric value of TRUE is 1, not −1. When you interact with Windows API calls that either accept or return Boolean values, verify whether or not it makes a difference to interpret TRUE as either 1 or −1. False has a numeric value of 0 (zero) in Visual Basic, C, and C++.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Defines the structure of a user-defined data type. |
Typical Syntax | [Private | Public] Type typename |
elementname [([subscripts])] As type | |
. . . | |
End Type | |
See Also | Const Statement, Dim Statement, Enum Statement, Global Statement, Private Statement, Public Statement, ReDim Statement, Static Statement |
Use the Type statement as needed within your Visual Basic source code. Always begin the statement with either the Private or Public keyword, Include a mixed-case typename ending in the word "Type." Each element within the type should follow the Hungarian naming standards for local variables, and include the appropriate As clause.
For more information about user-defined data types and the Hungarian naming conventions, see Chapter 2, Using Declaration, and Chapter 9, Declaration Standards.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the name of the type of data contained in a Variant variable or expression. |
Typical Syntax | TypeName(expression) |
See Also | VarType Function |
Use the TypeName function as needed within your Visual Basic source code. When taking an action based on the type of data contained in a Variant expression, it may be more convenient to use the VarType function.
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns the upper numeric bound of an array dimension. |
Typical Syntax | UBound(arrayname[, dimension]) |
See Also | Erase Statement, LBound Function, ReDim Statement |
Use the UBound function as needed within your Visual Basic source code. You cannot use the UBound function on an array that has not yet been dimensioned, or on a redimensioned array that has been cleared with the Erase statement.
If you are attempting to ascertain the upper bound of a one-dimensional array, do not include the dimension argument of the UBound function. If you are using the UBound 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 upper case. |
Typical Syntax | UCase(string) |
Variations | UCase$ Function |
See Also | LCase Function |
Use the UCase 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
UCase(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.
UCase$(argument)
When using the UCase$ 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 UCase$ 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.
sPostalCode = UCase$(rsInfo!PostalCode & "")
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Removes an instance of a form or control from memory. |
Typical Syntax | Unload object |
See Also | Load Statement |
Use the Unload statement as needed within your Visual Basic source code.
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Unlocks a portion or all of an open file. |
Typical Syntax | Unlock [#]filenumber[, recordrange] |
See Also | Open Statement, Lock # Statement |
Use the Unlock # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Unlock # statement. Although the "#" prefix of the filenumber argument is optional, always include it in the syntax of the statement.
The Unlock # 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 Unlock # 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:No |
Purpose | Converts the first numbers found in a string expression to a number. |
Typical Syntax | Val(string) |
See Also | CCur Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function |
Use the Val function as needed within your Visual Basic source code. However, it is better to use the other numeric conversion functions (CCur Function, CDbl Function, CDec Function, CInt Function, CLng Function, CSng Function) to change a string representation of a number into a true number.
The Val function is useful for converting strings with invalid or missing numbers to a number, even if that number is zero. The Val function converts all empty strings to the value 0. This is useful when retrieving possibly Null numeric fields from a database result set. Concatenate an empty string onto the end of the potentially Null value to prepare it for use with the Val function.
' ----- Retrieve the patient's age fsAge = Val(rsInfo!Age & "")
Category | Declaration Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Identifies the type of data contained in a Variant variable or expression. |
Typical Syntax | VarType(expression) |
See Also | TypeName Function |
Use the VarType function as needed within your Visual Basic source code. When describing the type of data contained in a Variant expression to the user, it may be more convenient to use the TypeName function.
The return value of the VarType function is an Integer value, or a combination of a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. Note that the vbArray constant may be combined with another constant in the return value.
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the weekday for a given date. |
Typical Syntax | Weekday(date[, firstdayofweek]) |
See Also | MonthName Function, WeekdayName Function |
Use the Weekday function as needed within your Visual Basic source code. The firstdayofweek argument to the Weekday 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 return value of the Weekday function returns a whole number indicating the day of the week for the supplied date. The set of return values from this function exists as a set of intrinsic Visual Basic constants. When available, always use the supplied constants instead of numeric literals. If you will use the return value directly in a numeric capacity (for example, as an array subscript), supply a comment to indicate which day of the week equates to which numeric value.
' ----- The maDailyInfo array ranges from 0 (Sunday) ' to 6 (Saturday). bInUse = maDailyInfo(Weekday(dtAction)).bInUse
Category | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes (with restrictions) |
Purpose | Return the name of the weekday for a given date. |
Typical Syntax | WeekdayName(weekday[, abbreviate[, firstdayofweek]]) |
Variations | WeekdayName$ Function |
See Also | MonthName Function, Weekday Function |
Use the WeekdayName 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
WeekdayName(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.
WeekdayName$(arguments)
The firstdayofweek argument to the WeekdayName 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.
Category | Flow Control Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Processes one or more statements repeatedly while a condition remains true. |
Typical Syntax | While condition |
[statements] | |
Wend | |
See Also | Do...Loop Statement |
The While...Wend statement is provided within all versions of Visual Basic for backward compatibility. While Microsoft has no plans to remove the construct from the language, its use is discouraged. Instead, use the Do...Loop statement with a While clause. For example, if you are considering writing the following While statement:
While (bFail = False) ' ---- Process one instance of the data set nSet = nSet + 1 bFail = ProcessOneSet(nSet) Wend
Replace it with this syntax instead:
Do While (bFail = False) ' ---- Process one instance of the data set nSet = nSet + 1 bFail = ProcessOneSet(nSet) Loop
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Identifies an open file as having output lines of a specific width. |
Typical Syntax | Width #filenumber, width |
See Also | Open Statement, Print # Statement |
Use the Width # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Width # statement.
The Width # statement permits automatic wrapping of characters within an output file. By default the line width is 0 (zero), which indicates an unlimited line length. The largest line length you can specify with the Width # statement is 255 characters. If you need to have lines wrap at a line length larger than 255 characters, you must perform the wrapping yourself before outputting the lines.
The Width # 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 Width # 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:Yes |
Purpose | Enters a code block with an assumed object prefix. |
Typical Syntax | With object |
[statements] | |
End With |
Use the With statement as needed within your Visual Basic source code. Do not use the With statement based on a simple one-level, non-array object.
With Me With objStatus With frmMain With txtName
With txtName(Index) With gaCustomer(nActiveCust).aOrder(nActiveOrder)
Category | File System Features |
Availability | VB:Yes, VBA:Yes, VBScript:No |
Purpose | Outputs delimited data to a sequential file. |
Typical Syntax | Write #filenumber, [outputlist] |
See Also | Input # Statement, Open Statement, Print # Statement |
Use the Write # statement as needed within your Visual Basic source code. Always use a file number returned from the FreeFile function as an argument to the Write # statement. If you wish to output text in a format to be read later by people instead of by an application, consider using the Print # 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 Write # 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 Write # 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 exclusion operation. |
Typical Syntax | expression1 Xor expression2 |
See Also | And Operator, Eqv Operator, Imp Operator, Not Operator, Or Operator. |
Use the Xor 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 | Date and Time Features |
Availability | VB:Yes, VBA:Yes, VBScript:Yes |
Purpose | Returns a value indicating the year for a given date. |
Typical Syntax | Year(date) |
See Also | DatePart Function, Day Function, Hour Function, Minute Function, Month Function, Second Function |
Use the Year 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 year returned from this function as a string (for example, to concatenate the year onto an existing string), consider using the Format$ function instead.
sInfo = "You were born in " & Format$(dtBirthdate, "yyyy")
3.134.79.121