On...GoSub Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeBranches to one or more code sections based on an expression.
Typical SyntaxOn expression GoSub destinationlist
See AlsoChoose 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.

On...GoTo Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeBranches to one or more code sections based on an expression.
Typical SyntaxOn expression GoTo destinationlist
See AlsoChoose 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.

Open Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeOpens a file for input or output.
Typical SyntaxOpen pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]
See AlsoClose 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.

Option Base Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates the default lower bound for all declared arrays.
Typical SyntaxOption Base {0 | 1}
See AlsoDim 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).

Option Compare Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIndicates the type of comparison used within a source code module.
Typical SyntaxOption Compare {Binary | Text | Database}
See AlsoOption 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.

Option Explicit Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeRequires all variables and constants to be declared before use.
Typical SyntaxOption Explicit
See AlsoOption 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.

Option Private Statement

CategoryDeclaration Features
AvailabilityVB:Yes (with restrictions), VBA:Yes, VBScript:No
PurposeLimits references to a module's contents from being accessed outside of the project.
Typical SyntaxOption Private Module
See AlsoOption 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.

Optional Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIdentifies a procedure argument as optional.
Typical SyntaxOptional [ByVal | ByRef] [ParamArray] varname[(þ)] [As type] [= defaultvalue]
See AlsoByRef 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.

Or Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise disjunction operation.
Typical Syntaxexpression1 Or expression2
See AlsoAnd 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.

ParamArray Keyword

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeProvides a mechanism for the caller of a procedure to send a variable number of arguments.
Typical SyntaxParamArray varname[ ( )] [As type]
See AlsoByRef 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.

Partition Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIdentifies the element in a series of ranges in which a value appears.
Typical SyntaxPartition(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.

Pmt Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the payment for an annuity.
Typical SyntaxPmt(rate, nper, pv[, fv[, type]])
See AlsoDDB 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.

PPmt Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the principal payment for an annuity.
Typical SyntaxPPmt(rate, per, nper, pv[, fv[, type]])
See AlsoDDB 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.

Print # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeOutputs text to a sequential file.
Typical SyntaxPrint #filenumber, [outputlist]
See AlsoInput 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.

Private Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a variable that is "module-level" in scope.
Typical SyntaxPrivate [WithEvents] varname[([subscripts])] [As [New] type]
See AlsoDim 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.

Property Get Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a property retrieval procedure.
Typical Syntax[Private | Public | Friend] [Static] Property Get name
 [(arglist)] [As type]
 [statements]
 End Property
See AlsoByRef 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.

Property Let Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a property assignment procedure.
Typical Syntax[Private | Public | Friend] [Static] Property Letname
 ([arglist,] value)
 [statements]
 End Property
See AlsoByRef 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.

Property Set Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares an object property assignment procedure.
Typical Syntax[Private | Public | Friend] [Static] Property Setname([arglist,] reference) [statements]
 End Property
See AlsoByRef 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.

Public Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a variable that is global in scope.
Typical SyntaxPublic [WithEvents] varname[([subscripts] )] [As [New] type]
See AlsoDim 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.

Put Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeWrites data from a variable to an open file.
Typical SyntaxPut [#] filenumbeyr, [recnumber], varname
See AlsoGet 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.

PV Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the present value of an annuity.
Typical SyntaxPV(rate, nper, pmt[, fv[, type]])
See AlsoDDB 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.

QBColor Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns an RGB color based on a "color number."
Typical SyntaxQBColor(color)
See AlsoRGB 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.

RaiseEvent Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRaises an event declared with the Event statement.
Typical SyntaxRaiseEvent eventname [ (argumentlist)]
See AlsoEvent 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.

Randomize Statement

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeInitializes the random number generator with a seed value.
Typical SyntaxRandomize [number]
See AlsoRnd 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.

Incorrect
Randomize Timer

Correct
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.

Correct
' ----- In the Declarations section
Public Const STANDARD_SEED = 150
' ----- Later, in a routine
Call Rnd(-1)
Randomize STANDARD_SEED

Rate Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the interest rate per period of an annuity.
Typical SyntaxRate(nper, pmt, pv[, fv[, type[, guess]]])
See AlsoDDB 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.

ReDim Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReallocates an array dynamically to increase or decrease storage.
Typical SyntaxReDim [Preserve] varname(subscripts) [As type]
See AlsoDim 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.

Incorrect for VB, VBA; Correct for VBScript
ReDim maElements(nNewElement)

Correct for VB, VBA
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.

Rem Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeBegins a source code comment line or line section.
Typical SyntaxRem 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.

Replace Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReplaces one sub-string with another sub-string in a larger string.
Typical SyntaxReplace(expression, find, replacewith[, start[, count[, compare]]] )
VariationsReplace$ Function
See AlsoFilter 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.

Reset Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCloses all open files.
Typical SyntaxReset
See AlsoClose 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.

Resume Statement

CategoryError Handling and Debugging Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeResumes execution of a procedure after error handling in an On Error statement.
Typical SyntaxResume [0]
 Resume Next
 Resume line
See AlsoErr 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.

RGB Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value for a color based on distinct red, green, and blue values.
Typical SyntaxRGB(red, green, blue)
See AlsoQBColor 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

Right Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the right portion of a string.
Typical SyntaxRight(string, length)
VariationsRight$ Function, RightB Function, RightB$ Function
See AlsoLeft 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)

RmDir Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDeletes a directory.
Typical SyntaxRmDir path
See AlsoChDir 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.

Rnd Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeGenerates a pseudo-random number.
Typical SyntaxRnd[(number)]
See AlsoRandomize 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)

Round Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeRounds a value to a specific number of decimal places.
Typical SyntaxRound(expression[, numdecimalplaces])
See AlsoAbs 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.

RSet Statement

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRight aligns a string within a string variable.
Typical SyntaxRSet stringvar = string
See AlsoLSet Statement, Right Function, Space Function

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

RTrim Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string with trailing spaces removed.
Typical SyntaxRTrim(string)
VariationsRTrim$ Function
See AlsoLTrim 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 & "")

SavePicture Statement
CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSaves a graphic to a file.
Typical SyntaxSavePicture picture, pathname
See AlsoLoadPicture 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.

SaveSetting Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSaves application information in the Windows registry.
Typical SyntaxSaveSetting appname, section, key, setting
See AlsoDeleteSetting 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.

Screen Object

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:No, VBScript:No
PurposeObject that supplies screen and display related properties.
Typical SyntaxScreen
See AlsoApp 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.

ScriptEngine Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeReturns the name of the engine processing the VBScript code.
Typical SyntaxScriptEngine
See AlsoScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function

Use the ScriptEngine function as needed within your VBScript source code.

ScriptEngineBuildVersion Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeReturns the build version number of the engine processing the VBScript code.
Typical SyntaxScriptEngineBuildVersion
See AlsoScriptEngine Version, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function

Use the ScriptEngineBuildVersion function as needed within your VBScript source code.

ScriptEngineMajorVersion Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeReturns the major version number of the engine processing the VBScript code.
Typical SyntaxScriptEngineMajorVersion
See AlsoScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMinorVersion Function

Use the ScriptEngineMajorVersion function as needed within your VBScript source code.

ScriptEngineMinorVersion Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeReturns the minor version number of the engine processing the VBScript code.
Typical SyntaxScriptEngineMinorVersion
See AlsoScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function

Use the ScriptEngineMinorVersion function as needed within your VBScript source code.

Second Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the second for a given date or time.
Typical SyntaxSecond(time)
See AlsoDatePart 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")

Seek Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns the current position in an open file.
Typical SyntaxSeek(filenumber)
See AlsoEOF 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.

Seek Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSets the current position in an open file.
Typical SyntaxSeek [#]filenumber, position
See AlsoEOF 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.

Select Case Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeExecutes one of several blocks of code based on an expression.
Typical SyntaxSelect Case expression
 [Case expressionlist-n
 [statements]]...
 [Case Else
 [statements]]
 End Select
See AlsoChoose 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.

SendKeys Statement

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSends keystrokes to the active window.
Typical SyntaxSendKeys string[, wait]
See AlsoAppActivate 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.

Incorrect
' ----- Click on the action button
cmdAction.SetFocus
SendKeys "%A"

Correct
' ----- 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.

Set Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeAssigns an object reference to an object variable.
Typical SyntaxSet 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.

SetAttr Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSets the attributes of a file.
Typical SyntaxSetAttr pathname, attributes
See AlsoFileAttr 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.

SetLocale Function

CategoryMiscellaneous Features
AvailabilityVB:No, VBA:No, VBScript:Yes
PurposeSets a new locale while identifying the previous locale.
Typical SyntaxSetLocale(lcid)
See AlsoGetLocale 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.

Sgn Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns -1, 0, or 1, depending on the sign of the passed expression.
Typical SyntaxSgn(expression)
See AlsoAbs Function, Fix Function, Int Function, Round Function

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

Shell Function

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRuns another program, and returns the task ID if successful.
Typical SyntaxShell(pathname[, windowstyle])
See AlsoAppActivate 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.

Sin Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the sine of an angle.
Typical SyntaxSin(number)
See AlsoAtn 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.

SLN Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the straight-line depreciation of an asset for one period.
Typical SyntaxSLN(cost, salvage, life)
See AlsoDDB 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.

Space Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string of space characters repeated a specified number of times.
Typical SyntaxSpace(number)
VariationsSpace$ Function
See AlsoSpc 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.

Spc Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposePositions output when using the Print # statement.
Typical SyntaxSpc(number)
See AlsoPrint # 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.

Split Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns an array of strings extracted from a larger string based on a delimiter.
Typical SyntaxSplit(expression[, delimiter[, count[, compare]]] )
See AlsoInStr 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.

Sqr Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the square root of a number.
Typical SyntaxSqr(number)
See AlsoExp 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.

Static Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDeclares a variable that is local in scope, but maintains its data throughout the life of the application.
Typical SyntaxStatic varname[ ([subscripts])] [As [New] type]
See AlsoDim 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.

Stop Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposePauses or halts program execution immediately.
Typical SyntaxStop
See AlsoEnd 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

Str Function

CategoryConversion Functions, String Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts a number to the String data type.
Typical SyntaxStr(number)
VariationsStr$ Function
See AlsoCStr Function, StrConv Function, Val Function

Do not use the Str function, or its Str$ variation, within your source code. Use the CStr function instead.

StrComp Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCompares two string values.
Typical SyntaxStrComp(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.

StrConv Function

CategoryConversion Functions, String Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts a string to a different format.
Typical SyntaxStrConv(string, conversion[, lcid])
See AlsoChr 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.

String Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string with a character repeated a specified number of times.
Typical SyntaxString(number, character)
VariationsString$ Function
See AlsoSpace 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.

Incorrect
sWork = String$(25, 42)
sWork = String$(15, Chr$(1))  ' Control-A

Correct
sWork = String$(25, "*")
sWork = String$(15, 1)  ' Control-A

StrReverse Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string with the characters of the original string reversed.
Typical SyntaxStrReverse(string)
VariationsStrReverse$ 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 & "")

Sub Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeDeclares a subroutine procedure.
Typical Syntax[Private | Public | Friend] [Static] Sub name [(arglist)] [statements]
 End Sub
See AlsoByRef 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.

Switch Function

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeReturns a value associated with the first True expression in a list of expressions.
Typical SyntaxSwitch(expr-1, value-1[, expr-2, value-2...[, expr-n, value-n]] )
See AlsoChoose 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.

SYD Function

CategoryFinancial Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeCalculates the sum-of-years' digits depreciation for an asset for one period.
Typical SyntaxSYD(cost, salvage, life, period)
See AlsoDDB 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.

Tab Function

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposePositions output when using the Print # statement.
Typical SyntaxTab[(number)]
See AlsoPrint # 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.

Tan Function

CategoryMath Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeCalculates the tangent of an angle.
Typical SyntaxTan(number)
See AlsoAtn 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.

Time Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns the current system time.
Typical SyntaxTime
VariationsTime$ Function
See AlsoDate 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.

Time Statement

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeSets the current system time.
Typical SyntaxTime = time
See AlsoDate 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.

Timer Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the number of seconds since midnight.
Typical SyntaxTimer
See AlsoDateDiff 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.

TimeSerial Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a time based on individual hour, minute, and second values.
Typical SyntaxTimeSerial(hour, minute, second)
See AlsoDateAdd 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.

TimeValue Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeConverts a time expression to a Variant (Date) value.
Typical SyntaxTimeValue(date)
See AlsoCDate 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.

Trim Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string with leading and trailing spaces removed.
Typical SyntaxTrim(string)
VariationsTrim$ Function
See AlsoLTrim 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 & "")

True Keyword

CategoryMiscellaneous Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeProvides an intrinsic constant for the True Boolean value.
Typical SyntaxTrue
See AlsoFalse 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++.

Type Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeDefines the structure of a user-defined data type.
Typical Syntax[Private | Public] Type typename
 elementname [([subscripts])] As type
 . . .
 End Type
See AlsoConst 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.

TypeName Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the name of the type of data contained in a Variant variable or expression.
Typical SyntaxTypeName(expression)
See AlsoVarType 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.

UBound Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns the upper numeric bound of an array dimension.
Typical SyntaxUBound(arrayname[, dimension])
See AlsoErase 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.

UCase Function

CategoryString Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturns a string converted to upper case.
Typical SyntaxUCase(string)
VariationsUCase$ Function
See AlsoLCase 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 & "")

Unload Statement

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeRemoves an instance of a form or control from memory.
Typical SyntaxUnload object
See AlsoLoad Statement

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

Unlock # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeUnlocks a portion or all of an open file.
Typical SyntaxUnlock [#]filenumber[, recordrange]
See AlsoOpen 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.

Val Function

CategoryConversion Functions
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeConverts the first numbers found in a string expression to a number.
Typical SyntaxVal(string)
See AlsoCCur 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 & "")

VarType Function

CategoryDeclaration Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeIdentifies the type of data contained in a Variant variable or expression.
Typical SyntaxVarType(expression)
See AlsoTypeName 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.

Weekday Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the weekday for a given date.
Typical SyntaxWeekday(date[, firstdayofweek])
See AlsoMonthName 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

WeekdayName Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes (with restrictions)
PurposeReturn the name of the weekday for a given date.
Typical SyntaxWeekdayName(weekday[, abbreviate[, firstdayofweek]])
VariationsWeekdayName$ Function
See AlsoMonthName 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.

While...Wend Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeProcesses one or more statements repeatedly while a condition remains true.
Typical SyntaxWhile condition
 [statements]
 Wend
See AlsoDo...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

Width # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeIdentifies an open file as having output lines of a specific width.
Typical SyntaxWidth #filenumber, width
See AlsoOpen 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.

With Statement

CategoryFlow Control Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeEnters a code block with an assumed object prefix.
Typical SyntaxWith 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.

Incorrect
With Me
With objStatus
With frmMain
With txtName

Correct
With txtName(Index)
With gaCustomer(nActiveCust).aOrder(nActiveOrder)

Write # Statement

CategoryFile System Features
AvailabilityVB:Yes, VBA:Yes, VBScript:No
PurposeOutputs delimited data to a sequential file.
Typical SyntaxWrite #filenumber, [outputlist]
See AlsoInput # 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.

Xor Operator

CategoryOperators
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposePerforms a logical or bitwise exclusion operation.
Typical Syntaxexpression1 Xor expression2
See AlsoAnd 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.

Year Function

CategoryDate and Time Features
AvailabilityVB:Yes, VBA:Yes, VBScript:Yes
PurposeReturns a value indicating the year for a given date.
Typical SyntaxYear(date)
See AlsoDatePart 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")

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

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