Conversion Functions

Asc Function

CBool Function

CCur Function

CDate Function

CDbl Function

CInt Function

CLng Function

CSng Function

CStr Function

CVar Function

CVErr Function

Format Function

Str Function

Val Function


Asc Function

Returns the character code corresponding to the first letter in a string.

Syntax

Asc(string)

Elements

The string named argument is any valid string expression.  If the string contains no characters, a run-time error occurs.


CBool Function

Converts an expression to a Boolean.

Syntax

CBool(expression)

Elements

The expression argument is any valid numeric expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned.  If expression can't be interpreted as a numeric value, a run-time error occurs.


CCur Function

Converts an expression to a Currency.

Syntax

CCur(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CCur to force currency arithmetic in cases where single-precision, double-precision, or integer arithmetic normally would occur.

You should use the CCur function instead of Val to provide internationally-aware conversions from any other data type to a Currency.  For example, different decimal separators are properly recognized depending on the locale setting of your computer, as are different thousand separators and various currency options.

If expression lies outside the acceptable range for the Currency data type, an error occurs.


CDate Function

Converts an expression to a Date.

Syntax

CDate(date)

Elements

The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time.  CDate recognizes date and time literals as well as some numbers that fall within the range of acceptable dates.  When converting a number to a date, the whole number portion is converted to a date.  Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the international settings of your system.  The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings.  In addition, a long date format is not recognized if it also contains the day-of-the-week string.

Note   A CVDate function is also provided for compatibility with previous versions of Visual Basic.  However, since there is now an intrinsic Date type, there is no further need for CVDate.  The syntax of the CVDate function is identical to the CDate function.  The difference is that it returns a Variant whose subtype is Date instead of an actual Date type.  The same effect can be achieved by converting an expression to a Date and then assigning it to a Variant.  This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes.


CDbl Function

Converts an expression to a Double.

Syntax

CDbl(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CDbl function instead of Val to provide internationally-aware conversions from any other data type to a Double.  For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.


CInt Function

Converts an expression to an Integer.

Syntax

CInt(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CInt function instead of Val to provide internationally-aware conversions from any other data type to an Integer.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer data type, an error occurs.

Note   CInt differs from the Fix and Int functions that truncate, rather than round, the fractional part of a number.  When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number.  For example, 0.5 rounds to 0, and 1.5 rounds to 2.


CLng Function

Converts an expression to a Long.

Syntax

CLng(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CLng function instead of Val to provide internationally-aware conversions from any other data type to a Long.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long data type, an error occurs.

Note   CLng differs from the Fix and Int functions that truncate, rather than round, the fractional part of a number.  When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number.  For example, 0.5 rounds to 0, and 1.5 rounds to 2.


CSng Function

Converts an expression to a Single.

Syntax

CSng(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CSng function instead of Val to provide internationally-aware conversions from any other data type to a Single.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single data type, an error occurs.


CStr Function

Converts an expression to a String.

Syntax

CStr(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CStr to force the result to be expressed as a String.

You should use the CStr function instead of Str to provide internationally-aware conversions from any other data type to a String.  For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to the following table:

If expression is	CStr returns

Boolean	String containing True or False (translated as appropriate for locale).

Date	String containing a date in the short-date format of your system.

Null	A run-time error.

Empty	A zero-length String ("").

Error	A String containing the word Error (translated as appropriate for locale) followed by the error number.

Other Numeric	A String containing the number.


CVar Function

Converts an expression to a Variant.

Syntax

CVar(expression)

Elements

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CVar to force the result to be expressed as a Variant.


CVErr Function

Returns a Variant of subtype Error containing an error number specified by the user.

Syntax

CVErr(errornumber)

Elements

The errornumber argument is any valid error number.

Remarks

Use the CVErr function to create user-defined errors in user-created procedures.  For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range.  If they are not, it is likely that your function will not return what you expect.  In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed.  For example, you can't directly assign the return value of CVErr to a non-Variant variable.  However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.


Val Function

Returns the numbers contained in a string.

Syntax

Val(string)

Elements

The string named argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can't recognize as part of a number.  Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized.  However, the function recognizes radix prefixes &O (for octal) and &H (for hexadecimal).  Blanks, tabs, and linefeeds are stripped from the argument.

The following returns the value 1615198:

Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

Note   The Val function recognizes only the period (.) as a valid decimal separator.  When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CDbl instead to convert a string to a number.


Asc Function Example

This example uses the Asc function to return a character code corresponding to the first letter in the string.

MyNumber = Asc("A")	' Returns 65.

MyNumber = Asc("a")	' Returns 97.

MyNumber = Asc("Apple")	' Returns 65.


CBool Function Example

This example uses the CBool function to convert an expression to a Boolean.  If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

A = 5 : B = 5	' Define variables.

Check = CBool(A = B)	' Check contains True.

A = 0	' Define variable.

Check = CBool(A)	' Check contains False.


CDate Function Example

This example uses the CDate function to convert a string to a Date.  In general, it is bad programming practice to hard code dates/times as strings as shown in this example.  Use date literals instead.

MyDate = "February 12, 1969"	' Define date.

MyShortDate = CDate(MyDate)	' Convert to Date data type.

MyTime = "4:35:47 PM"	' Define time.

MyShortTime = CDate(MyTime)	' Convert to Date data type.


CVErr Function Example

This example uses the CVErr function to return an Error Variant.  The user-defined function CalculateDouble returns an error if the argument passed to it isn't a number.  CVErr is useful for returning user-defined errors from user-defined procedures.  Use the IsError function to test if the value is an error.

' Define CalculateDouble Function procedure.

Function CalculateDouble(Number)

If IsNumeric(Number) Then

CalculateDouble = Number * 2	' Return result.

Else

CalculateDouble = CVErr(2001)	' Return a user-defined error

End If	' number.

End Function


CCur Function Example

This example uses the CCur function to convert an expression to a Currency.

MyDouble = 543.214588	' MyDouble is a Double.

MyCurr = CCur(MyDouble * 2)	' Convert result (1086.4292) to

' Currency.


CDbl Function Example

This example uses the CDbl function to convert an expression to a Double.

MyCurr = CCur(234.456784)	' MyCurr is a Currency.

MyDouble = CDbl(MyCurr * 8.2 * 0.01)	' Convert result to Double.


CInt Function Example

This example uses the CInt function to convert a value to an Integer.

MyDouble = 2345.5678	' MyDouble is a Double.

MyInt = CInt(MyDouble)	' MyInt contains 2346.


CLng Function Example

This example uses the CLng function to convert a value to a Long.

MyVal1 = 25427.45 : MyVal2 = 25427.55	' MyVal1, MyVal2 are Doubles.

MyLong1 = CLng(MyVal1)	' MyLong1 contains 25427.

MyLong2 = CLng(MyVal2)	' MyLong2 contains 25428.


CSng Function Example

This example uses the CSng function to convert a value to a Single.

' MyDouble1, MyDouble2 are Doubles.

MyDouble1 = 75.3421115 : MyDouble2 = 75.3421555

MySingle1 = CSng(MyDouble1)	' MySingle1 contains 75.34211.

MySingle2 = CSng(MyDouble2)	' MySingle2 contains 75.34216.


CStr Function Example

This example uses the CStr function to convert a numeric value to a String.

MyDouble = 437.324	' MyDouble is a Double.

MyString = CStr(MyDouble)	' MyString contains "437.324".


CVar Function Example

This example uses the CVar function to convert an expression to a Variant.

MyInt = 4534	' MyInt is an Integer.

MyVar = CVar(MyInt & "000")	' MyVar contains 4534000.


Val Function Example

This example uses the Val function to return the numbers contained in a string.

MyValue = Val("2457")	' Returns 2457.

MyValue = Val(" 2 45 7")	' Returns 2457.

MyValue = Val("24 and 57")	' Returns 24.


Creating an Object Variable

You can treat an object variable exactly as you would treat the object to which it refers.  You can set or return the properties of the object or use any of its methods.

To create an object variable

1.	Declare the object variable.

2.	Assign the object variable to an object.

Declaring an object Variable

Use the Dim statement or one of the other declaration statements (Public, Private, or Static) to declare an object variable.  A variable that refers to an object must be Variant, an Object, or a specific type of object.  For example, the following declarations are valid:

Dim MyObject	' Declares MyObject as Variant data type.

Dim MyObject As Object	' Declares MyObject as Object data type.

Dim MyObject As Font	' Declares MyObject as Font type.

Note   As with other variables, if you use an object variable without declaring it first, the data type of the object variable is Variant by default.

The Object data type allows you to create a generic reference to any object.  You can declare an object variable with the Object data type in situations where the specific object type is not known until the procedure runs.

If you know the specific object type an object variable will refer to, you should declare the object variable as that object type.  For example, if the application you use contains a Sample object type, you can declare an object variable for that object using either of these statements:

Dim MyObject As Object	' Declared as generic object.

Dim MyObject As Sample	' Declared only as Sample object.

Declaring specific object types provides automatic type checking, faster code, and improved readability.

Assigning an object variable to an object

Use the Set statement to assign an object to an object variable.  You can assign an object expression or Nothing.  For example, the following object variable assignments are valid:

Set MyObject = YourObject	' Assign object reference.

Set MyObject = Nothing	' Discontinue association.

Setting an object variable equal to Nothing discontinues the association of the object variable with any specific object.  This prevents you from accidentally changing the object by changing the variable.  If you always set an object variable to Nothing after closing the object, you can easily test whether or not the object variable points to a valid object, for example:

If MyObject Not Nothing Then	' Variable refers to valid object.

. . .

End If


Creating Arrays

Unless you specify a data type, declared arrays contain variants.  Arrays of type Variant consume 16 bytes for each element that the array contains.  The following lines of code compare the size of several arrays:

' Integer array uses 22 bytes (11 elements * 2 bytes).

ReDim MyIntegerArray(10) As Integer

' Double-precision array uses 88 bytes (11 elements * 8 bytes).

ReDim MyDoubleArray(10) As Double

' Variant array uses at least 176 bytes (11 elements * 16 bytes).

ReDim MyVariantArray(10)

' Integer array uses 100 * 100 * 2 bytes (20,000 bytes).

ReDim MyIntegerArray (99, 99) As Integer

' Double-precision array uses 100 * 100 * 8 bytes (80,000 bytes).

ReDim MyDoubleArray (99, 99) As Double

' Variant array uses at least 160,000 bytes (100 * 100 * 16 bytes).

ReDim MyVariantArray(99, 99)

The maximum size of an array varies, based on the operating system you are using and how much memory is available.  You aren't likely to encounter this limit, but using arrays that exceed the amount of random-access memory available on your system are slower because the data must be read from and written to disk.


Creating Recursive Procedures

Procedures have a limited amount of space for variables.  Each time a procedure calls itself, more of that space is used.  This type of procedure is called a recursive procedure.  A recursive procedure that indefinitely calls itself eventually causes an error.  For example:

Function RunOut(Maximum)

RunOut = RunOut(Maximum)	' Error Calls itself without ever exiting.

End Function

This error may be less obvious when two procedures call each other indefinitely, or some condition that limits the recursion is never met.  Recursion has its uses.  For example, the following procedure uses a recursive function to calculate factorials:

Function Factorial (N)

If N <= 1 Then	' Reached end of recursive calls.

Factorial = 1	' (N = 0) so climb back out of calls.

Else	' Call Factorial again if N > 0.

Factorial = Factorial(N - 1) * N

End If

End Function

You should test your recursive procedure to make sure it does not call itself so many times that you run out of memory.  If you get an error, make sure your procedure is not calling itself indefinitely.  After that, try to conserve memory by:

•	Eliminating unneeded variables.

•	Using data types other than Variant.

•	Reevaluating the logic of the procedure.  Often you can substitute nested loops for recursion.


Making Faster For...Next Loops

Integers are not only smaller than the Variant data type, they are also slightly faster to update.  Since computers operate at very great speed, this difference is only noticeable if you perform many thousands of operations.  For example:

Dim CountFaster As Integer	' First case, use Integer.

For CountFaster = 0 to 32766

Next CountFaster

Dim CountSlower As Variant	' Second case, use Variant.

For CountSlower = 0 to 32766

Next CountSlower

The first case above takes slightly less time to execute than the second case.  However, if CountFaster exceeds 32,767, an error occurs.  To fix this, you could change CountFaster to the Long data type, which accepts a much wider range of integers.  However, variables of the data type Long are slower to update than variables of type Integer.  In general, the smaller the data type, the less time it takes to update.  Variants are slightly slower than their equivalent data type.


Module Scope

Variables and objects defined at module level are visible in all procedures within the module.  You must qualify them with their module name to distinguish them from procedure-level variables with the same name.  For example, the variable MyVar declared at module level of MyModule can be distinguished from a variable MyVar declared in a procedure by qualifying it as MyModule.MyVar.  However, you need not qualify a module-level variable name in a procedure that has no local variable of the same name.  Module-level variables are always Static, that is, they exist whenever their module is part of a running program.

Procedures are always defined at module level, and by default are visible (callable) from anywhere in a project.  If you want a procedure to be visible only within its own module, you can define it as Private to prevent its being called from procedures in other modules in a project.  You can make all procedures in a module private by placing the statement Option Private at the beginning of the module.  The lifetime of a procedure is similar to that of a Static variable, whenever its module is part of a running program.

Identifiers in a directly referenced project that are declared Public (at module-level) are visible to the directly referencing project.  Variables and symbolic constants (declared with the Const statement) are Private by default.  Procedures are Public by default.  Structure types (declared with the Type...End Type statement) are Public by default.  You can use Option Private Module to keep Public identifiers visible throughout the modules in your project, but make them invisible to other projects.


Naming-Conflict Errors

A naming-conflict bug can occur even if you use Option Explicit, which normally protects you from such situations.  For example, if you use an undeclared identifier in a For...Next loop in a procedure, and that variable has the same name as one with wider scope, you can inadvertently change the variable with wider scope:

Option Explicit	' Forces declaration before use of variables.

Dim X	' Module-level declaration of X.

Sub AnyProc()

' A Dim X statement here would prevent a bug.

For X = 0 to 25	' Loop counter not declared in its procedure.

Print X	' This X is the same as the module-level X.

Next X

Call AnotherProc

End Sub

Sub AnotherProc()

X = X + 1

Print X	' This X has value of loop counter in AnyProc.

End Sub


OLE Automation

OLE Automation is an industry standard that applications use to expose their OLE objects to development tools, macro languages, and other applications that support OLE Automation.  For example, a spreadsheet application may expose a worksheet, chart, cell, or range of cells [image] all as different types of objects.  A word processor might expose objects such as application, document, paragraph, sentence, bookmark, or selection.

When an application supports OLE Automation, the objects it exposes can be accessed by Visual Basic.  Use Visual Basic to manipulate these objects by invoking methods on the object or by getting and setting the object's properties.  For example, if you created an OLE Automation object named MyObj, you might write code such as this to manipulate the object:

MyObj.Insert "Hello, world."	' Place text.

MyObj.Bold = True	' Format text.

MyObj.SaveAs  "C:\WORDPROC\DOCS\TESTOBJ.DOC"	' Save the object.

The following functions give you access to an OLE Automation object:

Function	Description

CreateObject	Creates a new object of a specified type.

GetObject 	Retrieves an object from a file.

See an application's documentation for details on the properties and methods it supports.  The objects, functions, properties and methods supported by an application are usually defined in the application's object library.

To add a reference to an object library

1.	From the Tools menu, choose References.

The References dialog appears.

2.	Select the application reference or, if it is not listed, choose Browse and select the appropriate file.

An application's objects can be referenced without adding a reference to the application's object library.  However, it is preferable to add the object library reference for the following reasons:

•	Globally accessible functions may be accessed directly without qualification.

•	The application will be automatically launched if it has not been previously by the first reference to it.

•	Invocation of functions, properties, and methods may be checked at compile time for correctness; therefore, they will execute more quickly at run time.

•	It is possible to declare variables of the types defined in the library, which increases run-time reliability and readability.


Passing Arguments Efficiently

All arguments are passed to procedures by reference unless you specify otherwise.  This is efficient because all arguments take the same amount of time to pass and the same amount of space (4 bytes) within a procedure regardless of the argument's data type.

You can pass an argument by value, instead of by reference, if you include the ByVal keyword in the procedure's declaration.  Arguments passed by value consume from 2 to 16+ bytes within the procedure, depending on the argument's data type.  Larger data types take slightly longer to pass than smaller ones.

Passing an argument by value copies the original variable.  Changes to the argument within the procedure aren't reflected back to the original variable.  For example:

Function Factorial (ByVal MyVar As Integer)	' Function declaration.

MyVar = MyVar - 1

If MyVar = 0 Then

Factorial = 1

Exit Function

End If

Factorial = Factorial(MyVar) * (MyVar + 1)

End Function

' Call Factorial with a variable S.

S = 5

Print Factorial(S)	' Displays 120 (the factorial of 5).

Print S	' Displays 5.

Without ByVal in the function declaration, the Print statements above would display 1 and 0.  This is because MyVar would then refer to variable S, which is reduced by 1 until it equals 0.

Because ByVal makes a copy of the argument, it allows you to pass a variant to the Factorial function above.  You can't pass a variant by reference if the procedure that declares the argument is another data type.


Procedure Scope

Variables and objects defined at procedure level (within procedures) are private to the procedure in which they are defined and are never visible outside the procedure.  If declared Static, the variable exists whenever its module is a part of the running program; otherwise, local variables are created each time the procedure begins, and are destroyed each time the procedure ends.

Procedures can't be nested within other procedures.


Project Scope

Only module names and the names of referenced projects are at project level.  These include host-application modules and projects (even though they may be referred to with host-specific terminology, for example, as Worksheets in Excel).

Public identifiers are visible at project level, even though they are defined at module level.  It is important to understand that visibility extends in only one direction.  That is, Public identifiers in a directly referenced project are visible in a directly referencing project, but identifiers in the referencing project are not visible within the referenced project.  For example, if MyProj directly references YourProj, module names and other Public identifiers in YourProj are visible in MyProj, but module names and other Public identifiers in MyProj are not visible in YourProj (or projects referenced by YourProj).


Resolving Naming Conflicts

A naming conflict occurs when you try to create or use an identifier that is recognized by Visual Basic as having been previously defined.  In some cases naming conflicts generate errors such as Ambiguous name detected or Duplicate declaration in current scope.  Naming conflicts can go unnoticed and result in bugs in your code and erroneous results, especially if you do not explicitly declare all variables before first use.

Most naming conflicts can be resolved by understanding the scoping characteristics of identifiers for data, objects, and procedures.  Visual Basic has three scoping levels: procedure level, module level, and project level.

A naming conflict can occur when an identifier:

•	Is visible at more than one level

•	Has two different meanings at the same level

For example, procedures in separate modules can have the same name.  Therefore, a procedure named MySub can be defined in modules named Mod1 and Mod2.  No conflicts occur if the procedures are called only from their own modules.  However, an error can occur if MySub is called from a third module, and no qualification is provided to distinguish between the two MySub procedures.  For example, to call the MySub (defined in both Mod1 and Mod2 modules) from Mod5, simply specify it as Mod1.MySub or Mod2.MySub in the call.

Visual Basic matches each reference to an identifier with the "closest" declaration of a matching identifier.  For example, if MyID is declared Public in two modules in a project (Mod1 and Mod2), you can specify the MyID declared in Mod2 without qualification from within Mod2, but you must qualify it (as Mod2.MyID) to specify it in Mod1.  This is also true if Mod2 is in a different project, but one that is a directly referenced project.  However, if Mod2 is in an indirectly referenced project, references to its variable named MyID must always be qualified, with the project name.  If you reference MyID from a third, directly referenced module, the match is made with the first declaration encountered by searching:

•	Directly referenced projects, in the order in they appear in the References dialog of the Tools menu.

•	The modules of each project.  (Note that there is no inherent order to the modules in the project.)

Names of host-application objects (for example, R1C1 in Excel) can't be reused at different scoping levels.

Beginning each module with the statement Option Explicit can help avoid both naming conflicts and identifier-related bugs by forcing explicit declarations of variables before they are used.

Most naming conflicts can be resolved by preceding the name with a qualifier that consists of its module name and, if necessary, a qualifying project name.  For example:

YourProject.YourModule.YourSub MyProject.MyModule.MyVar

The preceding code calls the Sub procedure YourSub and passes MyVar as an argument.  You can use any combination of qualifiers that is sufficient to differentiate identical identifiers.

Typical errors caused by naming conflicts include those for ambiguous names, duplicate declarations, undeclared identifiers, procedure not found, and so on.


Returning Strings from Functions

Some functions have two versions, one that returns a Variant data type and one that returns a String data type.  The variant versions tend to be the most convenient because variants handle conversions between different types of data automatically.

Consider using the String type version when:

•	Your program is very large and uses many variables.

•	Your code is densely structured, and you want to detect when data of one type is converted to another type.

•	You write data directly to random-access files.

The following functions return values in a String type variable when you append a dollar sign ($) to the function name.  These functions have the same usage and syntax as their variant equivalents without the dollar sign.

Chr$	CurDir$	Date$	Dir$

Error$	Format$	Hex$	Input$

LCase$	Left$ 	LTrim$	Mid$

Oct$	Right$	RTrim$	Seek$

Space$	Str$	String$	Time$

Trim$	UCase$

Note   The double-byte versions of Input (InputB), Left (LeftB), Mid (MidB), and Right (RightB) also support the appended $ syntax.


Saving Space with Data Types

Integers take the least amount of space in your computer's memory.  For example, you can fit eight integers (8 * 2 bytes) in the space used by one variant (16 bytes).  However, in most cases, using data types to save memory space is of limited value.  In general, you should not encounter memory storage limits unless your code contains, or you inadvertantly create, enormous arrays or recursive procedures.


Scoping Levels

A Visual Basic program has three scoping levels that determine where and when an identifier is recognized (visible), as illustrated in the following table:

Visible in	Declared with	Referenced as
Procedure only.	Dim or Static, declared inside a procedure.	variablename
Module (all procedures in module).	Dim, Static, Private, declared outside all procedures.	[modulename.]variablename
Project (all procedures in all modules in current project, and all referencing projects).	Public, declared outside all procedures.	[projectname.[modulename.]]variablename


Using Data Types Efficiently

Unless otherwise specified, undeclared variables are assigned the Variant data type.  This data type makes it easy to write programs, but it is not always the most efficient data type to use.

You should consider using other data types if:

•	Your program is very large and uses many variables.

•	Your program needs to run as quickly as possible.

•	Your code is tightly structured, and you wish to detect when data of one type must be converted to another type.

•	You write data directly to random-access files.

In addition to the Variant type, supported data types include: Boolean, Integer, Long, Single, Double, Currency, Date, Object, and String.  Use the Dim statement to declare a variable of a specific type, for example:

Dim X As Integer

This statement declares that X is an integer [image] a whole number between -32,768 and 32,767.  If you try to set X to a number outside that range, you will get an error.  If you try to set X to a fraction, the number is rounded.  For example:

X = 32768 	   ' Causes error

X = 5.9	' Sets x to 6.


Working Across Applications

Visual Basic can create new objects and retrieve existing objects from these Microsoft applications:

Application	Object type	Class
Microsoft Excel, version 5.0	Application	Excel.Application
	Worksheet	Excel.Sheet
	Chart	Excel.Chart
Microsoft Project, version 4.0	Application	MSProject.Project
Microsoft Word, version 6.0	WordBasic	Word.Basic
Note that later versions of Microsoft Excel, Project, and Word may allow you to create additional objects from other applications using Visual Basic.  Other applications may also provide objects that you can create using Visual Basic.  See your application's documentation for more information.

To create an new object or get an existing object from another application, use the CreateObject or GetObject functions:

' Start Microsoft Excel and create a new Worksheet object.

Set ExcelWorksheet = CreateObject("Excel.Sheet")

' Start Microsoft Excel and open an existing Worksheet object.

Set ExcelWorksheet = GetObject("SHEET1.XLS")

' Start Microsoft Word.

Set WordBasic = CreateObject("Word.Basic")

Different applications behave in different ways when started with CreateObject or GetObject.  For example, Microsoft Excel starts up invisibly; Microsoft Word starts up visibly.  While Microsoft Excel is invisible, it is not displayed on the screen or in the Windows Task List.  To display Microsoft Excel and add it to the Task List, set its Visible property to True.  For example:

ExcelWorksheet.Application.Visible = True

Setting Microsoft Excel's Visible property to False makes the application invisible and removes it from the Task List.  Microsoft Excel does not close, however, and is still available to Visual Basic.

Microsoft Word closes when its object variable is set to Nothing or goes out of scope.  If you don't save changes before this happens, edits will be lost.  For example:

' Save changes and close Word.

WordBasic.FileSaveAll

Set WordBasic = Nothing

Microsoft Excel closes if it is invisible when its object variable is set to Nothing or goes out of scope.

' If Microsoft Excel is invisible it will close. If not, it stays open.

Set ExcelWorksheet = Nothing

Most applications also provide an Exit or Quit method that closes the application whether or not it is visible.  For more information on the objects, methods, and properties an application provides, see the application's documentation.


Writing Data to Files

When working with large amounts of data, it is often convenient to write data to or read data from a file.  The Open statement lets you create and access files directly.  Open provides three types of file access:

•	Sequential access (Input, Output, and Append modes), commonly used for writing simple text files, such as error logs and reports.

•	Random access (Random mode), used whenever you need to read and write data to a file without closing it.  Random access files keep data in records, which makes it easy to locate information quickly.

•	Binary access (Binary mode), used in some specialized cases where you need to read or write to any byte position in a file, such as when storing or displaying a bitmap image.

The following table shows the statements typically used when writing data to and reading data from files.

Access Type	Writing Data	Reading Data

Sequential	Print #, Write #	Input #

Random	Put	Get

Binary	Put	Get

Input #, Print #, and Write # read and write data one line at a time.  For example:

Open "LOG.TXT" For Append As #1	' Append creates a file if it doesn't

Print #1, "Printing line to file."	' already exist.

Write #1, "Writing line to file."

Close #1

Open "LOG.TXT" For Input As #1

Do Until EOF(1)

Input #1, FileData

Print FileData	' Displays text.

Loop

Close #1

Get and Put read and write data as records.  The size of a record is determined by the variable's data type.  For example:

Dim MyData As Integer	' MyData is 2 bytes long.

Open "DATA.REC" For Random As #1

For RecordNumber = 1 To 10

MyData = I * I

Put #1, RecordNumber, MyData	' Write data to file.

Next RecordNumber

For RecordNumber = 1 To 10

MyData = I * I

Get #1, RecordNumber, MyData	' Read data from file.

Print MyData

Next RecordNumber

Close #1

When writing and reading random-access files, it is common to use user-defined data types declared with the Type statement.

Note   Print # writes user-readable/localized data.  Write # writes data in a language-independent form.


Writing Maintainable Programs

Variables of the Variant data type accept almost any data you assign to them.  This is convenient, but it can hide errors.  If you are writing programs that are used or maintained by many different people, it is best to use nonvariant data types and the Option Explicit statement.

Nonvariant data types cause an error if you try to assign data to a variable that is not appropriate.  For example:

Dim NumVar As Integer

Dim StrVar as String

StrVar = "This is some text"

NumVar = StrVar	' Error The data types don't match.

NumVar = 40000	' Too big Causes "Overflow" error.

Nonvariant data types perform some conversions.  For instance, floating point numbers are rounded up or down if they are assigned to a variable with an Integer data type.  If you want to convert a string to a numeric data type, however, you must use one of the data type conversion functions.

Normally, you are not required to declare variables before you use them.  Again, this is convenient, but can lead to errors if you accidentally misspell a variable name.  To catch this type of error, use the Option Explicit statement.  For example:

Option Explicit

Sub ReadValues()

Dim NumVar As Integer

Dim StrVar As String

For NumVar = 0 to 9

StrVar = "Some text"	' Error misspelled the variable.

Next NumVar

End Sub

Without Option Explicit, this type of error would not be caught and you would have a hard time finding it.


Call Statement

Transfers control to a Sub procedure, Function procedure, dynamic-link library (DLL) procedure, or a Macintosh code resource procedure.

Syntax

[Call] name [argumentlist]

Elements

The Call statement syntax has these parts:

Part	Description

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

Call MyProc(0)

name	Name of the procedure to call.

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

Remarks

You are never required to use the Call keyword when calling a procedure.  However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses.  If you omit the Call keyword, you also must omit the parentheses around argumentlist.  If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.


DoEvents Statement

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

Syntax

DoEvents

Remarks

DoEvents passes control to the operating system.  Control is not returned until the operating system has finished processing the events in its queue and, for Microsoft Windows only, all keys in the SendKeys queue have been sent.

If parts of your code take up too much processor time, use DoEvents periodically to relinquish control to the operating system so that events, such as keyboard input and mouse clicks, can be processed without significant delay.

Caution   Make sure the procedure that has given up control with DoEvents is not executed again from a different part of your code before the first DoEvents call returns; this could cause unpredictable results.  In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.


Do...Loop Statement

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax 1

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Syntax 2

Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until}condition]

Elements

The Do...Loop statement syntax has these parts:

Part	Description

condition	Expression that is True or False.

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

Remarks

The Exit Do can only be used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop.  Any number of Exit Do statements may be placed anywhere in the Do...Loop.  Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.


End Statement

Ends a procedure or block.

Syntax

End

End Function

End If

End Property

End Select

End Sub

End Type

End With

Elements

The End statement syntax has these forms:

Statement	Description

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

End Function	Required to end a Function statement.

End If	Required to end a block If...Then...Else statement.

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

End Select	Required to end a Select Case statement.

End Sub	Required to end a Sub statement.

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

End With	Required to end a With statement.

Remarks

Note   When executed, the End statement resets all module-level variables and all static local variables in all modules.  If you need to preserve the value of these variables, use Stop instead.  You can then resume execution while preserving the value of those variables.


Exit Statement

Exits a block of Do...Loop, For...Next, Function, Sub, or Property code.

Syntax

Exit Do

Exit For

Exit Function

Exit Property

Exit Sub

Elements

The Exit statement syntax has these forms:

Statement	Description

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

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

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

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

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

Remarks

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


For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

Syntax

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

Elements

The For Each...Next statement syntax has these parts:

Part	Description

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

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

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

Important   When using For Each... Next with arrays, you can only read the value contained in the array elements indicated by the control variable element.  You cannot set the value by assigning a value to element.

Remarks

The For Each block is entered if there is at least one element in group.  Once the loop has been entered, all the statements in the loop are executed for the first element in group.  Then, as long as there are more elements in group, the statements in the loop continue to execute for each element.  When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the loop.  The Exit For is often used with the evaluation of some condition (for example, If...Then),  and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one For Each...Next loop within another.  However, each loop element must be unique.

Note   If you omit element in a Next statement, execution continues as if you had included it.  If a Next statement is encountered before its corresponding For statement, an error occurs.

You can't use the For Each...Next statement with an array of user-defined types because a Variant can't contain a user-defined type.


For...Next Statement

Repeats a group of statements a specified number of times.

Syntax

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

Elements

The For...Next statement syntax has these parts:

Part	Description

counter	Numeric variable used as a loop counter.  The variable can't be any array element or any element of a user-defined type.

start	Initial value of counter.

end	Final value of counter.

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

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

Remarks

The step argument can be either positive or negative.  The value of the step argument determines loop processing as follows:

Value	Loop executes if

Positive or 0	counter <= end

Negative	counter >= end

Once the loop starts and all statements in the loop have executed, step is added to counter.  At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip   Changing the value of counter while inside a loop can make it more difficult to read and debug.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the loop.  The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another.  Give each loop a unique variable name as its counter.  The following construction is correct:

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

. . .

Next K

Next J

Next I

Note   If you omit counter in a Next statement, execution continues as if you had included it.  If a Next statement is encountered before its corresponding For statement, an error occurs.


GoSub...Return Statement

Branch to and return from a subroutine within a procedure.

Syntax

GoSub line
. . .
line
. . .
Return

Elements

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return must be in the same procedure.  A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note   You can't enter or exit Sub procedures with GoSub...Return.

Tip   Creating separate procedures which you can call may provide a more structured alternative to using GoSub...Return.


GoTo Statement

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

Elements

The line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

Note   Too many GoTo statements can be difficult to read and debug.  Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.


If...Then...Else Statement

Conditionally executes a group of statements, depending on the value of an expression.

Syntax 1

If condition Then statements [Else elsestatements ]

Syntax 2

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If

Elements

Syntax 1 has these parts:

Part	Description

condition	Numeric or string expression that evaluates True or False.

statements	One or more statements separated by colons; executed if condition is True.

elsestatements	One or more statements separated by colons; executed if condition is False.

Syntax 2 has these parts:

Part	Description

condition	Expression that is True or False.

statements	One or more statements executed if condition is True.

condition-n	Numeric or string expression that evaluates True or False.

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

elsestatements	One or more statements executed if no previous condition-n expressions are True.

Remarks

You can use the single-line form (Syntax 1) for short, simple tests.  However, the block form (Syntax 2) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note   With Syntax 1 it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by colons, as in the following statement:

If A > 10 Then A = A + 1 : B = B + A : C = C + B

When executing a block If (Syntax 2), condition is tested.  If condition is True, the statements following Then are executed.  If condition is False, each ElseIf condition (if any) is evaluated in turn.  When a True condition is found, the statements immediately following the associated Then are executed.  If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed.  After executing the statements following Then or Else, execution continues with the statement following End If.

The Else and ElseIf clauses are both optional.  You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause.  Block If statements can be nested; that is, contained within one another.

What follows the Then keyword is examined to determine whether or not a statement is a block If.  If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

A block If statement must be the first statement on a line.  The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them.  The block If must end with an End If statement.

Tip   Select Case may be more useful when evaluating a single expression that has several possible actions.


On...GoSub, On...GoTo Statements

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoSub destinationlist

On expression GoTo destinationlist

Elements

The On...GoSub and On...GoTo statement syntax has these parts:

Part	Description

expression	Any numeric expression that evaluates to a whole number between 0 and 255, inclusive.  If expression is any number other than a whole number, it is rounded before it is evaluated.

destinationlist	List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line in destinationlist is branched to.  If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

If expression is:	Then

Equal to 0	Control drops to the statement following On...GoSub or On...GoTo.

Greater than number of items in list	Control drops to the statement following On...GoSub or On...GoTo.

Negative 	An error occurs.

Greater than 255	An error occurs.

You can mix line numbers and line labels in the same list.  There is no practical limit to the number of line labels and line numbers you can use with On...GoSub and On...GoTo.  However, if you use more labels or numbers than will fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

Tip   Select Case provides a more structured and flexible way to perform multiple branching.


Select Case Statement

Executes one of several groups of statements, depending on the value of an expression.

Syntax

Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else
[elsestatements]]
End Select

Elements

The Select Case statement syntax has these parts:

Part 	Description

testexpression	Any numeric or string expression.

expressionlist-n	Comma-delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression.  The To keyword specifies a range of values.  If you use the To keyword, the smaller value must appear before To.  Use the Is keyword with comparison operators (except Is and Like) to specify a range of values.  If not supplied, the Is keyword is automatically inserted.

statements-n	One or more statements executed if testexpression matches any part of expressionlist-n.

elsestatements	One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks

If testexpression matches any expressionlist expression associated with a Case clause, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to the End Select.  Control then passes to the statement following End Select.  If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the statements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections.  When there is no Case Else statement and no expression listed in the Case clauses matches testexpression, execution continues at the statement following End Select.

Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values.

You can use multiple expressions or ranges in each Case clause.  For example, the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

Note   The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings.  In the following example, Case matches strings that are exactly equal to everything,strings that fall between nuts and soup in alphabetical order, and the current value of TestItem:

Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested.  Each Select Case statement must have a matching End Select statement.


Shell Function

Runs an executable program.

Syntax

Shell(pathname[,windowstyle])

Elements

The Shell function syntax has these named-argument parts:

Part	Description

pathname	Name of the program to execute and any required arguments or command line switches; may include directory or folder and drive.  May also be the name of a document that has been associated with an executable program.

On the Macintosh, you can use the MacID function to specify an application's signature instead of its name.  The following example uses the signature for Microsoft Word:

Shell MacID("MSWD")

windowstyle	Number corresponding to the style of the window in which the program is to be run.  In Microsoft Windows, if windowstyle is omitted, the program is started minimized with focus.  On the Macintosh (System 7.0 or later), windowstyle only determines whether or not the application gets the focus when it is run.

The windowstyle named argument has these values:

Value	Window Style

1, 5, 9	Normal with focus.

2	Minimized with focus.

3	Maximized with focus.

4,8	Normal without focus.

6,7	Minimized without focus.

Remarks

If you use the MacID function with Shell in Microsoft Windows, an error occurs.

If the Shell function successfully executes the named file, it returns the task identification (ID) of the started program.  The task ID is a unique number that identifies the running program.  If the Shell function can't start the named program, an error occurs.

Note   The Shell function runs other programs asynchronously.  This means you can't depend on a program started with Shell to be finished executing before the statements following the Shell function in your application are executed.


Stop Statement

Suspends execution.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend execution.  Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables.


While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax

While condition
[statements]
Wend

Elements

The While...Wend statement syntax has these parts:

Part	Description

condition	Numeric or string expression that evaluates to True or False.

statements	One or more statements executed while condition is True.

Remarks

If condition is True, all statements in statements are executed until the Wend statement is encountered.  Control then returns to the While statement and condition is again checked.  If condition is still True, the process is repeated.  If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level.  Each Wend matches the most recent While.

Caution   Do not branch into the body of a While...Wend loop without executing the While statement.  Doing so may cause run-time errors or other problems that are difficult to locate.

Tip   The Do...Loop statement provides a more structured and flexible way to perform looping.


With Statement

Executes a series of statements on a single object or a user-defined type.

Syntax

With object
[statements]
End With

Elements

The With statement syntax has these parts:

Part	Description

object	Name of an object or a user-defined type.

statements	One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object.  For example, if you have a number of different properties to change on a single object, it is more convenient to place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment.  The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel

.Height = 2000

.Width = 2000

.Caption = "This is MyLabel"

End With

You can nest With statements by placing one With loop within another.  Each object must be unique.


Call Statement Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, a dynamic-link library (DLL) procedure and a procedure in a Macintosh code resource.

' Call a Sub procedure.

Call PrintToDebugWindow("Hello World")

' The above statement causes control to be passed to the following

' Sub procedure.

Sub PrintToDebugWindow(AnyString)

Debug.Print AnyString	' Print to Debug window.

End Sub

' Call an intrinsic function. The return value of the function is

' discarded.

Call Shell(AppName, 1)	' AppName contains the path of the

' executable.

' Call a Microsoft Windows DLL procedure.

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

Sub CallMyDll()

Call MessageBeep(0)	' Call Windows DLL procedure.

MessageBeep 0	' Call again without Call keyword.

End Sub

' Call a Macintosh Code Resource.

Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _

As Integer)

Sub CallMyCodeResource()

Call MessageAlert(0)	' Call Macintosh code resource.

MessageAlert 0	' Call again without Call keyword.

End Sub


DoEvents Statement Example

This example uses the DoEvents Statement to cause execution to yield to the operating system once every 1000 iterations of the loop.

For I = 1 To 150000	' Start loop.

If I Mod 1000 = 0 Then 	' If loop has repeated 1000 times.

DoEvents	' Yield to operating system.

End If

Next I	' Increment loop counter.


Do...Loop Statement Example

This example shows how Do...Loop statements can be used.  The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement.  The outer loop exits immediately upon checking the value of the flag.

Check = True : Counter = 0	' Initialize variables.

Do	' Outer Loop.

Do While Counter < 20	' Inner Loop.

Counter = Counter + 1	' Increment Counter.

If Counter = 10 Then	' If condition is true.

Check = False	' Set value of flag to False.

Exit Do	' Exit inner loop.

End If

Loop

Loop Until Check = False	' Exit outer loop immediately.


End Statement Example

This example uses the End Statement to end code execution, a Select Case block, and a Sub procedure.

Sub EndStatementDemo()

For Number = 1 To 2	' Loop 2 times.

Select Case Number	' Evaluate Number.

Case 1	' If Number equals 1.

Debug.Print Number 	' Print value to Debug window.

Case Else	' If Number does not equal 1.

End	' Terminate procedure execution.

End Select	' End of Select Case Statement.

Next Number

End Sub	' End of Sub procedure.


Exit Statement Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Sub ExitStatementDemo()

Do	' Set up infinite loop.

For I = 1 To 1000	' Loop 1000 times.

MyNum = Int(Rnd * 1000)	' Generate random numbers.

Select Case MyNum	' Evaluate random number.

Case 7: Exit For	' If 7, exit For...Next.

Case 29: Exit Do	' If 29, exit Do...Loop.

Case 54: Exit Sub	' If 54, exit Sub procedure.

End Select

Next I

Loop

End Sub


For Each...Next Statement Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello".  In the example, MyObject is a text-related object and is an element of the collection MyCollection.  Both are generic names used for illustration purposes only.

Found = False	' Initialize variable.

For Each MyObject In MyCollection	' Iterate through each element.

If MyObject.Text = "Hello" Then	' If Text equals "Hello".

Found = True	' Set Found to True.

Exit For	' Exit loop.

End If

Next


For...Next Statement Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space.  The outer loop uses a loop counter variable that is decremented each time through the loop.

For Words = 10 To 1 Step -1 	' Set up 10 repetitions.

For Chars = 0 To 9	' Set up 10 repetitions.

MyString = MyString & Chars	' Append number to string.

Next Chars

MyString = MyString & " "	' Append a space.

Next Words


GoSub...Return Statement Example

This example uses GoSub to call a subroutine within a Sub procedure.  The Return statement causes the execution to resume at the statement immediately following the Gosub statement.  The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Sub GosubDemo()

Num = 10	' Initialize variable.

GoSub MyRoutine	' Branch to subroutine.

Debug.Print Num	' Print value upon return.

Exit Sub	' Exit Sub procedure.

MyRoutine:	' Start of subroutine.

Num = Num \ 2	' Halve the value.

Return	' Return from subroutine.

End Sub


GoTo Statement Example

This example uses the GoTo statement to branch to line labels within a procedure.

Sub GotoStatementDemo()

Number = 1 	' Initialize variable.

' Evaluate Number and branch to appropriate label.

If Number = 1 Then GoTo Line1 Else GoTo Line2

Line1:

MyString = "Number equals 1"

GoTo LastLine	' Go to LastLine.

Line2:

' The following statement never gets executed.

MyString = "Number equals 2"

LastLine:

Debug.Print MyString	' Print 1 in Debug window.

End Sub


If...Then...Else Statement Example

This example shows uses of the If...Then...Else statement.

Number = 53	' Initialize variable.

If Number < 10 Then

Digits = 1

ElseIf Number < 100 Then

' Condition evaluates to True so the next statement is executed.

Digits = 2

Else

Digits = 3

End If

' Assign a value using the single line form of syntax.

If Digits = 1 Then MyString = "One" Else MyString = "More than one"


On...GoSub, On...GoTo Statements Example

This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels respectively.

Sub OnGosubGotoDemo()

Number = 2	' Initialize variable.

' Branch to Sub2.

On Number GoSub Sub1, Sub2	' Execution resumes here after

' On...GoSub.

On Number GoTo Line1, Line2	' Branch to Line2.

' Execution does not resume here after On...GoTo.

Exit Sub

Sub1:

MyString = "In Sub1" : Return

Sub2:

MyString = "In Sub2" : Return

Line1:

MyString = "In Line1"

Line2:

MyString = "In Line2"

End Sub


Select Case Statement Example

This example uses the Select Case statement to evaluate the value of a variable.  The second Case clause contains the value of the variable being evaluated and therefore only the statement associated with it is executed.

Number = 8	' Initialize variable.

Select Case Number	' Evaluate Number.

Case 1 To 5	' Number between 1 and 5.

MyString = "Between 1 and 5"

Case 6, 7, 8, 9, 10	' Number between 6 and 10.

' This is the only Case clause that evaluates to True.

MyString = "Between 6 and 10"

Case Else	' Other values.

MyString = "Not between 1 and 10"

End Select


Shell Function Example

This example uses the Shell function to run an application specified by the user.  On the Macintosh, using the MacID function ensures that the application can be launched even if the file name of the application has been changed.  The Shell function is not available on the Macintosh prior to System 7.0.

' In Microsoft Windows.

' Specifying 1 as the second argument runs the application normally and

' gives it the focus.

RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)	' Run Calculator.

' On the Macintosh.

' Both statements launch Microsoft Excel.

RetVal = Shell("Microsoft Excel")	' Specify file name.

RetVal = Shell(MacID("XCEL"))	' Specify signature.


Stop Statement Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

For I = 1 To 10	' Start For...Next loop.

Debug.Print I	' Print I to Debug window.

Stop	' Stop each time through.

Next I


While...Wend Statement Example

This example uses the While...Wend statement to increment a counter variable.  The statements in the loop are executed as long as the condition evaluates to True.

Counter = 0	' Initialize variable.

While Counter < 20	' Test value of Counter.

Counter = Counter + 1	' Increment Counter.

Wend

Debug.Print Counter	' Prints 20 in Debug window.


With Statement Example

This example uses the With statement to execute a series of statements on a single object.  The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject

' Same as MyObject.Height = 100

.Height = 100

.Caption = "Hello World"

With .Font

' Same as MyObject.Font.Color = Red.

.Color = Red

.Bold = True

End With

End With


Date Function

Returns the current system date.

Syntax

Date

Remarks

To set the system date, use the Date statement.


Date Statement

Sets the current system date.

Syntax

Date = date

Elements

For MS-DOS computers, the date argument must be a date from January 1, 1980 through December 31, 2099, or an error occurs.  For the Macintosh, date must be a date from January 1, 1904 through December 31, 2040.  For all other systems, date is limited to dates from January 1, 100 through December 31, 9999.

Remarks

Note   If you use the Date statement to set the date on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the date on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


DateSerial Function

Returns a date for a specified year, month, and day.

Syntax

DateSerial(year,month,day)

Elements

The DateSerial function syntax has these named-argument parts:

Part	Description

year	Number between 100 and 9999, inclusive, or a numeric expression.

month	Number between 1 and 12, inclusive, or a numeric expression.

day	Number between 1 and 31, inclusive, or a numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the normally accepted range for the unit; that is; 1-31 for days and 1-12 for months.  However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.

The following example uses numeric expressions instead of absolute date numbers.  Here the DateSerial function returns a date that is the day before the first day (1 - 1) of two months before August (8 - 2) of 10 years before 1990 (1990 - 10); in other words, May, 31, 1980.

DateSerial(1990 - 10, 8 - 2, 1 - 1)

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900-1999.  For all other year arguments, use a complete four-digit year (for example, 1800).

If the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.


DateValue Function

Returns a date.

Syntax

DateValue(date)

Elements

The date named argument is normally a string expression representing a date from January 1, 100 through December 31, 9999.  However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

Remarks

If the date argument includes time information, DateValue doesn't return it.  However, if date includes invalid time information (such as "89:98"), an error occurs.

If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format you specified for your system.  DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form.  For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of date is omitted, DateValue uses the current year from your computer's system date.


Day Function

Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Syntax

Day(date)

Elements

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date.  If date contains no valid data, Null is returned.


Hour Function

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Syntax

Hour(time)

Elements

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time.  If time contains no valid data, Null is returned.


Minute Function

Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.

Syntax

Minute(time)

Elements

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time.  If time contains no valid data, Null is returned.


Month Function

Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Syntax

Month(date)

Elements

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date.  If date contains no valid data, Null is returned.


Now Function

Returns the current date and time according to the setting of your computer's system date and time.

Syntax

Now

Remarks

Note   When displayed directly, the Now function's return value is displayed as a string using the short date and time formats you specified for your system.


Second Function

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second(time)

Elements

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time.  If time contains no valid data, Null is returned.


Time Function

Returns the current system time.

Syntax

Time

Remarks

To set the system time, use the Time statement.


Time Statement

Sets the system time.

Syntax

Time = time

Elements

The time argument is limited to expressions that can represent a time.  If time contains no valid data, Null is returned.

Remarks

If time is a string, Time attempts to convert it to a time using the time separators you specified for your system.  If it can't be converted to a valid time, an error occurs.

Note   If you use the Time statement to set the time on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the time on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


Timer Function

Returns the number of seconds elapsed since midnight.

Syntax

Timer

Remarks

The return value of the Timer function is automatically used with the Randomize statement to generate a seed for the Rnd (random-number) function.


TimeSerial Function

Returns a date containing the time for a specific hour, minute, and second.

Syntax

TimeSerial(hour,minute,second)

Elements

The TimeSerial function syntax has these named-argument parts:

Part	Description

hour	Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

minute	Number between 0 and 59, inclusive, or a numeric expression.

second	Number between 0 and 59, inclusive, or a numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normally accepted range for the unit; that is, 0-23 for hours and 0-59 for minutes and seconds.  However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time.  The following example uses expressions instead of absolute time numbers.  The TimeSerial function returns a time for 15 minutes before (0 - 15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, 0 - 15, 0)

If the time specified by the three arguments, either directly or by expression, falls outside the acceptable range of times, an error occurs.


TimeValue Function

Returns a time.

Syntax

TimeValue(time)

Elements

The time named argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive.  However, time can also be any expression that represents a time in that range.  If time contains no valid data, Null is returned.

Remarks

You can enter valid times using a 12- or 24-hour clock.  For example, "2:24PM" and "14:24" are both valid time arguments.

If the time argument contains date information, TimeValue doesn't this information.  However, if time includes invalid date information, an error occurs.


Weekday Function

Returns a whole number representing the day of the week.

Syntax

Weekday(date)

Elements

The date named argument is limited to numbers or strings, in any combination, that can represent a date.  If date contains no valid data, Null is returned.

Return Values

Value	Description

1	Sunday

2	Monday

3	Tuesday

4	Wednesday

5	Thursday

6	Friday

7	Saturday


Year Function

Returns a whole number representing the year.

Syntax

Year(date)

Elements

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date.  If date contains no valid data, Null is returned.


Boolean Data Type

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.  Boolean variables display as either True or False (when Print is used) or #TRUE# or #FALSE# (when Write # is used).  Use the keywords True and False to assign one of  the two states to Boolean variables.

When other numeric data types are converted to Boolean values, 0 becomes False while all other values become True.  When Boolean values are converted to other data types, False becomes 0 while True becomes -1.


Currency Data Type

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

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.


Data Type Summary

The following table shows the supported data types, including their storage sizes and ranges.

Data type	Storage size	Range
Boolean	2 bytes	True or False.
Integer	2 bytes	-32,768 to 32,767.
Long (long integer)	4 bytes	-2,147,483,648 to 2,147,483,647.
Single (single-precision floating-point)	4 bytes	-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double (double-precision floating-point)	8 bytes	-1.79769313486232E308 to  -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency (scaled integer)	8 bytes	-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date	8 bytes	January 1, 100 to December 31, 9999.
Object	4 bytes	Any Object reference.
String	1 byte per character	0 to approximately 2 billion (approximately 65,535 for Microsoft Windows version 3.1 and earlier).
Variant	16 bytes + 1 byte for each character	Any numeric value up to the range of a Double or any character text.
User-defined (using Type)	Number required by elements	The range of each element is the same as the range of its data type.


Date Data Type

Date variables are stored as 64-bit (8-byte) numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59.  Any recognizable literal date values can be assigned to Date variables.  Literal dates must be enclosed within number sign characters (#).  For example, #January 1, 1993# or #1 Jan 93#.

Date variables display dates according to the short date format recognized by your computer.  Times display according to the time format (either 12- or 24-hour) recognized by your computer.

When other numeric data types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time.  Midnight is 0 and midday is .5.  Negative whole numbers represent dates before 30 December 1899.  When Date variables are converted to other numeric data types, they appear only as numbers.


Double Data Type

Double (double-precision floating-point) variables are stored as 64-bit (8-byte) numbers ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values.  The type-declaration character for Double is # (character code 35).


Integer Data Type

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767.  The type-declaration character for Integer is % (character code 37).

You can also use Integer variables to represent enumerated values.  An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used.  Enumerated values provide a convenient way to select among a known number of choices. For example, when asking the user to select a color from a list, you could have 0 = black, 1 = white, and so on.  It is good programming practice to define constants using the Const statement for each enumerated value.


Long Data Type

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647.  The type-declaration character for Long is & (character code 38).


Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application.  A variable declared as an Object is one that can subsequently be assigned (using the Set statement) to refer to any object produced by the application.


Single Data Type

Single (single-precision floating-point) variables are stored as 32-bit (4-byte) numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values.  The type-declaration character for Single is ! (character code 33).


String Data Type

There are two kinds of strings:

•	Variable-length strings, which can contain up to approximately 2 billion (2^31) characters (approximately 64K (2^16) characters for Microsoft Windows version 3.1 and earlier).

•	Fixed-length strings, which contain a declared number of characters (less than 64K).

The type-declaration character for String is $ (character code 36).  The codes for String characters range from 0 to 255.  The first 128 characters (0-127) of the character set correspond to the letters and symbols on a standard U.S. keyboard.  These first 128 characters are the same as those defined by the ASCII character set.  The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


User-Defined Data Type

Any data type you define using the Type statement.  User-defined data types can contain one or more elements of any data type, array, or a previously defined user-defined type.  For example:

Type MyType

MyName As String	' String variable stores a name.

MyBirthDate As Date	' Date variable stores a birthdate.

MySex as Integer	' Integer variable stores sex (0 for

End Type	' female, 1 for male.


Variant Data Type

The Variant data type is the data type that all variables become if not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static).  The Variant data type has no type-declaration character.

The Variant is a special data type that can contain any kind of data as well as the special values Empty, Error, and Null.  You can determine how the data in a Variant is treated using the VarType or TypeName function.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values.  Generally, numeric Variant data is maintained in its original data type within the Variant.  For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer.  However, if an arithmetic operation is performed on a Variant containing an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type.  An Integer is promoted to a Long, and a Long and a Single are promoted to a Double.  An error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

You can use the Variant data type in place of any data type to work with data in a more flexible way.  If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context.  For example:

Dim MyVar As Variant

MyVar = 98052

In the example shown above, MyVar contains a numeric representation [image] the actual value 98052.  Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers.  If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum.  See the information about addition and concatenation operators for complete information on how to use them with Variant data.

The value Empty denotes a Variant variable that hasn't been initialized (assigned an initial value).  A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string ("") if it is used in a string context.

Don't confuse Empty with Null.  Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure.  However, unlike for other kinds of errors, normal application-level error handling does not occur.  This allows the programmer, or the application itself, to take some alternative based on the error value.  Error values are created by converting real numbers to error values using the CVErr function.


Date Function Example

This example uses the Date function to return the current system date.

MyDate = Date	' MyDate contains current system date.


Date Statement Example

This example uses the Date statement to set the computer system date.

' In the development environment, the date literal will display in short

' format using the locale settings of your code.

MyDate = #February 12, 1985#	' Assign a date.

Date = MyDate	' Change system date.


DateSerial Function Example

This example uses the DateSerial function to return the date for the specified year, month and day.

' MyDate contains the date for February 12, 1969.

MyDate = DateSerial(1969, 2, 12)	' Return a date.


DateValue Function Example

This example uses the DateValue function to convert a string to a date.  In general, it is bad programming practice to hard code dates/times as strings as shown in this example.  Use date literals instead.

MyDate = DateValue("February 12, 1969")	' Return a date.


Day Function Example

This example uses the Day function to obtain the day of the month from a specified date.

' In the development environment, the date literal will display in short

' format using the locale settings of your code.

MyDate = #February 12, 1969#	' Assign a date.

MyDay = Day(MyDate)	' MyDay contains 12.


Hour Function Example

This example uses the Hour function to obtain the hour from a specified time.

' In the development environment, the time (date literal) will display

' in short format using the locale settings of your code.

MyTime = #4:35:17 PM#	' Assign a time.

MyHour = Hour(MyTime)	' MyHour contains 16.


Minute Function Example

This example uses the Minute function to obtain the minute of the hour from a specified time.

' In the development environment, the time (date literal) will display

' in short format using the locale settings of your code.

MyTime = #4:35:17 PM#	' Assign a time.

MyMinute = Minute(MyTime)	' MyMinute contains 35.


Month Function Example

This example uses the Month function to obtain the month from a specified date.

' In the development environment, the date literal will display in short

' format using the locale settings of your code.

MyDate = #February 12, 1969#	' Assign a date.

MyMonth = Month(MyDate)	' MyMonth contains 2.


Now Function Example

This example uses the Now function to return the current system date and time.

Today = Now	' Get current system date and time.


Second Function Example

This example uses the Second function to obtain the second of the minute from a specified time.

' In the development environment, the time (date literal) will display

' in short format using the locale settings of your code.

MyTime = #4:35:17 PM#	' Assign a time.

MySecond = Second(MyTime)	' MySecond contains 17.


Time Function Example

This example uses the Time function to return the current system time.

MyTime = Time	' Return current system time.


Time Statement Example

This example uses the Time statement to set the computer system time to a user-defined time.

MyTime = #4:35:17 PM#	' Assign a time.

Time = MyTime	' Set system time to MyTime.


Timer Function Example

This example uses the Timer function to record the number of seconds taken to print output to the Debug window.

Start = Timer	' Set start time.

For I = 1 to 50	' Loop 50 times.

Debug.Print I	' Print to Debug window.

Next I

Finish = Timer	' Set end time.

TotalTime = Finish - Start	' Calculate total time.


TimeSerial Function Example

This example uses the TimeSerial function to return a time for the specified hour, minute and second.

' MyTime contains the time for 4:35:17 PM

MyTime = TimeSerial(16, 35, 17)	' Return time.


TimeValue Function Example

This example uses the TimeValue function to convert a string to a time.  In general, it is bad programming practice to hard code dates/ times as strings as shown in this example.  Use date literals instead.

MyTime = TimeValue("4:35:17 PM")	' Return time.


Weekday Function Example

This example uses the Weekday function to obtain the day of the week from a specified date.

MyDate = #February 12, 1969#	' Assign a date.

MyWeekDay = Weekday(MyDate)	' MyWeekDay contains 4 since it

' was a Wednesday.


Year Function Example

This example uses the Year function to obtain the year from a specified date.

' In the development environment, the date literal will display in short

' format using the locale settings of your code.

MyDate = #February 12, 1969#	' Assign a date.

MyYear = Year(MyDate)	' MyYear contains 1969.


Array Function

Returns a Variant containing an array.

Syntax

Array(arglist)

Elements

The arglist consists of  a comma-delimited list of an arbitrary number of values that are assigned to the elements of the array contained within the Variant.  If no arguments are specified, an array of zero-length is created.

Remarks

Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the way the array elements are accessed is the same.  The notation used to refer to any element of an array consists of the variable name followed by parentheses containing an index number to the desired element.  In the following example, the first statement creates a variable A as a Variant.  The second statement assigns an array to the variable A.  The final statement illustrates how to assign the value contained in the second array element to another variable.

Dim A As Variant

A = Array(10,20,30)

B = A(2)

The lower bound of an array created using the Array function is determined by the lower bound specified with the Option Base statement.


Const Statement

Declares constants for use in place of literal values.

Syntax

[Public | Private] Const constname [As type] = expression

Elements

The Const statement syntax has these parts:

Part	Description

Public	Used at module level to declare constants that are available to all procedures in all modules.  Not allowed in procedures.

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

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

type	Data type of the constant; may be Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant.  Use a separate As type clause for each constant being declared.

expression	Literal, other constant, or any combination including arithmetic or logical operators except Is.

Remarks

If not explicitly specified using either Public or Private, constants are Private by default.

Several constant declarations can be combined on the same line by separating each constant assignment with a comma.  If constant declarations are combined in this way, the Public or Private keywords, if used, apply to all of them.

You can't use string concatenation, variables, user-defined or intrinsic functions (such as Chr) in expressions assigned to constants.

If you don't explicitly declare the constant type (using As type), the constant is given a data type that is most appropriate for the expression provided.

Constants declared in Sub, Function, or Property procedures are local to that procedure.  A constant declared outside a procedure is defined throughout the module in which it is declared.   You can use constants anywhere you would use an expression.


Declare Statement

Used at module level to declare references to external procedures in a dynamic-link library (DLL) or Macintosh code resource.

Syntax 1

[Public | Private ] Declare Sub name [CDecl] Lib "libname" [Alias "aliasname" ][([arglist])]

Syntax 2

[Public | Private ] Declare Function name [CDecl] Lib "libname" [Alias "aliasname" ] [([arglist])][As type]

Elements

The Declare statement syntax has these parts:

Part	Description

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

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

Sub	Indicates that the procedure doesn't return a value.

Function	Indicates that the procedure returns a value that can be used in an expression.

name	Any valid procedure name.

CDecl	For the Macintosh only.  Indicates that the procedure uses C language argument order, naming conventions, and calling conventions.

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

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

Alias	Indicates that the procedure being called has another name in the DLL or is in a Macintosh code resource.  This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a Public variable or constant or any other procedure in the same scope.  Alias is also useful if any characters in the DLL procedure name aren't allowed in names.

aliasname	Name of the procedure in the DLL or code resource.

In Microsoft Windows, if the first character is not a #, aliasname is the name of the procedure's entry point in the DLL.  If # is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.

On the Macintosh, the syntax to specify the code resource type is as follows:

"[resourcetype]$[resourcename]"

The resourcetype is any valid 4-character constant. If omitted, the default  resourcetype is CODE.  The resourcename is the procedure name in the code resource.  If resourcename is omitted, it is assumed to be the same as name.

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

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

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part	Description

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

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

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

Remarks

For Function procedures, the data type of the procedure determines the data type it returns.  You can use an As clause following the arglist to specify the return type of the function.  Within arglist you can use an As clause to specify the data type of any of the arguments passed to the procedure.  In addition to specifying any of the standard data types, you can specify As Any in the arglist to inhibit type checking and allow any data type to be passed to the procedure.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that arguments should be checked to ensure that none are passed.  In the following example, First takes no arguments.  If you use arguments in a call to First, an error occurs:

Declare Sub First Lib "MyLib" ()

If you include an argument list, the number and type of arguments are checked each time the procedure is called.  In the following example, First takes one Long argument:

Declare Sub First Lib "MyLib" (X As Long)

Note   You can't have fixed-length strings in the argument list of a Declare statement because only variable-length strings can be passed to procedures.  Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed.


Deftype Statements

Used at module level to set the default data type for variables and Function procedures whose names start with the specified characters.

Syntax

DefBool letterrange[,letterrange] . . .

DefInt letterrange[,letterrange] . . .

DefLng letterrange[,letterrange] . . .

DefCur letterrange[,letterrange] . . .

DefSng letterrange[,letterrange] . . .

DefDbl letterrange[,letterrange] . . .

DefDate letterrange[,letterrange] . . .

DefStr letterrange[,letterrange] . . .

DefObj letterrange[,letterrange] . . .

DefVar letterrange[,letterrange] . . .

Elements

The argument letterrange has the following syntax:

letter1[-letter2]

The arguments letter1 and letter2 specify the name range for which you can set a default data type.  Each argument represents the first letter of the variable or Function procedure name and can be any letter of the alphabet.  The case of letters in letterrange isn't significant.

Remarks

The statement name determines the data type:

Statement	Data Type

DefBool	Boolean

DefInt	Integer

DefLng	Long

DefCur	Currency

DefSng	Single

DefDbl	Double

DefDate	Date

DefStr	String

DefObj	Object

DefVar	Variant

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

DefStr A-Q

. . .

Message = "Out of stack space."

A Deftype statement affects only the module where it is used.  For example, a DefInt statement in one module affects only the default data type of variables and Function procedures declared in that module; the default data type of variables in other modules is unaffected.  If not explicitly declared with a Deftype statement, the default data type for all variables and all Function procedures is Variant.

When you specify a letter range, it usually defines the data type for variables that begin with letters in the lower 128 characters of the character set.  However, when you specify the letter range A-Z, you set the default to the specified data type for all variables, including any that begin with international characters from the extended part of the character set (128-255).

Once the range A-Z has been specified, you can't further redefine any subranges of variables using Deftype statements.  In fact, once a range has been specified, if you include a previously defined letter in another Deftype statement, an error occurs.  However, you can explicitly specify the data type of any variable, defined or not, using a Dim statement with an As type clause.  For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:

DefInt A-Z

Dim TaxRate As Double

Deftype statements don't affect elements of user-defined types since they must be explicitly declared.


Dim Statement

Declares variables and allocates storage space.

Syntax

Dim varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

Elements

The Dim statement syntax has these parts:

Part	Description

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

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

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

type	Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module.  At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type or object type of a variable.  For example, the following statement declares a variable as an Integer.

Dim NumberOfEmployees As Integer

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it was a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public or Dim statement, an error occurs.

Tip   When you use the Dim statement in a procedure, it is a generally accepted programming practice to put the Dim statement at the beginning of the procedure.


Erase Statement

Reinitializes the elements of fixed-size arrays and deallocates dynamic-array storage space.

Syntax

Erase arraylist

Elements

The arraylist argument is one or more comma-delimited array variables to be erased.

Remarks

It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array.  No memory is recovered for fixed-size arrays.  Erase sets the elements of a fixed array as follows:

Type of array	Effect of Erase on fixed-array elements

Fixed numeric array	Sets each element to zero.

Fixed string array (variable length)	Sets each element to zero-length ("").

Fixed string array (fixed length)	Sets each element to zero.

Fixed Variant array	Sets each element to Empty.

Array of user-defined types	Sets each element as if it were a separate variable.

Array of objects	Sets each element to the special value Nothing.

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


Function Statement

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private][Static] Function name [(arglist)][As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function

Elements

The Function statement syntax has these parts:

Part	Description

Public	Indicates that the Function procedure is accessible to all other procedures in all modules.  If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.

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

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

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

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

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

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

expression	Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part	Description

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

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

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

Remarks

If not explicitly specified using either Public or Private, Function procedures are Public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function keywords cause an immediate exit from a Function procedure.  Program execution continues with the statement following the statement that called the Function procedure.  Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments.  However, unlike a Sub procedure, a Function procedure can be used on the right hand side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression.  If the function has no arguments, you still must include the parentheses.  See the Call statement for specific information on how to call Function procedures.

Caution   Function procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow.  The Static keyword is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name.  Any number of such assignments can appear anywhere within the procedure.  If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a Variant function returns Empty.  A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named BinarySearch.  In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .) As Boolean

. . .

' Value not found. Return a value of False.

If lower > upper Then

BinarySearch = False

Exit Function

End If

. . .

End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.  Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure.  Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution   A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined at the module level has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

Caution   Arithmetic expressions may be rearranged to increase internal efficiency.  Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.


LBound Function

Returns the smallest available subscript for the indicated dimension of an array.

Syntax

LBound(arrayname[,dimension])

Elements

The LBound statement syntax has these parts:

Part	Description

arrayname	Name of the array variable; follows standard variable naming conventions.

dimension	Whole number indicating which dimension's lower bound is returned.  Use 1 for the first dimension, 2 for the second, and so on.  If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array.  Use the UBound function to find the upper limit of an array dimension.

LBound returns the values listed in the table below for an array with the following dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement	Return Value

LBound(A, 1)	1

LBound(A, 2)	0

LBound(A, 3)	-3

The default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement.

Arrays for which dimensions are set using the To clause in a Dim, Private, Public, ReDim, or Static statement can have any integer value as a lower bound.


Let Statement

Assigns the value of an expression to a variable or property.

Syntax

[Let] varname = expression

Elements

The Let statement syntax has these parts:

Part	Description

varname	Name of the variable or property; follows standard variable naming conventions.

expression	Value assigned to the variable.

Remarks

In order to simplify Basic code, the optional Let keyword is most often omitted.

A value expression can be assigned to a variable only if it is of a data type that is compatible with the variable.  You can't assign string expressions to numeric variables, and you can't assign numeric expressions to string variables.  If you do, an error occurs at compile time.

Variant variables can be assigned either string or numeric expressions.  However, the reverse is not always true.  Any Variant except a Null can be assigned to a string variable, but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable.  Use the IsNumeric function to determine if the Variant can be converted to a number.

Caution   Assigning an expression of one numeric data type to a variable of a different numeric data type coerces the value of the expression into the data type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type.  Use the LSet statement to assign record variables of different user-defined types.  Use the Set statement to assign object references to variables.


Option Base Statement

Used at module level to declare the default lower bound for array subscripts.

Syntax

Option Base {0 | 1}

Remarks

If used, the Option Base statement must appear in a module before any statements that declare variables or define constants.

Since the default base is 0, the Option Base statement is never required.  However, if used, it  can appear only once in a module and must precede array declarations that include dimensions.

The Option Base statement has no effect on arrays within user-defined types for which the lower bound is always 0.

Tip   The To clause in the Dim, Private, Public, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts.  However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.

The Option Base statement only affects the lower bound of arrays in the module where the statement is located.


Option Compare Statement

Used at module level to declare the default comparison mode to use when string data is compared.

Syntax

Option Compare {Binary | Text}

Remarks

If used, the Option Compare statement must appear in a module before any statements that declare variables or define constants.

The Option Compare statement specifies the string comparison method (Binary or Text) for a module.  If a module doesn't include an Option Compare statement, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. On the Macintosh, sort order is determined by the character set. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e  < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system's locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)


Option Explicit Statement

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any statements that declare variables or define constants.

If you don't use the Option Explicit statement, all undeclared variables are Variant unless the default type is otherwise specified with a Deftype statement.

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements.  If you attempt to use an undeclared variable name, an error occurs at compile time.

Tip   Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid risking confusion in code where the scope of the variable is not clear.


Option Private Statement

Used at module level to indicate that an entire module is Private.

Syntax

Option Private Module

Remarks

If used, the Option Private statement must appear in a module before any statements that declare variables or define constants.

The public parts (variables, objects, and user-defined types declared at module level) of modules declared Private using the Option Private statement are still available within the project containing the module, but they are not available to other applications or projects.


Private Statement

Used at module level to declare private variables and allocate storage space.

Syntax

Private varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

Elements

The Private statement syntax has these parts:

Part	Description

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

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

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

type	Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Private variables are available only to the module in which they are declared.

Use the Private statement to declare the data type or object type of a variable.  For example, the following statement declares a variable as an Integer:

Private NumberOfEmployees As Integer

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it was a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Private statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public or Dim statement, an error occurs.


Property Get Statement

Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property.

Syntax

[Public | Private][Static] Property Get name [(arglist)][As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property

Elements

The Property Get statement syntax has these parts:

Part	Description

Public	Indicates that the Property Get procedure is accessible to all other procedures in all modules.  If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.

Private	Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.

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

name	Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.

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

type	Data type of the value returned by the Property Get procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, or Variant.  Arrays of any type can't be returned, but a Variant containing an array can.

statements	Any group of statements to be executed within the body of the Property Get procedure.

expression	Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef] varname[( )][As type]

Part	Description

Optional	Indicates that an argument is not required.  If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.  All Optional arguments must be Variant.

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Get procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Get procedure.  Program execution continues with the statement following the statement that called the Property Get procedure.  Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments.  However, unlike a Sub or Property Let procedure, a Property Get procedure can be used on the right-hand side of an expression in the same way you use a Function or a property name when you want to return the value of a property.


Property Let Statement

Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property.

Syntax

[Public | Private][Static] Property Let name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

Elements

The Property Let statement syntax has these parts:

Part	Description

Public	Indicates that the Property Let procedure is accessible to all other procedures in all modules.  If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.

Private	Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.

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

name	Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.

arglist	List of variables representing arguments that are passed to the Property Let procedure when it is called.  Multiple variables are separated by commas.  The last argument is the value assigned to the property on the right-hand side of an expression.

statements	Any group of statements to be executed within the body of the Property Let procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part	Description

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

Note   Every Property Let statement must define at least one argument for the procedure it defines.  That argument (or the last argument if there is more than one) will contain the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Let procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Let procedure.  Program execution continues with the statement following the statement that called the Property Let procedure.  Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments.  However, unlike a Function and Property Get procedure, both of which return a value, a Property Let procedure can only be used on the left side of a property assignment expression or Let statement.


Property Set Statement

Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object.

Syntax

[Public | Private][Static] Property Set name [(arglist)]

[statements]
[Exit Property]
[statements]
End Property

Elements

The Property Set statement syntax has these parts:

Part	Description

Public	Indicates that the Property Set procedure is accessible to all other procedures in all modules.  If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.

Private	Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.

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

name	Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.

arglist	List of variables representing arguments that are passed to the Property Set procedure when it is called.  Multiple variables are separated by commas. The last argument is the object reference used on the right-hand side of an object reference assignment.

statements	Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part	Description

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

Note   Every Property Set statement must define at least one argument for the procedure it defines.  That argument (or the last argument if there is more than one) will contain the actual object reference for the property when the procedure defined by the Property Set statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Set procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Set procedure.  Program execution continues with the statement following the statement that called the Property Set procedure.  Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments.  However, unlike a Function and Property Get procedure, both of which return a value, a Property Set procedure can only be used on the left side of an object reference assignment (Set statement).


Public Statement

Used at module level to declare public variables and allocate storage space.

Syntax

Public varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

Elements

The Public statement syntax has these parts:

Part	Description

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

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

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

type	Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are Public only within the project in which they reside.

Use the Public statement to declare the data type or object type of a variable.  For example, the following statement declares a variable as an Integer:

Public NumberOfEmployees As Integer

If you do not specify a data type or object type and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it was a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Public statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public or Dim statement, an error occurs.


ReDim Statement

Used at the procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][,varname(subscripts) [As type]] . . .

Elements

The ReDim statement syntax has these parts:

Part	Description

Preserve	Preserves the data in an existing array when you change the size of the last dimension.

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

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

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

type	Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.  For a Variant containing an array, type describes the type of each element of the array, but does not change the Variant to some other type.

Remarks

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Private, Public or Dim statement with empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.  However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed using an As type clause.

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all.  For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions you can only change the size of the last dimension and still preserve the contents of the array.  The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)

. . .

ReDim Preserve X(10, 10, 15)

Caution   If you make an array smaller than it was, data in the eliminated elements will be lost.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it was a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note   In order to resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.


Rem Statement

Used to include explanatory remarks in a program.

Syntax 1

Rem comment

Syntax 2

' comment

Elements

The argument comment is the text of any comment you want to include.  After the Rem keyword, a space before comment is required.

Remarks

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement.  Execution continues with the first executable statement following the Rem statement.

As shown in syntax 2, you can use a single quotation mark or apostrophe (') instead of the Rem keyword.  If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon.  However, when you use a single quotation mark, the colon is not required after other statements.


Set Statement

Assigns an object reference to a variable or property.

Syntax

Set objectvar = {objectexpression | Nothing}

Elements

The Set statement syntax has these parts:

Part	Description

objectvar	Name of the variable or property; follows standard variable naming conventions.

objectexpression	Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.

Nothing	Discontinues association of objectvar with any specific object.  Assigning objectvar to Nothing releases all the resources associated with the previously referenced object when no other variable refers to it.

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, Redim and Static statements only declare a variable that refers to an object.  No actual object is referred to until you use Set statement to assign a specific object.

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable.  Instead, a reference to the object is created.  More than one object variable can refer to the same object.  Because these variables are references to (rather than copies of) the object, any change is reflected in all variables that refer to it.


Static Statement

Used at the procedure level to declare  variables and allocate storage space.  Variables declared with the Static statement retain their value as long as the code is running.

Syntax

Static varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

Elements

The Static statement syntax has these parts:

Part	Description

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

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

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

type	Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Once the module code is running, variables declared with the Static statement retain their value until the module is reset or restarted.  Use the Static statement in nonstatic procedures to explicitly declare Static variables.

Use a Static statement within a procedure to declare the data type of a Static variable.  For example, the following statement declares a fixed-size array of integers:

Static EmployeeNumber(200) As Integer

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

Note   The Static statement and the Static keyword affect the lifetime of variables differently.  If you declare a procedure using the Static keyword (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once and the value of the variables is preserved for the entire time the code is running.  For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited.  The Static statement is used to declare variables within nonstatic procedures to preserve their value as long as the program is running.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it was a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Tip   When you use the Static statement in a procedure, it is a generally accepted programming practice to put the Static statement at the beginning of the procedure with any Dim statements.


Sub Statement

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Private | Public][Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub

Elements

The Sub statement syntax has these parts:

Part	Description

Public	Indicates that the Sub procedure is accessible to all other procedures in all modules.  If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.

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

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

name	Name of the Sub; follows standard variable naming conventions.

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

statements	Any group of statements to be executed within the body of the Sub procedure.

The arglist argument has the following syntax and parts:

[[Optional][ByVal | ByRef][ParamArray] varname[( )] As type]

Part	Description

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

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

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

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

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

Remarks

If not explicitly specified using either Public or Private, Sub procedures are Public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keyword causes an immediate exit from a Sub procedure.  Program execution continues with the statement following the statement that called the Sub procedure.  Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments.  However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list.  See the Call statement for specific information on how to call Sub procedures.

Caution   Sub procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.  Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure.  Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution   A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined at the module level has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

Note   You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.


Type Statement

Used at module level to define a user-defined data type containing one or more elements.

Syntax

[Private | Public] Type varname
  elementname [([subscripts])] As type
[ elementname [([subscripts])] As type]
. . .
End Type

Elements

The Type statement syntax has these parts:

Part	Description

Public	Used to declare user-defined types that are available to all procedures in all modules in all projects.

Private	Used to declare user-defined types that are available only within the module where the declaration is made.

varname	Name of the user-defined type; follows standard variable naming conventions.

elementname	Name of an element of the user-defined type.  Element names also follow standard variable naming conventions, except that reserved words can be used.

subscripts	Dimensions of an array element.  Use only parentheses when declaring an array whose size can change.

type	Data type of the element; may be Boolean, Integer, Long, Currency, Single, Double, Date, String, String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks

The Type statement can be used only at module level.  Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration.  Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records, which frequently consist of a number of related elements of different data types.

The following example shows the use of fixed-size arrays in a user-defined type:

Type StateData

CityCode (1 To 100) As Integer ' Declare a static array.

County As String * 30

End Type

Dim Washington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables.

The setting of the Option Base statement determines the lower bound for arrays within user-defined types.


UBound Function

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(arrayname[,dimension])

Elements

The UBound function syntax has these parts:

Part	Description

arrayname	Name of the array variable; follows standard variable naming conventions.

dimension	Whole number indicating which dimension's upper bound is returned.  Use 1 for the first dimension, 2 for the second, and so on.  If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array.  Use the LBound function to find the lower limit of an array dimension.

UBound returns the values listed in the table below for an array with these dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement	Return Value

UBound(A, 1)	100

UBound(A, 2)	3

UBound(A, 3)	4


ANSI Character Set <definition>
ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used by Microsoft Windows that allows you to represent up to 256 characters (0-255) using your keyboard.  The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard.  The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


argument <definition>
argument

A constant, variable, or expression passed to a procedure.


array <definition>
array

A set of sequentially indexed elements having the same intrinsic data type.  Each element of an array has a unique index number that identifies it.  Changes made to one element of an array do not affect the other elements.


ASCII Character Set <definition>
ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard.  The ASCII character set is the same as the first 128 characters (0-127) in the ANSI character set.


automatic formatting <definition>
automatic formatting

A feature that automatically formats code as you enter it by capitalizing the first letter for keywords, regularizing spacing, adding punctuation, and setting the foreground and background colors.


bit-wise comparison <definition>
bit-wise comparison

A bit-by-bit comparison of identically positioned bits in two numeric expressions.


Boolean expression <definition>
Boolean expression

An expression that evaluates to either True or False.


break mode <definition>
break mode

Temporary suspension of program execution while in the development environment.  In break mode, you can examine, debug, reset, step, or continue program execution.  Break mode can be entered by:

Setting a breakpoint.

Pressing CTRL+BREAK during program execution.

Encountering a Stop statement or untrapped run-time error during program execution.

Adding a Break When True watch expression.  Execution stops when the value of the watch changes and evaluates to True.

Adding a Break When Changed watch expression.  Execution stops when the value of the watch changes.


breakpoint <definition>
breakpoint

A selected program line at which execution automatically stops.  Breakpoints are not saved with your code.


by reference <definition>
by reference

A way of passing an argument to a procedure that allows the procedure access to the actual variable.  As a result, the variable's actual value can be changed by the procedure to which it is passed.


by value <definition>
by value

A way of passing an argument to a procedure that allows the procedure access to a copy of the variable.  As a result, the variable's actual value can't be changed by the procedure to which it is passed.


Clipboard <definition>
Clipboard

A temporary storage location used to transfer text, graphics, and code.


character code <definition>
character code

A number that represents a particular character in a set, such as the ANSI character set.


close box <definition>
close box

On the Macintosh, the small box in the upper-left corner of a window that you click to close the window.


collection <definition>
collection

A group of objects.  An object's position in the collection can change whenever a change occurs in the collection.  Therefore, the position of any specific object in the collection is unpredictable.  This unpredictability distinguishes a collection from an array.


comment <definition>
comment

Text added to code by a programmer that explains how the code works.  Each comment line starts with an apostrophe (') or the keyword Rem followed by a space.


comparison operator <definition>
comparison operator

A character or symbol indicating a relationship between two or more values or expressions:

Symbol	Description

<	Less than

<=	Less than or equal to

> 	Greater than

>=	Greater than or equal to

<> 	Not equal

=	Equal

Additional comparison operators include Is and Like.  Note, however, that Is and Like can't be used as comparison operators in a Select Case statement.


compile time <definition>
compile time

The moment at which source code is translated to executable code.


constant <definition>
constant

A named item that retains a constant value throughout the execution of a program, as opposed to a variable, whose value can change during execution.  Each application can predefine its own set of constants.  Additional constants may be defined using the Const statement.  Constants of either type can be used anywhere in your code in place of actual values.  A constant may be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is.  For example:

Const A = "MyString"


Control Panel <definition>
Control Panel

Program(s) that control your system configuration.  Use Control Panel utilities to adjust hardware and software options, such as desktop colors, printer selections, date and number formats, fonts, and international settings (such as language and system of measurement).


Control-menu box <definition>
Control-menu box

In Microsoft Windows, the box in the upper-left corner of a window that opens the Control menu.

For applications, this menu displays commands that allow you to restore, move, size, minimize, maximize, or close the current application.  In addition, you may be able to switch to or run other Microsoft Windows-based applications.

For windows within an application, this menu displays commands that allow you to size, move, split, or close the active window.


data type <definition>
data type

The characteristic of a variable that determines what kind of data it can hold.  Data types include Boolean, Integer, Long, Currency, Single, Double, Date, String, Object, Variant (default) and user-defined types, as well as specific types of objects.

User-defined types are defined using the Type statement.  Arrays of user-defined and other data types are created using the Dim statement.  Arrays of any type can be included within user-defined types.


data type ranges <definition>
data type ranges

Each data type has a specific range of allowed values:

Data type	Range

Boolean	True or False.

Integer	-32,768 to 32,767.

Long	-2,147,483,648 to 2,147,483,647.

Single	-3.402823E28 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

Double	-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Currency	-922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Date	January 1, 100 to December 31, 9999.

Object	Any Object reference.

String	Strings may range in length from 0 to approximately 2 billion (approximately 65,535 for Microsoft Windows version 3.1 and earlier).

Variant	Any numeric value up to the range of a Double or any character text.

User-defined Type elements	The range of each element is the same as the range of its data type.


date expression <definition>
date expression

Any expression that can be interpreted as a date.  This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions.  A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999.

Dates are stored as part of a real number.  Values to the left of the decimal represent the date; values to the right of the decimal represent the time.  Negative numbers represent dates prior to December 30, 1899.


date literal <definition>
 date literal

Any sequence of characters with a valid format that is surrounded by number signs (#).  Valid formats include the date format specified by the locale settings for your code or the universal date format.

For example, #12/31/92# is the date literal that represents December, 31, 1992 where English-U.S. is the locale setting for your application.  Use date literals to maximize portability across national languages.


date separators <definition>
date separators

Characters used to separate the day, month, and year when date values are formatted.  The characters are determined by system settings or by the Format function.


dates and times <definition>
dates and times

Dates and times are stored internally as different parts of a real number.

The value to the left of the decimal represents a date between January 1, 100 and December 31, 9999, inclusive.  Negative values represent dates prior to December 30, 1899.

The value to the right of the decimal represents a time between 0:00:00 and 23:59:59, inclusive.  Midday is represented by .5.


declaration <definition>
declaration

A declaration specifies the type associated with data and procedure identifiers.  Declarative statements for constants and variables are Const, Dim, Private, Public, ReDim, Static.  A variable that is not explicitly declared with a variable-declaration statement is implicitly declared unless the statement Option Explicit occurs at module level.  The Type...End Type statement declares the structure for a variable of user-defined type.  Sub, Function, Property, and Declare (and the optional attributes Public and Private) are used to declare procedures.

A declaration can specify type with an As clause, or in some cases, by appending a type-declaration character to the name.  Variables for which no type is specified have the current default type (by default, Variant).  Declarations permit Visual Basic to allocate appropriately sized memory for variables and function-return values.  They further permit checking to ensure the arguments passed to a procedure are of the expected type and number.


dynamic-link library (DLL) <definition>
dynamic-link library (DLL)

A library of routines loaded and linked into applications at run time.  DLLs are created with other programming languages such as C, MASM, or Fortran.


Empty <definition>
Empty

A value that indicates that a variable is uninitialized; that is, no beginning value has been assigned.  Empty variables are equal to 0 (in a numeric context), zero-length (in a string context), or VarType 0.


error number <definition>
error number

A whole number in the range 0 to 65,535, inclusive, that represents a particular error message.


expression <definition>
expression

A combination of keywords, operators, variables, and constants that yield a string, number, or object.  An expression can perform a calculation, manipulate characters, or test data.


file number <definition>
file number

Number used in the Open statement to open a file.  Use file numbers in the range 1 to 255, inclusive, for files not accessible to other applications.  Use file numbers in the range 256 to 511, inclusive, for files accessible from other applications.


host application <definition>
host application

Any application that supports the use of Visual Basic, Applications Edition.  For example, Microsoft Excel, Microsoft Project, and so on.


insertion point <definition>
insertion point

The place where text is inserted when you type; usually indicated by a text cursor or selection.


keyword <definition>
keyword

A word or symbol recognized as part of the programming language; for example, a statement, function name, or operator.

There are two types of keywords:

Type	Description

Restricted	Keywords that should not be used to name procedures.

Unrestricted	Keywords that can be used without restriction.  Many of the unrestricted keywords are system or application-provided functions, methods, properties, and statement names that are unknown to the compiler. This allows you to define your own procedures with the same name. For example, if you create a FileCopy procedure and call it from within your application, your version of FileCopy is used, rather than the system-provided FileCopy statement.


line label <definition>
line label

A line label is used to identify a single line of code.  It can be any combination of characters that starts with a letter and ends with a colon.  Each line label must be unique within the module where it is used.  Line labels are not case-sensitive and can begin in any column as long as they are the first nonblank characters on the line.


line number <definition>
line number

A line number is used to identify a single line of code. This number can be any combination of digits that is unique within the module where it is used.  Line numbers can begin in any column as long as they are the first nonblank characters.

Note   Line numbers greater than 65,529 are treated as line labels and can't be returned by the Erl function.


line-continuation character <definition>
line-continuation character

The combination of a space followed by an underscore ( _); used in the development environment to extend a single logical line of code to two or more physical lines.  Note that line-continuation characters can't be used to continue a line of code within a string expression.


locale <definition>
locale

The set of information that corresponds to a given language and country.  A locale describes the language of predefined programming terms and locale-specific settings such as the decimal and list separators, date formats, and character-sorting order.  There are two contexts where locale information is important:

The code locale affects such things as the language of the keywords and what decimal separator is appropriate.  You set the code locale by choosing Options from the Tools menu.

The system locale affects the way locale-aware functionality behaves.  For example, the system locale is used when you display numbers or convert strings to dates.  You set the system locale using the Control Panel utilities provided by the operating system.

In the most common cases, the system locale and code locale are the same.


logic error <definition>
logic error

A programming error that can cause code to produce incorrect results or halt execution.  For example, an error can be caused by incorrect variable names, wrong variable types, endless loops, flaws in logical comparisons, or array problems.


member <definition>
member

The constituent elements of a collection, object, or user-defined type.


method <definition>
method

A procedure that applies to a specific object.


module <definition>
module

A collection of declarations and procedures.


module level <definition>
module level

The declarations section of a module.  Any code outside a procedure is referred to as module-level code.  Declarations must be listed first, followed by procedures.  For example:

Dim X as Integer	' This is a module-level declaration.

Const RO = "ReadOnly"	' This is a module-level declaration.

Type MyType	' This is a module-level declaration.

MyString As String

MyAge As Integer

End Type

Sub MySub()	' This statement declares a sub procedure block.

Dim A	' This statement starts the procedure block.

A = "My variable"	' Procedure-level code.

Debug.Print A	' Procedure-level code.

End Sub	' This statement ends a sub procedure block.


module variable <definition>
module variable

A variable declared outside Function, Sub, or Property procedure code.  Module variables must be declared before any procedures in the module.


named argument <definition>
named argument

An argument that has a predefined name.  Instead of providing values for arguments in the order expected by the syntax, you can use named arguments to assign values in any order to only the arguments you want (if they are optional).  For example, suppose a method accepts three arguments:

DoSomeThing namedarg1, namedarg2, namedarg3

By assigning values to named arguments, you can use the following statement:

DoSomeThing namedarg3:=4,namedarg2:=5

Note that the arguments need not be in their normal positional order.


Null <definition>
Null

A value indicating that a variable contains no valid data.  Null is the result of:

An explicit assignment of a variable to Null.

Any operation between expressions that contain Null.


numeric expression <definition>
numeric expression

Any expression that can be evaluated as a number.  Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number.


numeric type <definition>
numeric type

Any intrinsic numeric data type (Boolean, Integer, Long, Currency, Single, Double or Date) or any Variant numeric subtype (Empty, Integer, Long, Single, Double, Currency, Date, Error or Boolean).


object expression <definition>
object expression

An expression that specifies a particular object.  This expression may include any of the object's containers.  For example, if your application has an Application object that contains a Document object that contains a Text object, the following are valid object expressions:

Application.Document.Text

Application.Text

Document.Text

Text


object type <definition>
object type

A type of object exposed by an application through OLE Automation; for example, Application, File, Range, and Sheet.  Refer to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on) for a complete listing of available objects.


parameter <definition>
parameter

Variable name by which a procedure argument is known within the procedure.  This variable receives the argument passed into the procedure and its scope ends at the End statement of the procedure.


path <definition>
path

A string expression specifying a directory or folder location; may include a drive specification.  For example, in Microsoft Windows:

C:\MAIN\SUBDIR\MYSUBDIR

On the Macintosh:

MY HARDDRIVE:MY FOLDER OF STUFF


pathname <definition>
pathname

A string expression specifying a file(s) within a specific directory or folder.  Unless otherwise noted, a pathname may include a drive specification.  For example, in Microsoft Windows:

C:\MAIN\SUBDIR\MYSUBDIR\MYFILE.TXT

On the Macintosh:

MY HARDDRIVE:MY FOLDER OF STUFF:MY FILE


pi <definition>
pi

Pi is a mathematical constant equal to approximately 3.1415926535897932.


print zone <definition>
print zone

Print zones begin every 14 columns.  The width of each column is an average of the width of all characters in the point size for the chosen font.


procedure <definition>
procedure

A named sequence of code statements executed as a unit.  For example, Function, Property, and Sub are all types of procedures.


procedure level <definition>
procedure level

Statements located within a Function, Property, or Sub procedure.  Declarations are usually listed first, followed by assignments and other executable code.  For example:

Sub MySub()

Dim A	' This statement is a declaration.

A = "My variable"	' This statement is an assignment.

Debug.Print A	' This statement is executable.

End Sub

Note   In contrast, module-level code resides outside of any Sub...End Sub blocks.


project <definition>
project

A collection of modules.


property <definition>
property

A named attribute of an object.  Properties define object characteristics (such as size, color, and screen location) or object behaviors (for example, whether it is enabled).


referenced project <definition>
referenced project

The project you are working on is called the current project.  You can create links to other projects from the current project.  When you do so, the project linked to is called a directly referenced project, while the current project is called the directly referencing project.  How a project is linked to depends on the host application.  For example, in Excel you can directly reference a project by choosing it from the Tools menu's References dialog.  Public symbols in a directly referenced project are visible to the directly referencing project, but not vice versa (Public symbols in a directly referencing project are not visible to a directly referenced project).

A project referenced by one of the current project's directly referenced projects is called an indirectly referenced project.  Its Public symbols are not accessible to the current project except through qualification with its project name.  Any combination of direct and indirect references between projects is valid as long as they do not result in a complete cycle.  For example, if ProjectA references ProjectB, both ProjectA and ProjectB can reference ProjectC, but neither ProjectB nor ProjectC can reference ProjectA, since that would create a cyclic reference.


run time <definition>
run time

The time when code is running.  During run time, you interact with the code as a user would.


run-time error <definition>
run-time error

An error that occurs when code is running.  A run-time error results when a statement attempts an invalid operation.


scope <definition>
scope

Defines the accessibility and lifetime of a variable, procedure, or object.  For example, a variable declared as Public is available to all procedures in all modules in all applications (unless Option Private Module is in effect).


seed <definition>
seed

An initial value used to generate pseudorandom numbers.  For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.


sort order <definition>
sort order

A sequencing principle used to order data; for example, alphabetic, numeric, ascending, descending, and so on.


split bar <definition>
split bar

The thin bar that divides a window into two separate areas.  In a module, the split bar divides the code pane into two separate code panes.  In the Debug window, the split bar divides the window between the Immediate or Watch pane, and the code pane.


statement <definition>
statement

A syntactically complete unit that expresses one kind of action, declaration, or definition.  Normally a statement is a single line, although you can use a colon (:) to put more than one statement on a line, and you can use a space underscore ( _) sequence to continue a single logical line onto a second physical line.


string comparison <definition>
string comparison

A comparison of two sequences of characters.  Comparisons can be either binary or text.  In English, binary comparisons are case-sensitive; text comparisons are not.


string constant <definition>
string constant

Any constant (defined using the Const keyword) consisting of a sequence of contiguous characters interpreted as the characters themselves rather than some numeric value.  For example:

Const A="MyString"


string expression <definition>
string expression

Any expression that evaluates to a sequence of contiguous characters.  Elements of the expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).


string literal <definition>
string literal

Any expression consisting of a sequence of contiguous characters surrounded by quotation marks that is literally interpreted as the characters within the quotation marks.  For example:

"MyString"


string type <definition>
string type

A data type whose data consists of a sequence of contiguous characters that represent the actual characters themselves rather than some numerical value.  Strings can include letters, numbers, spaces, and punctuation marks.


syntax checking <definition>
syntax checking

A feature that checks your code for correct syntax.  If syntax checking is turned on, a message is displayed when you enter code that has a syntax error.


syntax error <definition>
syntax error

An error that occurs when the system doesn't understand a line of code that was just entered.

Note   Syntax rules for individual keywords are defined in the Syntax section of the associated Help topic.  To get Help on a keyword from within the development environment, select the keyword and press F1.


time expression <definition>
time expression

Any expression that can be interpreted as a time.  This includes any combination of time literals, numbers that look like times, strings that look like times, and times returned from functions.

Times are stored as part of a real number.  Values to the right of the decimal represent the time.  Midday (12:00 P.M.) is represented by .5.


title bar <definition>
title bar

An area at the top of a window that displays the window's caption or name.


type-declaration character <definition>
type-declaration character

A character appended to a variable name indicating the variable's data type.  By default, variables are of type Variant unless a corresponding Deftype statement is present in the module.

Character	Data type

none	Boolean

%	Integer

&	Long

!	Single

#	Double

none	Date

@	Currency

$	String

none	Object

none	Variant


universal date format <definition>
universal date format

The universal date format is #yyyy-mm-dd hh:mm:ss#.  However, both the date component (#yyyy-mm-dd#) and the time component (#hh:mm:ss#) can be represented separately.


user-defined type <definition>
user-defined type

Any data type defined using the Type statement.  User-defined data types can contain one or more elements of any data type.  Arrays of user-defined and other data types are created using the Dim statement.  Arrays of any type can be included within user-defined types.


variable <definition>
variable

A named storage location that can contain a certain type of data that can be modified during program execution.  Each variable has a unique name that identifies it within its level of scope.  Variable names must begin with an alphabetic character, can't contain an embedded period or type-declaration character, and must be unique within the same scope.


variable name <definition>
variable name

Variable names:

Must begin with an alphabetic character.

Can't contain an embedded period or type-declaration character.

Must be unique within the same scope.

Must be no longer than 255 characters in length.


VarType <definition>
VarType

The VarType function returns a value that provides information about the type of data stored in a variable.

Value Returned	Equivalent Constant	Description of Variable
0	vbEmpty	Uninitialized
1	vbNull	Contains no valid data
2	vbInteger	Integer
3	vbLong	Long integer
4	vbSingle	Single-precision floating point number
5	vbDouble	Double-precision floating point number
6	vbCurrency	Currency
7	vbDate	Date
8	vbString	String
9	vbObject	OLE Automation object
10	vbError	Error
11	vbBoolean	Boolean
12	vbVariant	Variant (used only for arrays of Variants)
13	vbDataObject	Non-OLE Automation object
8192	vbArray	Array
Note   The constant vbArray combined with any other constant indicates an array of that type of variable.


wait mode <definition>
wait mode

The time when your program is not running and variables have not been reset.  In wait mode, you can examine, debug, or reset execution.


watch expression <definition>
watch expression

An expression you define that allows you to observe the behavior of a variable or expression.  For example, if a and b are two variables, the following expressions are valid watch expressions:

a

a*b

3*a = b-2

Watch expressions appear in the Watch pane of the Debug window and are automatically updated when you enter break mode.  The Watch pane displays the value of an expression within a given context.  Watch expressions are not saved with your code.


Array Function Example

This example uses the Array function to return a Variant containing an array.

MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

' Return values assume lower bound equals 1 (using Option Base).

MyDay = MyWeek(2)	' Returns "Tue".

MyDay = MyWeek(4)	' Returns "Thu".


Const Statement Example

This example uses the Const statement to declare constants for use in place of literal values.

' Constants are Private by default.

Const MyVar = 459

' Declare Public constant.

Public Const MyString = "HELP"

' Declare Private Integer constant.

Private Const MyInt As Integer = 5

' Declare multiple constants on same line.

Const MyStr = "Hello", MyDouble As Double = 3.4567


Declare Statement Example

This example shows how the Declare statement is used at the module level to declare a reference to an external procedure in a dynamic-link library (DLL) or Macintosh code resource.

' In Microsoft Windows.

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

' On the Macintosh.

Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _

As Integer)


Deftype Statement Example

This example shows various uses of the Deftype statements to set default data types of variables and function procedures whose names start with specified characters.  The default data type can be overridden only by explicit assignment using the Dim statement.  Deftype statements can only be used at the module-level.

' Variable names beginning with A through K default to Integer.

DefInt A-K

' Variable names beginning with L through Z default to String.

DefStr L-Z

CalcVar = 4	' Initialize Integer.

StringVar = "Hello there"	' Initialize String.

AnyVar = "Hello" 	' Causes "Type mismatch" error.

Dim Calc As Double	' Explicitly set the type to Double.

Calc = 2.3455	' Assign a Double.

' Deftype statements also apply to function procedures.

CalcNum = ATestFunction(4)	' Call user-defined function.

' ATestFunction function procedure definition.

Function ATestFunction(INumber)

ATestFunction = INumber * 2	' Return value is an integer.

End Function


Dim Statement Example

This example shows various uses of the Dim statement to declare variables.  The Dim statement is also used to declare arrays.  The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values

' set to Empty.

Dim AnyValue, MyValue

'  Explicitly declare a variable of type Integer.

Dim Number As Integer

' Multiple declarations on a single line. AnotherVar is of type Variant

' since its type is omitted.

Dim AnotherVar, Choice As Boolean, BirthDate As Date

' DayArray is an array of Variants with 51 elements indexed,

' starting at 0 thru 50, assuming Option Base is set to 0 (default) for

' the current module.

Dim DayArray(50)

' Matrix is a two-dimensional array of integers.

Dim Matrix(3,4) As Integer

' MyMatrix is a three-dimensional array of doubles with explicit

' bounds.

Dim MyMatrix(1 To 5,  4 To 9,  3 To 5) As Double

' BirthDay is an array of dates with indexes from 1 to 10.

Dim BirthDay(1 To 10) As Date

' MyArray is a dynamic array.

Dim MyArray()


Erase Statement Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

' Declare array variables.

Dim NumArray(10) As Integer	' Integer array.

Dim StrVarArray(10) As String	' Variable-string array.

Dim StrFixArray(10) As String * 10	' Fixed-string array.

Dim VarArray(10) As Variant	' Variant array.

Dim DynamicArray() As Integer	' Dynamic array.

ReDim DynamicArray(10)	' Allocate storage space.

Erase NumArray	' Each element set to 0.

Erase StrVarArray	' Each element set to "".

Erase StrFixArray	' Each element set to 0.

Erase VarArray	' Each element set to Empty.

Erase DynamicArray	' Free memory used by array.


Function Statement Example

This example uses the Function statement to declare the name, arguments and code that form the body of a Function procedure.

' The following user-defined function returns the square root of the

' argument passed to it.

Function CalculateSquareRoot(NumberArg As Double) As Double

If NumberArg < 0 Then	' Evaluate argument.

Exit Function	' Exit to calling procedure.

Else

CalculateSquareRoot = Sqr(NumberArg)	' Return square root.

EndIf

End Function

' Using the ParamArray keyword enables a function to accept a variable

' number of arguments. In the following definition, FirstArg is passed

' by value.

Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())

' If the function is invoked as...

ReturnValue = CalcSum(4,3,2,1)

' Local variables get the following values: FirstArg=4, OtherArgs(1)=3,

' OtherArgs(2) = 2 and so on, assuming default lower bound for

' arrays = 1.

' If a function's arguments are defined as...

Function MyFunc(MyStr As String, Optional MyArg1, Optional MyArg2)

' It can be invoked in the following ways.

RetVal = MyFunc("Hello", 2, "World")	' All 3 arguments supplied.

RetVal = MyFunc("Test", , 5)	' Second argument omitted.

RetVal = MyFunc("Test")	' First argument only.


LBound Function Example

This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array.  Use the Option Base statement to override the default base array subscript value of 0.

Dim MyArray(1 To 10, 5 To 15, 10 To 20) 	' Declare array variables.

Dim AnyArray(10)

Lower = LBound(MyArray, 1) 	' Returns 1.

Lower = LBound(MyArray, 3)	' Returns 10.

Lower = LBound(AnyArray)	' Returns 0 or 1, depending on

' setting of Option Base.


Let Statement Example

This example uses statements with and without the Let statement to assign the value of an expression to a variable.

' The following variable assignments use the Let statement.

Let MyStr = "Hello World"

Let MyInt = 5

' The following are the same assignments without the Let statement.

MyStr = "Hello World"

MyInt = 5


Option Base Statement Example

This example uses the Option Base statement to override the default base array subscript value of 0.  The LBound function returns the smallest available subscript for the indicated dimension of an array.  The Option Base statement is used at the module-level only.

' Set default array subscripts to 1.

Option Base 1

Dim MyArray(20), TwoDArray(3,4)	' Declare array variables.

Dim ZeroArray(0 To 5)	' Override default base subscript.

' Use LBound function to test lower bounds of arrays.

Lower = LBound(MyArray)	' Returns 1.

Lower = LBound(TwoDArray, 2)	' Returns 1.

Lower = LBound(ZeroArray)	' Returns 0.


Option Compare Statement Example

This example uses the Option Compare statement to set the default string comparison mode.  The Option Compare statement is used at the module-level only.

' Set the string comparison method to Binary.

Option Compare Binary 	' i.e. "AAA" less than "aaa"

' Set the string comparison method to Text.

Option Compare Text	' i.e. "AAA" equal to "aaa".


Option Explicit Statement Example

This example uses the Option Explicit statement to force you to explicitly declare all variables.  Attempting to use an undeclared variable gives you an error at compile time.  The Option Explicit statement is used at the module-level only.

Option Explicit	' Force explicit variable declaration.

Dim MyVar	' Declare variable.

MyInt = 10	' Undeclared variable generates error.

MyVar = 10	' Will not generate error.


Option Private Statement Example

This Option Private statement is used at the module-level to indicate that the entire module is private.

Option Private Module	' Indicate that module is private.


Private Statement Example

This Private statement is used at the module-level to declare variables as private; that is, they are available only to the module in which they are declared.

Private Number As Integer	' Private integer variable.

Private NameArray(1 To 5) As String	' Private array variable.

Private MyVar, YourVar, ThisVar As Integer	' Multiple declarations.


Property Get Statement Example

This example uses the Property Get Statement to define a property procedure that gets the value of a property that identifies,  as a string, the current color of a pen in a drawing package:

Dim CurrentColor As Integer

Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Returns the current color of the pen as a string

Property Get PenColor() As String

Select Case CurrentColor

Case RED

PenColor = "Red"

Case GREEN

PenColor = "Green"

Case BLUE

PenColor = "Blue"

End Select

End Property

' The following line gets the color of the pen

' calling the Property Get procedure.

ColorName = PenColor()


Property Let Statement Example

This example uses the Property Let statement to define a procedure that assigns a value to a property that identifies the pen color for a drawing package.

Dim CurrentColor As Integer

Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Sets the pen color property for a Drawing package.

' The module level variable 'CurrentColor' is set to

' a numeric value that identifies the color used for drawing.

Property Let PenColor(ColorName as String)

Select Case ColorName	' Check color name string.

Case "Red"

CurrentColor = RED	' Assign value for Red.

Case "Green"

CurrentColor = GREEN	' Assign value for Green.

Case "Blue"

CurrentColor = BLUE	' Assign value for Blue.

Case Else

CurrentColor = BLACK	' Assign default value.

End Select

End Property

' The following line sets the PenColor property for a drawing package

' by calling the Property Let procedure.

PenColor() = "Red"


Property Set Statement Example

This example uses the Property Set statement to declare a property procedure which sets a reference to an object.

' The Pen property may be set to different Pen implementations.

Property Set Pen(P As Object)

Set CurrentPen = P	' Assign Pen to object.

End Property


Public Statement Example

The Public statement is used at the module-level to declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Public Number As Integer	' Public integer variable.

Public NameArray(1 To 5) As String	' Public array variable.

Public MyVar, YourVar, ThisVar As Integer	' Multiple declarations.


ReDim Statement Example

This example uses the ReDim statement to declare dynamic-array variables and then allocate and reallocate storage space.

Dim MyArray() As Integer	' Declare dynamic array.

ReDim MyArray(5)	' Allocate 5 elements.

For I = 1 To 5	' Loop 5 times.

MyArray(I) = I	' Initialize array.

Next I

' The next statement resizes the array and erases the elements.

ReDim MyArray(10)	' Resize to 10 elements.

For I = 1 To 10	' Loop 10 times.

MyArray(I) = I	' Initialize array.

Next I

' The next statement resizes the array but does not erase elements.

ReDim Preserve MyArray(15)	' Resize to 15 elements.


Rem Statement Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Rem This is the first form of the syntax.

' This is the second form of the syntax.

MyStr1 = "Hello" : Rem Comment after a statement separated by a colon.

MyStr2 = "Goodbye" 	' This is also a comment.


Set Statement Example

This example uses the Set statement to assign object references to variables.

Set MyObject = YourObject	' Assign object reference.

' MyObject and YourObject refer to the same object.

YourObject.Text = "Hello World"	' Initialize property.

MyStr = MyObject.Text	' Returns "Hello World".

' Discontinue association. MyObject no longer refers to YourObject.

Set MyObject = Nothing


Static Statement Example

This example uses the Static statement to retain the value of a variable as long as module code is running.

' Function definition.

Function KeepTotal(Number)

' Only the variable Accumulate preserves its value between calls.

Static Accumulate

Accumulate = Accumulate + Number

KeepTotal = Accumulate

End Function

' Static function definition.

Static Function MyFunction(Arg1, Arg2, Arg3)

' All local variables preserve value between function calls.

Accumulate = Arg1 + Arg2 + Arg3

Half = Accumulate / 2

MyFunction = Half

End Function


Sub Statement Example

This example uses the Sub statement to declare the name, arguments and code that form the body of a Sub procedure.

' Sub procedure definition.

Sub SubComputeArea(Length, Width)	' Sub with two arguments.

Dim Area As Double	' Declare local variable.

If Length = 0 Or Width = 0 Then	' If either argument = 0.

Exit Sub	' Exit Sub immediately.

End If

Area = Length * Width	' Calculate area of rectangle.

Debug.Print Area	' Print Area to Debug window.

End Sub


Type Statement Example

This example uses the Type statement to define a user-defined data type.  The Type statement is used at the module level only.

Type EmployeeRecord	' Create user-defined type.

ID As Integer	' Define elements of type.

Name As String * 20

Address As String * 30

Phone As Long

HireDate As Date

End Type

Dim MyRecord As EmployeeRecord	' Declare variable.

MyRecord.ID = 12003	' Assign a value to an element.


UBound Function Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)	' Declare array variables.

Dim AnyArray(10)

Upper = UBound(MyArray, 1)	' Returns 10.

Upper = UBound(MyArray, 3)	' Returns 20.

Upper = UBound(AnyArray)	' Returns 10.


Ambiguous name detected

The identifier conflicts with another identifier or needs qualification.  More than one object in the same scope may have elements with the same name, making it necessary to qualify the element name by including the object name and a period.  For example:

object.property

Module-level identifiers and project-level identifiers (module names and referenced project names) may be reused in a procedure (although it makes programs harder to maintain and debug).  However, if you want to refer to both items in the same procedure, the item having wider scope must be qualified.  For example, if MyID is declared at the module level of MyModule, and then a procedure-level variable is declared with the same name in the module, references to the module-level variable must be appropriately qualified:

Dim MyID As String

Sub MySub

MyModule.MyID = "This is module-level variable"

Dim MyID As String

MyID = "This is the procedure-level variable"

Debug.Print MyID

Debug.Print MyModule.MyID

End Sub

An identifier declared at module level may conflict with a procedure name.  For instance, this error occurs if the variable MyID is declared at module level, and then a procedure is defined with the same name:

Public MyID

Sub MyID

. . .

End Sub

In this case, you need to change one of the names because modification with a common module name would not resolve the ambiguity.  Note that procedure names are Public by default, but variable names are Private unless specified as Public.


AppleScript error

An error occurred during processing of your script.  The error could be related to either the target application or AppleScript.


Argument in ParamArray may not be named

Arguments to a ParamArray must be positional.  To supply only some of the elements of the Paramarray, you can use commas as placeholders for those you want to omit.  For example if, in the following call, the ParamArray arguments begin after Arg2, values are being passed only for the first, third, and sixth values in the ParamArray:

MySub Arg1, Arg2, 7,, 44,,,3

Also note that the ParamArray always represents the last items in the argument list.


Argument not optional (Error 449)

The number and types of arguments must match those expected.  For instance, the Left function requires two arguments, the first representing the character string being operated on, and the second representing the number of characters to return from the left side of the string.  Because neither argument is optional, both must be supplied.

An argument can only be omitted from a call to a user-defined procedure if it was declared Optional in the procedure declaration.


Argument required for Property Let or Property Set

The purpose of Property Let and Property Set procedures is to give a new value to a property.  This value must be passed in through the last argument.  When defining such a procedure, you must include a parameter to receive the argument.


Array already dimensioned

Possible causes:

•	You attempted to change the dimensions of a static array with a ReDim statement [image] only dynamic arrays can be redimensioned.

•	An Option Base statement occurs after array dimensions are set.

To define a dynamic array, use a Dim, Public, Private, or Static statement with empty parentheses.  For example:

Dim MyArray()

In a procedure, you can define a dynamic array with the ReDim statement using a variable for the number of elements:

ReDim MyArray(n)


Array argument must be ByRef

An individual element of an array can be passed ByVal (by value), but a whole array must be passed ByRef (by reference).  Note that ByRef is the default.


Bad DLL calling convention (Error 49)

Your program is calling a routine in a dynamic-link library (DLL) that either is being passed the wrong type or number of arguments or does not use the Pascal calling convention.  Make sure that the arguments passed to the DLL routine exactly match the arguments expected by the routine.  If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.


Bad file mode (Error 54)

Possible causes:

•	A Put or Get statement is specifying a sequential file.  Note that Put and Get can only refer to files opened for Random access.

•	A Print # statement specifies a file opened for an access mode other than Output or Append.

•	An Input # statement specifies a file opened for an access mode other than Input.

•	Any attempt to write to a read-only file.


Bad file name or number (Error 52)

A statement refers to a file with a file number or file name that is:

•	An invalid name or number.

•	Not specified in the Open statement.

•	Specified in an Open statement, but has since been closed.

•	Out of the range of file numbers (1-511).

In Microsoft Windows, use the following conventions for naming files and directories:

•	The name of a file or directory can have two parts: a name and an optional extension.  The two parts are separated by a period, for example, MYFILE.NEW.

•	The name can contain up to eight characters, and the extension can contain up to three characters.

•	The name must start with either a letter or number.  It can contain any uppercase or lowercase (file names are not case-sensitive) characters except the following:

Character	Description

 .	Period

"	Quotation mark

'	Single quotation mark (apostrophe)

+	Plus sign

/	Slash

\	Backslash

[ ]	Brackets

:	Colon

;	Semicolon

|	Vertical bar

=	Equal sign

,	Comma

•	The name should not contain any spaces.  The following names are reserved and can't be used for files or directories:  CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  For instance, if you try to name a file PRN in an Open statement, the default printer will simply become the destination for Print #, and Write # statements directed to the file number specified in the Open statement.

•	The following are examples of valid Microsoft Windows file names:

LETTER.DOC

MEMO.TXT

BUDGET.92

12345678.901

2NDTRY.RPT

On the Macintosh, a file can have any character except the colon (:), and may contain spaces.  Null characters (Chr(0)) are not allowed in any file names.


Bad record length (Error 59)

The length of a record variable for a Get or Put statement does not match the length specified in the corresponding Open statement.  Because a two-byte descriptor is always added to a variable-length string Put to a random access file, the variable-length string must be at least two characters shorter than the record length specified in the Len clause of the Open statement.

Variant data types also require a two-byte descriptor.  Variants containing variable-length strings require a four-byte descriptor.  Therefore, for variable-length strings in a Variant, the string must be at least 4 bytes shorter than the record length specified in the Len clause.


Bad record number (Error 63)

The record number in a Put or Get statement is less than or equal to zero.


Beginning of search scope has been reached; do you want to continue from the end?

Your upward search has reached the beginning of the specified scope.  You can choose to continue searching from the end of the search scope, or cancel and change the scope of the search.


Block If without End If

An If statement is used without a corresponding End If statement.  For nested If...End If statements, make sure there is a correctly matched If...End If structure inside the outer If...End If structure.


Breakpoint not allowed on this line

Some lines can't accept breakpoints.  For example, you can't put a breakpoint on a comment, a line label (unless the line also contains executable code), a line in a hidden module, or lines in the Immediate pane.  Breakpoints are not allowed on declaration lines (Const, Dim, Static, Type, and so on).


ByRef argument type mismatch

When a procedure expects an argument to be passed by reference (ByRef, the default), the passed argument must have the precise data type expected.  For example, if you try to pass an Integer variable when a Long is expected, this error occurs.  If you want coercion to occur, even if it causes information to be lost, you can pass the argument in its own set of parentheses.  For example, to pass the Variant argument MyVar to a procedure that expects an integer argument, you could write the call as follows:

Dim MyVar

MyVar = 3.1415

Call SomeSub((MyVar))

Sub SomeSub (MyNum As Integer)

MyNum = MyNum + MyNum

End Sub

Placing the argument in its own set of parentheses forces evaluation of it as an expression.  During this evaluation, the fractional portion of the number is rounded (not truncated) to make it conform to the expected argument type.  The result of the evaluation is placed in a temporary location, and a reference to the temporary location is received by the procedure.  Thus, the original MyVar retains its value.


Can't assign array of fixed-length string or user-defined type to Variant

A Variant variable can't accept assignment of an array consisting of variables defined as fixed-length strings or user-defined types.


Can't assign to an array

An assignment must be to a specific array element, not simply to an array name.  For example, if MyArray is an integer array, the expression MyArray = 5 is invalid, but the following expression is valid:

MyArray(UBound(MyArray)) = 5


Can't change data types of array elements

You can change the number of elements in an array using ReDim, but the data type of its elements must remain the same as in the statement that originally created the array (unless the array is contained in a Variant).


Can't display hidden procedure

You tried to view a procedure, but the procedure can't be displayed because its module is hidden.  You need to unhide the module to view the procedure.  If you are trying to view a line that generated an error in a hidden procedure, run the code again (after unhiding the module) to view the error.


Can't edit module

The module was marked as protected.  Unprotect the module before trying to edit.


Can't find project or library

A referenced project could not be found, or a referenced object library corresponding to the language of the project could not be found.  You will not be able to run your code until all missing references are resolved.

Unresolved references are prefixed with "MISSING:" in the References dialog.  Select the missing reference to display the path name and language of the missing project or library.  Follow these steps to resolve the reference or references:

To resolve the references

1.	Choose References from the Tools menu.

2.	Select the missing reference.

3.	Choose Browse to open the Browse dialog.

4.	Use the Browse dialog to find the missing reference.

5.	Click OK.

6.	Repeat the preceding steps until all missing references are resolved.

Once you browse a missing item, the "MISSING:" prefix is removed to indicate that the link is reestablished.  If the file name of a referenced project has changed, a new reference is added, and the old reference must be removed.

To remove references that are no longer needed, simply clear the checkbox beside the unneeded reference.  Note that the references to the Visual Basic object library (VBAXX.OLB) and host-application object library cannot be removed.

Applications may support different language versions of their object libraries.  To find out which language version is required, click the reference, and check the language indicated at the bottom of the dialog.

Object libraries exist in different versions for each platform.  Therefore, when projects are moved across platforms (for example, from Macintosh to Windows), the correct language version of the referenced library (for that platform) must be available in the location specified in your host application documentation.

Object library file names are generally constructed as follows:

•	Windows:	Application Code + Language Code + [Version].OLB.  For example:

•	VBAFR.OLB would be the French Visual Basic object library.

•	XLFR50.OLB  would be the French Excel 5.0 object library.

•	Macintosh:	Application Name Language Code [Version] OLB.  For example:

•	VBA FR OLB would be the French Visual Basic object library.

•	MS Excel FR 50 OLB  would be the French Excel 5.0 object library.

If you cannot find a missing project or library on your system, contact the referencing project's author.  If the missing library is a Microsoft application object library, you can obtain it as follows:

•	If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file.  Under electronic services, you will find instructions on how to use the appropriate service option.

•	If you do not have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft.  Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.


Can't Get or Put user-defined type containing object reference

You are trying to use the Get or Put statements on a user-defined type containing an object reference.  Remove the object reference from the record variable or try using Input #, Line Input #, Print #, or Write #.


Can't load module; invalid format (Error 323)

The module you attempted to load is not a text module.  Some versions of Visual Basic permit you to save code in both binary and text formats.  If possible, reload the file in the application in which it was last saved and save it as text.


Can't perform requested operation (Error 17)

The requested operation can't be performed because it would invalidate the current state of the project.  For example, the error occurs if you use the References dialog of the Tools menu to add a reference to a new project or object library while a program is in break mode.


Can't record into running module

You can't record a macro while executing module code.  To stop execution, choose End from the Run menu or press CTRL+BREAK.


Can't rename with different drive (Error 74)

You can't use the Name statement to rename a file with a new drive designation.  Use FileCopy to write the file to another drive, and delete the old file with a Kill statement.


Case Else outside Select Case

A Case Else can only occur between matching Select Case and End Select statements.


Case without Select Case

A Case statement was used without a corresponding Select Case statement.  Check other control structures within the Select Case...Case structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Select Case...Case structure will generate this error.


Circular dependencies between modules

A user-defined type or constant in one module references a user-defined type or constant in a second module, which in turn references another user-defined type or constant in the first module.  This type of circular reference between modules, constants, and user-defined types is not allowed.


Class doesn't support OLE Automation (Error 430)

The object specified in the GetObject or CreateObject function call was found, but has not exposed a programmability interface.  Therefore you can't write code to control this object's behavior.  Check the documentation of the application that created the object for limitations on the use of OLE Automation with this class of object


Code execution has been interrupted

A CTRL+BREAK (Microsoft Windows) or COMMAND+PERIOD (Macintosh) key combination has been encountered.  Choose either Debug to enter break mode, Continue to resume, or End to terminate execution.


Code resource lock error (Error 455)

A call was made to a procedure in a code resource.  The code resource was found, but an error occurred when an attempt was made to lock the resource.  Check for an error returned by HLock (for example, "Illegal on empty handle" or "Illegal on free block").  This error can only occur on the Macintosh.


Code resource not found (Error 454)

A call was made to a procedure in a code resource, but the code resource could not be found.  This error can only occur on the Macintosh.


Compile error in hidden module: <module name>

There is a compilation error in the code of the specified module, but it can't be displayed because the project is protected.  Unprotect the project, then run the code again to view the error.


Constant expression required

A constant must be initialized.  You can't initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.  You can initialize a constant with literals, previously-declared constants, or literals and constants joined by operators (except the Is logical operator).  This error also occurs if you try to declare an array using a variable to specify the number of elements (unless you declare the array with ReDim).


Current module does not support Print method

Only Debug.Print is valid in this module.


Cyclic reference of projects not allowed

You tried to add a reference to a project that is already part of the project.  For example, if MyProj references YourProj, then YourProj (or a project that references YourProj) can't reference MyProj.


Deftype statements must precede declarations

Statements such as DefInt, DefDbl, DefCur, and so on can only occur at the module level and must precede all other variable declarations.


Destination label too far away; loop, Select Case, or block If too large

Possible causes:

•	You have a branching statement (GoTo, GoSub) whose destination label is farther away than 32,767 bytes from the source branching statement.

•	You have a very large loop structure that occupies more than 32K of memory from beginning to end.

•	You have a very large block If structure that contains a Then or Else clause that occupies more than 32K of memory from beginning to end.

Procedures can be as large as 64K from beginning to end, but because branching can occur either forward or backward within a procedure, such branching is limited to 32,767 bytes in either direction.


Device I/O error (Error 57)

An input or output error occurred while your program was using a device such as a printer or disk drive.


Device unavailable (Error 68)

The device you are trying to access is either not online or does not exist.


Disk full (Error 61)

Possible causes:

•	There is not enough room on the disk for the completion of a Print #, Write #, or Close operation.

•	There is not enough room on the disk to create required files.

Move some files to another disk, or delete some files.


Disk not ready (Error 71)

There is either no disk in the drive specified or the drive door is open.  Insert a disk in the drive, close the door, and retry the operation.


Division by zero (Error 11)

The value of an expression being used as a divisor is zero.  Check the spelling of variables in the expression.  A misspelled variable name can implicitly create a numeric variable that is initialized to zero.  Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.


Do without Loop

A Do statement was used without a terminating Loop statement.  Check that other control structures within the Do...Loop structure are correctly matched.  For example, a block If without a matching End If inside the Do...Loop structure may generate this error.


Duplicate declaration in current scope

The specified name is already used at this level of scope.  For example, two variables can have the same name if they are defined in different procedures, but not if they are defined within the same procedure.  Typical causes:

•	A new variable or procedure has the same name as an existing variable or procedure.  For example:

Sub MySub()

Dim A As Integer

Dim A As Variant

. . .	' Other declarations or procedure code here

End Sub

•	A Const statement uses the same name as an existing variable or procedure.

•	You declared a fixed array more than once.

Check the current procedure, module, or project and remove any duplicate declarations.  Choose Find from the Edit menu to locate the duplicate name.  When specifying the name to search for, omit the type-declaration character, if there is one, because a conflict occurs if the names are the same and the type-declaration characters are different.

Note that a module-level variable can have the same name as a variable declared in a procedure, but when you want to refer to the module-level variable within the procedure, you must qualify it with the module name.  Module names and the names of referenced projects can also be reused as variable names within procedures, and can also be qualified.


Duplicate definition (Error 10)

This error usually occurs only when generated from code.  For example:

Error 10

However the error may also occur if you try to use ReDim to change the number of elements of a fixed-size array.  For example, in the following code the fixed array FixedArr is received by SomeArr in the procedure NextOne, then an attempt is made to resize SomeArr:

Sub FirstOne

Static FixedArr(25) As Integer	' Create a fixed-size array &

NextOne FixedArr()	' pass it to another sub.

End Sub

Sub NextOne(SomeArr() As Integer)

ReDim SomeArr(35)	' Duplicate definition occurs here.

. . .

End Sub


Duplicate Deftype statement

Part or all of the letter range for this Deftype statement is already included in another Deftype statement.


Duplicate Option statement

You've defined more than one Option Base, Option Compare,Option Explicit, or Option Private statement in this module.  Remove any duplicates in the module.


Edit can't be undone--proceed anyway?

You will not be able to choose Undo to restore the current state after you perform this edit.  The edit may be too large to be saved.  Try performing the edit in smaller increments.


Else without If

An Else statement was used without a corresponding If statement.  Check other control structures within the If...End If structure and verify that they are correctly matched.  Also check that the block If is correctly formatted.


Empty watch expression

You did not supply a watch expression in the Add Watch dialog.


End If without block If

An End If statement is used without a corresponding If statement.  Check other control structures within the If...End If structure and verify that they are correctly matched.  Also check that the block If is correctly formatted.


End of search scope has been reached; do you want to continue from the beginning?

Your downward search has reached the end of the specified scope.  You can choose to continue searching from the beginning of the search scope, or cancel and change the scope of the search.


End Select without Select Case

An End Select statement is used without a corresponding Select Case statement.  This is usually due to an extra End Select below a Select Case block, or leaving behind the End Select statement when copying a Select Case block from one procedure to another.  Check each End Select statement to make sure it terminates a Select Case structure.


End With without With

An End With statement is used without a corresponding With statement.  Check other control structures within the With...End With structure and verify that they are correctly matched.  For example, an If without a matching End If inside the With...End With structure can cause this error.


Error accessing the system registry

The registration database for your system has been corrupted.  Run the Setup program for the host application again.


Error in loading DLL (Error 48)

The specified dynamic-link library (DLL) can't be loaded.  This is usually because the file specified with the Lib clause in the Declare statement is not a valid DLL.

Possible causes:

•	The file is not DLL-executable.

•	The file is not a Microsoft Windows DLL.

•	The file is an old Microsoft Windows DLL that is incompatible with Microsoft Windows protect mode.

•	The DLL references another DLL that is not present.

•	The DLL or one of the referenced DLLs is not in a directory specified by your path.


Exit Do not within Do...Loop

An Exit Do statement was used outside a Do...Loop statement.  Make sure a valid Do statement precedes the Exit Do.


Exit For not within For...Next

An Exit For statement was used outside a For...Next statement.  Make sure a valid For statement precedes the Exit For.


Exit Function not allowed in Sub or Property

Use the proper Exit construct for this type of procedure.


Exit Property not allowed in Function or Sub

Use the proper Exit construct for this type of procedure.


Exit Sub not allowed in Function or Property

Use the proper Exit construct for this type of procedure.


Expected array

The syntax you specified is appropriate for an array, but no array with this name is in scope.


Expected End Function

Use the proper End statement for this type of procedure.


Expected End Property

Use the proper End statement for this type of procedure.


Expected End Sub

Use the proper End statement for this type of procedure.


Expected End With

Use the proper End statement for this type of construct.


Expected Function or variable

The syntax of your statement indicates a variable or function call, but the name is not that of a known variable or function.  Check the spelling of the name.  Also, make sure that any variable or function with that name is visible in the portion of the program from which you are referencing it.  For example, if the function is defined as Private or the variable is not defined as Public, it is only visible within its own module.


Expected procedure, not module

There is no procedure by this name in the current scope, but there is a module by this name.  Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.


Expected procedure, not project or library

There is no procedure by this name in the current scope, but there is a project by this name.  Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.


Expected procedure, not user-defined type

There is no procedure by this name in the current scope, but there is a variable of user-defined type by this name.  Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.


Expected procedure, not variable

There is no procedure by this name in the current scope, but there is a variable by this name.  The error may also be caused by misspelling the name of a valid procedure, because that can be misconstrued as an implicitly defined variable.  Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.


Expected Sub or Function

The syntax of your statement indicates a Sub or Function procedure invocation, but the name specified is not that of a Sub or Function in scope in this part of your program.  Note that if the procedure is defined as Private, it can only be called from within its module.


Expected user-defined type, not project

There is no user-defined type by this name in the current scope, but there is a project by this name.  Check the spelling of the user-defined type name, and make sure the user-defined type is not private to another module.


Expected variable or procedure, not module

There is no variable or procedure by this name in the current scope, but there is a module by this name.  Check the spelling of the variable or procedure name, and make sure the name you want to refer to is not private to another module.  A module name can be a qualifier, but can't stand alone.


Expected variable or procedure, not project

There is no variable or procedure by this name in the current scope, but there is a project by this name.  Check the spelling of the variable or procedure name, and make sure the name you want to refer to is not private to another module.  A project name can be a qualifier, but can't stand alone.


Expected: <various>

An expected part of the syntax was not found.  The error is usually located to the left of the selected item, but isn't always obvious.  For example, you can invoke a Sub procedure with or without the Call keyword.  However, if you use the Call keyword, you must enclose the argument list in parentheses.

The following errors occur in the circumstances described:

•	Expected: End of Statement [image] For example, you must use parentheses if a function call specifies arguments.  Similarly, you must place parentheses around the argument list of a Sub procedure invocation when you use the Call keyword.

X = Workbook.Add F:= 5	' Error due to no parentheses

Call MySub 5	' Error due to no parentheses.

•	Expected: ) [image] For example, a function call can't stand by itself; it must be used in an expression.  Similarly, if you invoke a Sub procedure with more than one argument, and you enclose the argument list in parentheses, you must use the Call keyword.

Workbook.Add (X:=5, Y:=7)	' Function call without expression.

YourSub(5, 7)	' Sub invocation without Call.

•	Expected: Expression [image] For example, when pasting code from the Object Browser, you may have forgotten to specify a value for a named argument.

Workbook.Add (X:= )	' Error because no value assigned

' named argument.

•	Expected: Variable [image] For example, restricted keywords cannot be used for variable names.  In the example below, the Input # statement expects a variable as the second argument.  Since Type is a restricted keyword, it can't be used as a variable name.

Input # 1, Type	' Type keyword illegally used as

' variable name.


External name not defined

The identifier specified within square brackets has no meaning to the host application.


File already exists (Error 58)

At run time, this error occurs when the new file name (for example, one specified in a Name statement) is identical to a file name that already exists.  It also occurs when you use Save As to save a currently loaded project if the project name already exists.


File already open (Error 55)

Possible causes:

•	A sequential-output mode Open statement was executed for a file that is already open.

•	A statement (for example Kill, SetAttr, or Name) refers to an open file.


File format no longer supported

Not all file formats are readable under all circumstances.  For example, earlier Visual Basic modules may have to be converted to text format before they can be loaded by later versions of Visual Basic.


File not found (Error 53)

Possible causes at run time:

•	A statement (for example, Kill, Name, or Open) refers to a file that does not exist.

•	An attempt has been made to call a procedure in a dynamic-link library (DLL), but the library file name specified in the Lib clause of the Declare statement can't be found.

In the development environment, this error occurs if you attempt to open a project or load a text file that does not exist.


Fixed or static data can't be larger than 64K

Possible causes:

•	You attempted to allocate more than 64K of module-level data.  Note that although the size limit for module-level data is 64K, module-level variable-length strings and arrays can exceed this limit.

•	You attempted to allocate more than 64K of static procedure-level data in the module.  Static data from all procedures in a module is limited to a total of 64K (not 64K per procedure).  Note that static variable-length strings and arrays can exceed this limit.

•	The size of a user-defined type cannot exceed 64K (and is the sum of the sizes specified for its elements).

•	The size of a fixed-length string declared within a procedure cannot exceed 65,464, although variable-length strings can exceed this limit.


For control variable already in use

When you nest For...Next loops, you must use different control variables in each one.  For example, if the outer loop uses For Count = 1 To 25, the inner loops can't use Count as their control variables.  Check nested loops for repetition.


For Each control variable must be Variant or Object

For collections, Variant and Object data types are valid types for the control variable or element part of a For Each statement.  For arrays, the control variable or element part of a For Each statement must be a Variant type variable.


For Each control variable on arrays must be Variant

For arrays, the control variable or element part of a For Each statement must be a Variant type variable.


For Each may not be used on array of user-defined type

For Each constructs are only valid for collections and arrays of intrinsic types (including arrays of objects).


For Each may only iterate over a collection object or an array

The For Each construct can only be used with collections and arrays.  Check the spelling of the item over which you want to iterate to make sure it is a collection or array.


For loop not initialized (Error 92)

You've jumped into the middle of a For...Next loop.  Placing labels inside a For...Next loop is not recommended.


For without Next

A For statement is used without a corresponding Next statement.  Check for an incorrectly matched For...Next structure inside the outer For...Next structure.


Forward reference to user-defined type

Possible causes:

Although a user-defined type can generally be nested within other user-defined types, you can't nest a user-defined type within itself.  This may occur indirectly if you nest a type within another type in which the first is already declared.  Check the definition of each nested type to eliminate duplication.

You may have declared a variable with a user-defined type before the definition of the user-defined type appears.  In the following example, the variable OtherVar is declared before its type (OtherType) is known:

Type MyVar

OtherVar As OtherType

End Type

Type OtherType

WholeVar As Integer

RealVar As Double

End Type


Function call on left-hand side of assignment must return Variant or Object

A function call can appear on the left-hand side of an assignment, but only if the return value of the function is an object or Variant.  If the return value is an object or a Variant that contains an object, the assignment is to the default property of the object.  If the Variant returned is not an object, the assignment has no effect.


Identifier too long

Identifiers can't be more than 255 characters long.


Identifier under cursor is not a procedure name

You tried to view a procedure, but the identifier at the insertion point was not a procedure name.  Check the spelling of the identifier.


Incorrect DLL version

Your version of the Visual Basic dynamic-link library (DLL) does not match the version expected by this host application.  The program is attempting to call routines in a DLL, but the version of the library is inconsistent with either Visual Basic or the host application.


Incorrect OLE version

Your versions of the OLE dynamic-link libraries (DLL) do not match those expected by the host application.  In Microsoft Windows, the application searches for the DLLs, first in the current directory, then along your path settings, and then in the WINDOWS\SYSTEM directory.  This error results if old OLE DLLs are encountered in that search before the DLLs expected by the host application.  To use both versions of the DLLs, you must place the appropriate versions in the directory from which you invoke its corresponding application.  On the Macintosh, OLE files are normally only found in the extensions folder so it is unlikely that this error will occur.


Input past end of file (Error 62)

An Input # or Line Input # statement is reading from a file in which all data has already been read or from an empty file.  To avoid this error, use the EOF function (immediately before the Input # statement) to detect the end of file.


Insufficient memory to save Undo information

You will not be able to choose Undo to restore the current state after you perform this edit.  The edit may be too large to be saved.  Try performing the edit in smaller increments.


Internal error (Error 51)

An internal malfunction has occurred in Visual Basic.  Unless this call was generated by the Error statement, contact Microsoft Product Support Services to report the conditions under which the message appeared.


Invalid Access mode

In your Open statement, you specified an access mode that was illegal for the specified file type.

Possible causes:

•	You attempted to open a file for Input, but specified an illegal access mode.  You can omit the access mode specification when opening a file for input, but if you specify it, the access mode must be Read.  Both Write and ReadWrite are illegal access modes on a file opened for Input.

•	You attempted to open a file for Append, but specified an illegal access mode.  You can omit the access mode specification when opening a file for append, but if you specify it, the access mode must be Write.  Both Read and ReadWrite are illegal access modes on a file opened for Append.

•	You attempted to open a file for Output, but specified an illegal access mode.  You can omit the access mode specification when opening a file for output, but if you specify it, the access mode must be Write.  Both Read and ReadWrite are illegal access modes on a file opened for Output.


Invalid procedure call (Error 5)

An argument probably exceeds the range of permitted values.  For example, the Sin function can only accept values within a certain range.  Positive arguments less than 2147483648 are accepted, while 2147483648 generates this error.

This error may also occur if an attempt is made to call a procedure that is not valid on the current platform.  For example, some procedures may only be valid for the Macintosh, or for Microsoft Windows, and so forth.


Invalid attribute in Sub or Function

For example, Public and Private attributes are not permitted within the body of a procedure definition.


Invalid character

The character can't be used in the current context.  For example, a bracket or hyphen can't be used as a character in a variable name.


Invalid data format

The data read from a file was not in the expected format.  For example, a project file or object library file is either corrupted or in a format that can't be understood.  You may have attempted to load an .EXE file into a module.

You may have used the References dialog and Browse dialog via the Tools menu to add a reference to a file that is not a valid object library or contains a Basic project in a format not supported by the host application.  For example Excel can't understand .BAS or .FRM files, or Microsoft Project files containing Basic code.


Invalid data type for constant

Constants can't be arrays, objects, or have user-defined type.


Invalid in Immediate pane

Not all statements are permitted in the Immediate pane.

Possible causes:

•	Declarative statements such as Const, Declare, Deftype, Dim, Function, Option Base, Option Explicit, Option Compare, Private, Public, property procedure declaration statements (including Property Let, Property Set, Property Get), ReDim, Static, Sub, and Type are not allowed in the Immediate pane.

•	Some control flow statements such as Sub, Function, Property, GoSub, GoTo, Return, Resume, and so on are not permitted in the Immediate pane.

•	There is no logical connection made between separated physical lines in the Immediate pane, so statements formatted as multiple physical lines, such as a block If statement, can't be properly executed.  However such blocks can be typed on a single physical line, with each statement separated from the next by a colon (:).  Conversely, you can extend a single statement across physical lines in the Immediate pane by using the line-continuation character, a space followed by an underscore ( _).

•	You tried to execute some code in the Immediate pane that invalidates the current state of your program and requires you to reinitialize the program.


Invalid inside procedure

The statement can't occur in a Sub or Function procedure.  The statements Declare, Deftype, Private, Public, Option Base, Option Compare, Option Explicit, Option Private, and Type are not allowed in procedures.


Invalid length for fixed-length string

Fixed-length strings are limited to a maximum of 65,529 characters.  Variable-length strings can exceed this limit.


Invalid Next control variable reference

A Next clause specified a control variable name, but the matching For clause uses a different control variable.  If you have nested For loops, start with the innermost loop and make sure each Next clause properly matches its For clause.


Invalid or unqualified reference

An identifier beginning with a period is valid only within a With block.


Invalid ordinal (Error 452)

Your call to a dynamic-link library (DLL) indicated to use a number instead of a procedure name, using the #num syntax.  However, an attempt to convert the expression num to an ordinal failed, or the num specified does not specify any function in the DLL.  Check to make sure the expression represents a valid number, or call the procedure by name.


Invalid outside procedure

The statement must occur within a Sub or Function, or a property (Property Get, Property Let, Property Set) procedure.  Executable statements, Static, and ReDim can be used only in a Sub or Function procedure.  At the module level, you can use only comments and declarative statements such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type.  The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.


Invalid ParamArray use

The ParamArray keyword can only be applied to the last parameter in a procedure declaration.  It can't be combined with ByVal, ByRef, or Optional for the same argument.


Invalid pattern string (Error 93)

The pattern string specified in the Like operation of a search is invalid.  A common example of an invalid character list expression is [a-b , where the right bracket is missing.


Invalid procedure name

You attempted to define a procedure, but the name used for the procedure is illegal because the host already uses that identifier for another purpose.  For example, if the host application is Microsoft Excel, you can't define a procedure with the name R1C1 because that identifier is already used by Microsoft Excel.


Invalid qualifier

The qualifier must identify a project, module, object, or a variable of user-defined type.


Invalid ReDim

If you do not specify a type for a variable, the variable receives the default type, Variant.  This error occurs if a variable is implicitly declared a Variant, and you attempt to use ReDim to change it to an array.  The error can also occur if you attempt to ReDim a host object that is a member of a type library or can only be recognized by Visual Basic at run time.


Invalid type-declaration character

You can't append a type-declaration character to a variable declared in a Private, Public, or Static statement with an As clause.  Similarly, you can't append a type-declaration character to an inconsistent literal.  For example, since & is the type-declaration character for a Long integer, appending it to a literal of a different type causes this error:

10.253&


Invalid use of Null (Error 94)

You are trying to obtain the value of a Variant variable or an expression that is Null.  Null is a Variant subtype used to indicate that a data item contains no valid data.  For example:

MyVar = Null

For Count = 1 To MyVar

. . .

Next Count


Invalid use of object

You tried to use an object in a way that can't be done.  For example, you may have tried to discontinue an object reference by assigning Nothing to it, but omitted the Set keyword:

MyObject = Nothing

Omitting the Set keyword is an implicit use of Let, which causes an attempt to perform a value assignment, rather than the reference assignment.  Nothing can't be used in a value assignment.  Assuming MyObject is an object, you must set it to Nothing with the Set statement:

Set MyObject = Nothing

The error could also be produced by attempting to use Nothing in an expression:

Debug.Print 5 + Nothing


Invalid watch expression

The specified watch expression is not a valid expression.  The watch expression may be syntactically incorrect.  Note that the syntax for a watch expression corresponds to the locale of the project in which the expression being watched is defined.


Label not defined

A line label or line number is referred to (in a GoTo statement, for example), but does not occur within the scope of the reference.


Language/country setting has changed

You are changing the default language/country setting for the Visual Basic environment.


Line too long

A physical line of Visual Basic code can contain up to 1023 characters.  You can create a longer logical line by joining physical lines with a line-continuation character (a space followed by an underscore character).  Up to ten physical lines can be joined with line-continuation characters to form a single logical line.  Thus, a logical line could potentially contain a total of 10230 characters.  Beyond that, you must break the line into individual statements or assign some expressions to intermediate variables.


Loop without Do

A Do loop must begin with a Do statement.  You may have an unterminated loop block nested within another loop.  Check to verify the correct Do...Loop syntax is used.


LSet allowed only on strings and user-defined types

LSet is used to left align strings within fixed-length or variable-length strings.  LSet can also be used to assign the elements of a user-defined type variable to the elements of a different, but compatible, user-defined type.


LSet not allowed

You can't use LSet on variables of user-defined types that contain strings, objects, or variants.


Err, Erl Functions

Returns error status.

Syntax

Err

Erl

Remarks

After an error occurs, the Err function returns a number that is the run-time error number, identifying the error.  The Erl function returns a number that is the line number of the line in which the error occurred, or the numbered line most closely preceding it.

Because Err and Erl return meaningful values only after an error has occurred, they are usually used in error-handling routines to determine the error and corrective action.  Both Err and Erl are reset to 0 after any form of the Resume or On Error statement and after an Exit Sub or Exit Function statement within an error-handling routine.

Caution   If you set up an error handler using On Error GoTo and that error handler calls another procedure, the value of Err and Erl may be reset to 0.  To make sure that the value doesn't change, assign the values of Err or Erl to variables before calling another procedure or before executing Resume, On Error, Exit Sub, Exit Function, or Exit Property.

You can directly set the value returned by the Err function using the Err statement.  You can set values for both Err and Erl indirectly using the Error statement.

The Erl function returns only a line number, not a line label, located at or before the line producing the error.  Line numbers greater than 65,529 are treated as line labels and can't be returned by Erl.  If your procedure has no line numbers, or if there is no line number before the point at which an error occurs, Erl returns 0.


Err Statement

Sets Err to a specific value.

Syntax

Err = errornumber

Elements

The errornumber argument can be any valid error number or 0, which means no run-time error occurred.

Remarks

Err is used to record whether a run-time error has occurred and identifies the error.  Use the Err statement to set Err to a nonzero, whole number to communicate error information between procedures.  For example, you might use one of the unassigned run-time error numbers as an application-specific error number.  To determine which error numbers are being used, use the Error function, the Error statement, or both.  To avoid conflict with existing error numbers, create user-defined errors by defining your first error at 65,535 and work down from there.

You can also set Err to 0 using any form of the Resume or On Error statement or by executing an Exit Sub, Exit Function or Exit Property statement within an error handler.  In addition, the Error statement can set Err to any value to simulate any run-time error.


Error Function

Returns the error message that corresponds to a given error number.

Syntax

Error[(errornumber)]

Elements

The errornumber argument can be any valid error number.  If errornumber is not defined, an error occurs.  If omitted, the message corresponding to the most recent run-time error is returned.  If no run-time error has occurred, Error returns a zero-length string ("").

Remarks

Use the Err function to return the error number for the most recent run-time error.


Error Statement

Simulates the occurrence of an error.

Syntax

Error errornumber

Elements

The errornumber can be any valid error number.

Remarks

If errornumber is defined, the Error statement simulates the occurrence of that error; that is, it sets the value of Err to errornumber.

To define your own error numbers, use a number greater than any of the standard error numbers.  To avoid conflict with existing error numbers, create user-defined errors by defining your first error at 65,535 and work down from there.

If an Error statement is executed when no error-handling routine is enabled, an error message is displayed and execution stops.  If the Error statement specifies an error number that is not used, an error message is displayed.


On Error Statement

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

Syntax

On Error GoTo line

On Error Resume Next

On Error GoTo 0

Elements

The On Error statement syntax can have any of the following forms:

Statement	Description

On Error GoTo line 	Enables the error-handling routine that starts at line, which is any line label or line number.  Thereafter, if a run-time error occurs, control branches to line.  The specified line must be in the same procedure as the On Error statement.  If it isn't, a compile-time error occurs.

On Error Resume Next	Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred. In other words, execution continues.

On Error GoTo 0	Disables any enabled error handler in the current procedure.

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is generated and execution stops.

If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error.  If the calling procedure has an enabled error handler, control is returned to the calling procedure and its error handler is activated to handle the error.  If the calling procedure's error handler is also active, control is passed back through any previous calling procedures until an inactive error handler is found.  If no inactive error handler is found, the error is fatal at the point at which it actually occurred.  Each time the error handler passes control back to the calling procedure, that procedure becomes the current procedure.  Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement.

Notice that an error-handling routine is not a Sub or Function procedure.  It is a block of code marked by a line label or line number.

Error-handling routines rely on the value in Err to determine the cause of the error.  The error-handling routine should test or save this value before any other error can occur or before a procedure that could cause an error is called.  The value in Err reflects only the most recent error.  You can use the Error function to return the error message associated with any given run-time error number returned by Err.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the error-handling routine.  This allows execution to continue despite a run-time error.  You can then build the error-handling routine in line with the procedure rather than transferring control to another location within the procedure.

On Error GoTo 0 disables error handling in the current procedure.  It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0.  Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement, as appropriate, immediately ahead of the error-handling routine, as in the following example:

Sub InitializeMatrix(Var1, Var2, Var3, Var4)

On Error GoTo ErrorHandler

. . .

Exit Sub

ErrorHandler:

. . .

Resume Next

End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the normal procedure flow.  This is only one possible solution; error-handling code can be placed anywhere in a procedure.


Resume Statement

Resumes execution after an error-handling routine is finished.

Syntax

Resume [0]

Resume Next

Resume line

Elements

The Resume statement syntax can have any of the following forms:

Statement	Description

Resume [0]	If the error occurred in the same procedure as the error handler, execution resumes with the one that caused the error.  If the error occurred in another procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.

Resume Next	If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error.  If the error occurred in another procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine.

Resume line	Execution resumes at line, which is a line label or line number.  The argument line must be in the same procedure as the error handler.

Remarks

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

When an error-handling routine is active and the end of the procedure (an End Sub, End Function, or End Property statement) is encountered before a Resume statement is encountered, an error occurs because a logical error is presumed to have been made inadvertently.  However, if an Exit Sub, Exit Function, or Exit Property statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of execution.


Maximum number of list items added

You have added the total number of items the Watch pane can contain.


Member not defined

The collection, object, or user-defined type does not contain the referenced member.  You may have misspelled the object or member name, or specified a collection index that is out of range.  Check the Count property to determine whether a collection member exists.  Check the Type...End Type statement or the object documentation to determine members and the proper spelling of the object or member names.


Missing end bracket

An open bracket must be matched by a closing bracket.


Module not found

The requested module does not exist in the specified project.  For example, the following code generates this error when MyModule is not visible in the project MyProject:

MyModule.SomeVar = 5


Must be first statement on the line

The Sub, Function, and Property statements must always be the first statement on any line in which they appear.  Additionally, End If, Else (only when used in a block If structure), and ElseIf can be used only when they are the first statements on a line.


Name conflicts with existing module, project, or object library

There is already a module, project, or object library with this name referenced in this project, so the duplicate reference can't be added.  Names in the References dialog of the Tools menu are not qualified by a path, so files from different directories are indistinguishable unless they have different file names.  Note that a file name extension is not considered part of the name, so different extensions can't be used to distinguish one file from another.  To add the file, change the name of the file that could not be added.

This error can also occur when attempting to add a reference to a project or library whose file name (without extension) is the same as the name of one of the current project's modules.  In this case, you could change either the module name or the name of the file that could not be added.


Named argument already specified

When you use a named argument, you can only use it once in an argument list.  For example, if the procedure MySub expects the named arguments Arg1 and Arg2, both the following calls would generate this error:

Call MySub(1, Arg1:=3)

Call MySub(Arg1:=3, Arg1:=5)


Named arguments not allowed

You are trying to use a named argument where it is not allowed.  For example, consider the following:

•	Where MyVar2 is a Property Let or Property Set procedure:

MyVar1 = MyVar2(myNamedArg := 1)	'Invalid with Property Let or

'Property Set procedures.

•	Where MyVar2 is an array:

MyVar1 = MyVar2(myNamedArg := 1)	'Invalid with arrays.

•	Where MyVar2 is an object:

MyVar1 = MyVar2(myNamedArg := 1)	'Invalid with objects.

•	Where MyVar2 is an external name:

MyVar1 = [MyVar2](myNamedArg := 1)	'Invalid with external names.

•	Where MyVar2 is a data member of an object:

MyVar1 = [MyVar2](myNamedArg := 1)	'Invalid with data members.


Named argument not found (Error 448)

You specified a named argument, but the procedure was not defined to accept an argument by that name.  Check the spelling of the argument name.


Next without For

A Next statement was used without a corresponding For statement.  Check other control structures within the For...Next structure and verify that they are correctly matched.  For example, an If without a matching End If inside the For...Next structure will generate this error.


No text selected

You must select some text to perform this operation.  To select text, place the cursor at the beginning of the desired selection, then hold down SHIFT and use either the arrow keys or click on the end of the line of text to complete the selection.


No watch expression selected

You must have an expression selected when you choose Instant Watch.  Highlight the watch expression in a code pane before choosing Instant Watch.


Object doesn't support current locale setting (Error 447)

The object you are attempting to access does not support the locale setting for the current project.  For example, if your current project has the locale setting Canadian French, the object you are trying to access must support that locale setting.  Check which locale settings the object supports.

Also note that the object may rely on national language support in a dynaminc-link library (DLL), for example OLE2NLS.DLL.  If so, you may need a more recent version that supports the current project locale.


Object doesn't support named arguments (Error 446)

Arguments can only be specified positionally when performing methods on this object.  See the object's documentation for more information on argument positions and types.


Object doesn't support this action (Error 445)

This method or property is not supported by this object.  See the object's documentation for more information on the object and to check the spellings of properties and methods.


Object library not registered

An attempt was made to load the Visual Basic object library (VBAXX.OLB) or host-application object libraries.  However, the correct language version of these object libraries could not be found in the system registry.  To fix this problem, delete the VBA.INI file from your Windows directory or Preferences folder, and restart your application.


Object not a collection (Error 451)

You have specified an operation or property that is exclusive to collections, but the object is not a collection.  Check the spelling of the object or property name, or verify that the object is a collection.


Object received ByVal can't be passed ByRef to another procedure

An object was passed ByVal (by value) into one procedure, and you tried to pass it on by reference (ByRef, the default) to another procedure.  For example:

Sub FirstOne(ByVal MyObject As Object)

NextOne MyObject

End Sub

Sub NextOne(ThisObject As Object)	' Note that default is ByRef.

. . .

End Sub

If an object is passed into a procedure ByVal, it must be passed ByVal when passed on to other procedures.  If the procedure you are passing the object on to specifies a ByRef object argument, you can override that by designating the argument ByVal in the call.  For example:

Sub FirstOne(ByVal MyObject As Object)

NextOne ByVal MyObject	' Override potential conflict.

End Sub


Object required (Error 424)

You have referred to an object property or method, but have not provided a valid object qualifier.


Object variable not Set (Error 91)

You are attempting to use an object variable that is not yet referencing a valid object, or one that has been set to Nothing.  Specify or respecify a reference for the object variable.  For example, if the Set statement were omitted in the following code, an error would be generated:

Dim MyObject As Object	' Creates object variable.

Set MyObject = Sheets(1)	' Creates valid object reference.

MyCount = MyObject.Count	' Assigns Count value to MyCount.


OLE Automation error (Error 440)

An error occurred while executing a method or accessing a property of an object variable.  The error was reported by the application that created the object.


Object doesn't support this property or method (Error 438)

This method or property does not exist for this OLE automation object.  See the object's documentation for more information on the object and to check the spellings of properties and methods.


Only comments may appear after End Sub, End Function, or End Property

Executable code is not permitted outside procedures.  Any nondeclarative lines outside a procedure must begin with a comment delimiter (an apostrophe).  Declarative statements must appear before the first procedure declaration.  Comments are ignored when the code executes.


Optional argument must be Variant

Only Variant type variables can be optional.  Change any optional arguments to Variant type.


Out of memory (Error 7)

More memory was required than is available, or a 64K segment boundary was encountered.  To prevent this error, try the following:

•	Close any unnecessary applications, documents, or source files that are in memory.

•	If you have extremely large modules or procedures, consider breaking them into smaller ones.  This doesn't save memory, but it can prevent hitting 64K segment boundaries.

•	If you are running Microsoft Windows in standard mode on an 80386 or 80486 computer, try running in enhanced mode.

•	If you are running Microsoft Windows in enhanced mode, free up some disk space, or at least ensure that some space is available.

•	Eliminate terminate-and-stay-resident programs.

•	Eliminate unnecessary device drivers.

•	Reduce the number of global variables.


Out of memory; some watches might have been deleted

When your system runs out of memory, watch expressions are deleted to make enough memory available to permit recovery from the condition.  To continue working, remove any dispensable elements from memory, including unnecessary applications, projects, or modules that may be loaded.


Out of resources

Certain types of resources, called "handles," are used internally for many operations.  Your code may have reached a resource limit.  Try saving, closing, and reloading your code.  If you still receive this error message, reduce the number of objects referenced in the code.


Out of stack space (Error 28)

Possible causes:

•	Too many active Function or Sub calls.  Check that general recursive procedures are not nested too deeply and that they terminate properly.

•	Local variables require more local variable space than is available.  Try declaring some variables at the module level instead.  You can also declare all variables in the procedure static by preceding the Property, Sub, or Function keyword with Static.  Or you can use the Static statement to declare individual static variables within procedures.

•	Fixed-length strings use more stack space than variable-length strings.  Try redefining some of your fixed-length strings as variable-length strings.

•	Too many nested DoEvents statements.

Use the Calls dialog to view which procedures are active (on the stack).  To display the Calls dialog, select the button to the right of the Procedures box in the Debug window.


Out of string space (Error 14)

Your system may have run out of memory, which has prevented a string from being allocated.  Similarly, expressions requiring that temporary strings be created for evaluation may be causing this error.  For example, the following code will cause an Out of string space error:

MyString = "Hello"

For Count = 1 To 100

MyString = MyString & MyString

Next Count

Visual Basic lets you allocate a string with a maximum length of 65,535 characters.  However, in executing statements at run time, the host application needs to use some string space for overhead.  The amount of overhead varies among hosts, but should not exceed 50 bytes.  If you need to allocate a string of the maximum length your host can support, reduce the string size by 50 bytes, then increase the length incrementally until this error is generated again.  The value immediately preceding the error represents the host's maximum string length.

Dim MyString As String * 65485	' Start with (65535-50).

' On successive runs, increment

' length until "Out of string space"

Sub MySub	' error occurs.

MyString = "string"	' Error occurs here when the

End Sub	' maximum length is exceeded.


Overflow (Error 6)

Possible causes:

•	The result of an assignment, calculation, or data type conversion is too large to be represented within the range allowed for that type of variable.

•	An assignment to a property exceeds the maximum value the property can accept.


ParamArray must be declared as an array of Variant

You can supply any number of arguments in a ParamArray, but the procedure must be defined with the ParamArray variable as an array of Variant type.  When the call is made, each argument supplied in the call becomes a corresponding element of the Variant array.  For example:

Sub MySub(ParamArray VarArg())

. . .

End Sub

Call MySub ("First arg", 2, 3.54)


Path not found (Error 76)

During a file- or disk-access operation (for example, Open, MkDir, ChDir, or RmDir), the operating system was unable to find the specified path.  The error also occurs in the debugging environment if you attempt to open a project or insert a text file with an invalid path.  Make sure the path is typed correctly.


Path/File access error (Error 75)

During a file- or disk-access operation (for example, Open, MkDir, ChDir, or RmDir), the operating system could not make a connection between the path and the file name.

Make sure the file specification is formatted correctly.  A file name can contain a fully-qualified or relative path.  A fully-qualified path starts with the drive name (if the path is on another drive) and lists the explicit path from the root to the file.  Any path that is not fully qualified is relative to the current drive and directory.

This error can also occur while attempting to save a file that would replace an existing read-only file.


Permission denied (Error 70)

An attempt was made to write to a write-protected disk or to access a locked file.  For example, this error will occur if an Open For Output statement is performed on a write-protected file.


Procedure type mismatch

You are using a Property procedure where a Function procedure is expected, or vice versa.


Project not found

You have specified a project name that could not be found.


Property or method not found (Error 423)

Object.method or object.property is referred to, but method or property is not defined, or you may have misspelled the name of the object.  To see what properties and methods are defined for an object, choose the Object Browser from the View menu.  Select the appropriate library and object to display available properties and methods.


Qualified name disallowed in module scope

Only declarations are permitted at the module level.


Qualifier must be collection

The name on the left side of the exclamation point (!) is not the name of a collection.  Check to make sure the name is spelled correctly.


Range has no values

You specified your array boundaries incorrectly.  For example, the following ranges are invalid:

Dim MyArray(10 to -5)

Dim MyArray(0 to 0)

Check to be sure your syntax is correct.  For example, the following range is valid:

Dim MyArray(-5 to 10)


Resume without error (Error 20)

A Resume statement has been encountered, but either it is outside the error handler code, or it was encountered while there was no error-handling routine active.


Return without GoSub (Error 3)

A Return statement does not have a corresponding GoSub statement.  Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.


RSet allowed only on strings

RSet is used to right align strings within fixed-length or variable-length strings.  Unlike LSet, RSet can't be used to assign the elements of a user-defined-type variable to the elements of a different, but compatible, user-defined type.


Run-time error <number>:

This error is user defined.


Search string too long or complex

The search string specified is either too long, or the combination of wildcard specifications can't be understood.


Search string must be specified

A search operation can't be performed without a string for comparison.  You must specify the search string.


Search text is not found

There is no matching text between the start point and end point of the specified search scope.  You can widen the scope of the search if you want to continue searching.  This error also occurs if you fail to provide a left bracket when using a pattern-matching expression.


Seek failed: can't read/write from the disk

Seek statements are carried out directly to disk.  If the disk or file is write-protected, read-only or locked, or has become unavailable (for example, if a removable disk has been physically changed), the Seek statement can't succeed.  Check the access status of the file and the physical status of the disk itself.  This error may occur occasionally during an attempt to read from a project file or a type library, in which case the file has been corrupted.


Select Case without End Select

A Select statement is used without a corresponding End Select statement.  Check if there is an incorrectly matched Select...End Select structure inside the outer Select...End Select structure.  If you have nested Select Case statements, each must have a matching End Select.


Selected watch expression invalid

You chose Instant Watch, but the selected expression is not a valid expression.  For example, you can't watch a comment or a Sub procedure call.  The watch expression must also have code syntax corresponding to the locale of the project that defines the expression being watched.


Set assignment to ByVal Variant argument or ByVal object argument not allowed

You can't use Set with an argument or parameter that has been specified as ByVal.


SHARE.EXE required

The program SHARE.EXE must be running when you start Visual Basic.  To fix this problem now, close your application, start SHARE.EXE, then restart your application.  To avoid this problem in the future, place an invocation of SHARE.EXE in your AUTOEXEC.BAT file so it will automatically be started when you turn on your machine.


Specified DLL function not found (Error 453)

The dynamic-link library (DLL) in a user library reference was found, but the DLL function specified was not found within the DLL.  An invalid ordinal may have been specified in the function declaration.  Also, the DLL may have the right name but is not the version that contains the specified function.


Specified library or project already referenced

You selected a type library or project from the Browse dialog that is already listed in the References dialog.  The References dialog displays referenced libraries and projects.


Statement invalid inside Type block

Only comments and the As type clause are allowed within a Type...End Type pair.


Statement invalid outside Type block

You may have tried to declare a variable outside a Type...End Type block or outside a Dim, Redim, Static, Public, Private statement.  For example, the first declaration of MyVar in the following code generates this error, but the second declaration of MyVar is valid:

MyVar As Double

Type AType

MyVar As Double

End Type

The error may also be caused by an End Type occurring without a corresponding Type statement.


Statement too complex

Visual Basic is unable to parse the statement due to its complexity or you may have used too many function calls within a statement or function.  Try breaking the statement into several smaller components or replace complex conditional clauses with a combination of logical operators and If...Then statements.  Make function calls earlier and assign the results to specific variables; then use the variables in the statement that is causing the complexity error.


Statements or labels invalid between Select Case and first Case

A Select Case statement must be immediately followed by its first Case statement.  You can't place anything but a comment between the Select Case and the first Case clause.


String expression too complex (Error 16)

A string expression is too complicated.  Strings not assigned to variables (such as those returned by functions) are assigned to temporary locations during string expression evaluation.  Having a large number of these strings can cause this error.  Try assigning these strings to variables and use the variables in the expression instead.


Sub or Function not defined (Error 35)

A Sub, Function, or Property procedure is called but is not defined.

Possible causes:

•	You have misspelled the name of your procedure.

•	The specified procedure is not visible to the calling procedure.  Procedures declared Private in one module can't be called from procedures outside the module.  If Option Private Module is in effect, procedures in the module are not available to other projects.  Choose Find from the Edit menu to locate the procedure.

•	You have declared a dynamic-link library (DLL) routine, but the routine is not in the specified library.


Subscript out of range (Error 9)

You have referenced a nonexistent array element or collection member.  The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application.


Syntax error

Visual Basic can't determine what action to take.

Possible causes:

•	A keyword or argument is misspelled.

•	Punctuation is incorrect.

•	A procedure is not defined.

•	You tried to specify both Optional and ParamArray in the same procedure declaration.


Too many arguments

You specified more than 60 arguments to a procedure.


Too many code panes open

The maximum number of windows viewing this module has been exceeded.


Too many dimensions

Arrays can have no more than 60 dimensions.  The number of dimensions may also be limited by available memory.


Too many DLL application clients

The dynamic-link library (DLL) for Visual Basic can only accommodate access by 50 host applications at a time.  Reduce the number of open applications accessing Visual Basic.


Too many files (Error 67)

Possible causes:

•	There is a limit to the number of disk files that can be open at one time.  For Microsoft Windows, this limit is a function of the Files= setting in your CONFIG.SYS file.  Increase that number and reboot.

•	The operating system has a limit to the number of files in the root directory (usually 512).  If your program is opening, closing, or saving files in the root directory, change your program so that it uses a subdirectory.

•	On the Macintosh, the standard limit is 40 files.  This limit can be changed using a utility to modify the MaxFiles parameter of the boot block.


Too many line continuations

More than 10 consecutive lines have been joined with line-continuation characters.  Make some of the constituent lines physically longer (to reduce the number of line-continuation characters needed), or break the construct into more than one statement.


Type-declaration character does not match declared data type

If a variable is declared to be of a specific type, only the matching type-declaration character can be used.  The type can't be changed by appending the type-declaration character for another type.


Type-declaration character not allowed

You can't use a type-declaration character in the declaration of a variable that uses the As clause, as for instance with Dim, Static, Public, and so on.  The Boolean, Date, Object, and Variant types have no associated type-declaration characters.


Type-declaration character required

A variable that was originally declared with a type-declaration character was referenced without a type-declaration character.  For example:

MyStr$ = "Implicit declaration"

MyStr = "Trying to refer to MyStr$ but calling it MyStr"

Note that if the variable declaration contains a type-declaration character, inclusion of the character is optional in later references.  For example:

Dim MyStr$

MyStr = "Because it was explicitly declared, the $ is optional"

Finally, note that if MyStr is explicitly declared with an As clause, the type-declaration character can't be used, either in the declaration or in subsequent references:

Dim MyStr As String

MyStr$ = "This causes a Duplicate definition error!"


Type mismatch (Error 13)

Possible causes:

•	The variable or property is not of the correct type.  For example, a variable that requires an integer value can't accept a string value.

•	An object has been passed to a procedure that is expecting a single property or value.

•	A module or project name was used where an expression was expected, for example:

Debug.Print MyModule

•	You attempted to mix traditional Basic error handling with variant values having the Error subtype (10, vbError); for example:

Error CVErr(n)

•	A CVErr value can't be converted to Date or numeric types (Integer, Long, and so on); for example:

MyVar = CInt(CVErr(9))

At run time, this error typically indicates that a Variant used in an expression has an incorrect subtype, or that a Variant containing an array appeared in a Print statement.


Type mismatch: array or user-defined type expected

If a parameter is declared as an array or user-defined type (record variable), a reference to a whole array or user-defined type must be given as the argument, rather than a single element or a simple variable, literal, or constant.


Unable to read from the disk

There is a general problem reading from a disk.  The disk may not be properly formatted.  If the disk is removable, check the drive door.  If it is a floppy disk, make sure it is inserted right-side up.


Unable to write to the disk

There is a general problem writing to a disk.  The disk may not be properly formatted.  If the disk is removable, check the drive door.  If it is a floppy disk, make sure it is not write-protected and is inserted right-side up.


Unmatched brackets in search string

An open bracket must be matched by a closing bracket.


Unrecognized project language

The specified code locale for the project to be loaded is not currently supported by this application.  This error could occur if a project is created on a system that supports the code locale, and the project is then moved to a system where that code locale is not recognized.  For example, the OLE2NLS.DLL on the current machine may be an old version that does not recognize the code locale.  Also check to be sure the correct object libraries are available.


Object library feature not supported

An attempt was made to access an object library data type or function that can't be supported by Visual Basic.  Contact the creator of the object library for more information on when it is appropriate to use the object library, and the tools with which it should be used.


User interrupt occurred (Error 18)

A CTRL+BREAK or other interrupt key has been pressed.


User-defined error (Error 95)

The application has executed the Error n statement, which caused a trappable user-defined error.  If the Error statement specifies an error code that is not used by Visual Basic, the Error function returns the message User-defined error.


User-defined type may not be passed ByVal

User-defined types can only be passed by reference.  Remove the ByVal keyword.  If you want to keep changes from being propagated back to the caller, Dim a temporary variable of the type and pass the temporary variable into the procedure.  The error may not be reported until the call is made.


User-defined type not defined

A variable or argument was declared with an undefined data type.  Use the Type statement in a module to define a new data type.


User-defined type without members not allowed

You can't create a user-defined type containing no member elements.  Check the Type...End Type statement for unintentional comment delimiters.


Variable not defined

You've used an Option Explicit statement to require the explicit declaration of variables, and you've used a variable without declaring it.  Using this option protects your application from having undeclared variables and eliminates the possibility of creating new variables when making typographical errors.


Variable required

Possible causes:

•	You have attempted to use a numeric expression as an argument to the Len function.  The Len function does not accept a numeric expression, but it does accept either a string or numeric variable or a string expression.

•	You have used a function call or an expression as an argument to Input, Let, Get, or Put.  For example, you've used an argument that appears to be a valid reference to an array variable, but instead is a call to a function of the same name.  These statements do not accept function calls as arguments.

This error typically occurs when you attempt to assign a value to something that can't accept the assignment.  For example, you can't assign a value to a Sub name or to an expression.  The loop counter in a For construction must also be a variable.  Similarly, while the Len function can accept a numeric variable as an argument, it can't accept a numeric literal or a binary numeric expression as an argument.


VBA object library not found

The Visual Basic object library (VBAXX.OLB) corresponding to the language of the project could not be found.  The object library could be either missing completely, not in the expected directory, or could be an incorrect version.  Search your disk to make sure it is in the correct directory, as specified in the host-application documentation.

If the missing library is a language version that is installed by the host application, it may be easiest to simply rerun the setup program.  If your project requires a different language object library than the one that ships with your host application (for example, if someone sent you a project written on a machine set up for a different language), make sure the correct language version of the Visual Basic object library was included with the project, and that it is installed in the expected location.

Applications may support different language versions of their object libraries.  To find out which language version is required, click the reference, and check the language indicated at the bottom of the dialog.

Object libraries exist in different versions for each platform.  Therefore, when projects are moved across platforms (for example, from Macintosh to Windows), the correct language version of the referenced library (for that platform) must be available in the location specified in your host application documentation.

The Visual Basic object library file name is constructed as follows:

•	Windows:	Application Code + Language Code + [Version].OLB.  For example:

•	VBAFR.OLB would be the French Visual Basic object library.

•	Macintosh:	Application Name Language Code [Version] OLB.  For example:

•	VBA FR OLB would be the French Visual Basic object library.

If you cannot find a missing project or library on your system, contact the referencing project's author.  If the missing library is a Microsoft application object library, you can obtain it as follows:

•	If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file.  Under electronic services, you will find instructions on how to use the appropriate service option.

•	If you do not have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft.  Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.


Warning: custom language settings not portable

When you choose a Custom language/country settings for your code, the language conventions used in your code match those set in the Control Panel of your system.  You can use custom code locale settings, but your code may not work in other locales or on other systems with different settings.  The host application parses some strings based on the Control Panel settings of the machine on which it is running.

If the Control Panel settings on the target machine are not the same as those on the machine on which the code was written, strings parsed by a host application (for example, code that depends on a locale-specific decimal separator) will not work.  Therefore, you should not use Custom language settings unless you do not intend to send your code to other users.  If you plan to send your code to other users, please select a predefined locale.


Wend without While

Every Wend statement must be preceded by a matching While.  Check for an unterminated loop nested within the While...Wend loop that is causing the error.


While without Wend

A While statement is used without a corresponding Wend statement.  Check for an incorrectly matched While...Wend structure inside the outer While...Wend structure.


With object must be user-defined type or Object

You tried to use a nonobject variable (or a variable that was not of user-defined type) within a With block.  Check to see if you misspelled the name of the object or user-defined type variable.


Wrong number of arguments (Error 450)

The number of arguments in the call to the procedure was not the same as the number of arguments expected by the procedure.  Check the argument list in the call against the procedure declaration.


Wrong number of dimensions

You referred to an array with a different number of dimensions than it actually contains.  For example, referring to an array as X(2,4), an array with two dimensions, when it has been defined as Dim X(5), a one-dimensional array, will generate this error.


You'll have to restart your program after this edit{bmc emdash.bmp}proceed anyway?
You'll have to restart your program after this edit [image] proceed anyway?

You can't edit code while in break mode.  If you choose Yes, execution will terminate and you will be able to edit your code.  If you choose No, you can continue running the code from the point at which it was suspended.


Err, Erl Functions Example

This example shows an error-handling routine which uses the Err and Erl functions.  If there are no additional errors, Err returns error number 11 and Erl returns line 1030.

Sub ErrDemo()

1010  On Error GoTo ErrorHandler	' Set up an error handler.

1020  B = 1: C = 0	' Initialize variables.

1030  A = B \ C	' Cause a "Division by zero" error.

1040  Exit Sub

ErrorHandler:	' Error handler.

ErrorNumber = Err 	' Get run-time error number.

ErrorLine = Erl	' Get line number.

Resume Next	' Resume execution at next line.

End Sub


Err Statement Example

This example shows how the Err statement is used to clear an error by setting Err to 0.  Error number 55 is generated to illustrate its usage.

On Error Resume Next	' Enable error handling.

Open "TESTFILE" For Output as #1	' Open file for output.

Kill "TESTFILE"	' Attempt to delete open file.

Select Case Err	' Evaluate Error Number.

Case 55	' "File already open" error.

Close #1	' Close open file.

Kill "TESTFILE"	' Delete file.

Err = 0	' Reset Err to 0.

Case Else

' Handle other situations here...

End Select


Error Function Example

This example uses the Error function to print error messages that correspond to the specified error numbers.

For ErrorNumber = 61 To 64	' Loop through values 61 - 64.

Debug.Print Error(ErrorNumber)	' Print error to Debug window.

Next ErrorNumber


Error Statement Example

This example uses the Error statement to simulate error 11.

On Error Resume Next	' Enable error handling.

Error 11	' Simulate the "Division by zero" error.


On Error Statement Example

This example uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure.  Attempting to delete an open file generates error number 55.  The error is handled in the error-handling routine and control is then returned to the statement that caused it.

Sub OnErrorStatementDemo()

On Error GoTo ErrorHandler	' Enable error-handling routine.

Open "TESTFILE" For Output as #1	' Open file for output.

Kill "TESTFILE"	' Attempt to delete open file.

Exit Sub	' Exit Sub before error handler.

ErrorHandler:	' Error-handling routine.

Select Case Err	' Evaluate Error Number.

Case 55	' "File already open" error.

Close #1	' Close open file.

Case Else

' Handle other situations here...

End Select

Resume	' Resume execution at same line

' that caused the error.

End Sub


Resume Statement Example

This example uses the Resume statement to end error handling in a procedure and resume execution with the statement that caused the error.  Error number 55 is generated to illustrate its usage.

Sub ResumeStatementDemo()

On Error GoTo ErrorHandler	' Enable error-handling routine.

Open "TESTFILE" For Output As #1	' Open file for output.

Kill "TESTFILE"	' Attempt to delete open file.

Exit Sub	' Exit Sub before error handler.

ErrorHandler:	' Error-handling routine.

Select Case Err	' Evaluate Error Number.

Case 55	' "File already open" error.

Close #1	' Close open file.

Case Else

' Handle other situations here...

End Select

Resume	' Resume execution at same line

' that caused the error.

End Sub


Close Statement

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

Syntax

Close [filenumberlist]

Elements

The filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number:

[#]filenumber][,[#]filenumber] . . .

Remarks

If you omit filenumberlist, all active files opened by the Open statement are closed.

When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file.  All buffer space associated with the closed file is released.

When the Close statement executes, the association of a file with its file number ends.


EOF Function

Returns a value that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

Elements

The filenumber named argument is any valid file number.

Remarks

Use EOF to avoid an error when attempting to get input past the end of a file.

False is returned unless the end of the file has been reached; then True is returned.  When used with files opened for Random or Binary access, EOF returns False unless the last executed Get statement is unable to read an entire record; then True is returned.


FileAttr Function

Returns file mode or operating system file handle information for files opened using the Open statement.

Syntax

FileAttr(filenumber,returnType)

Elements

The FileAttr function syntax has these named-argument parts:

Part	Description

filenumber	Any valid file number.

returnType	Number indicating the type of information to return: specify 1 to return a value indicating the file mode; specify 2 to return the operating system file handle.

Return Values

When the returnType argument is 1, the following return values indicate the file mode:

Value	File Mode

1	Input

2	Output

4	Random

8	Append

32	Binary


 FreeFile Function

Returns the next file number available for use by the Open statement.

Syntax

FreeFile[(rangenumber)]

Elements

The rangenumber argument specifies the range from which the next free file number is to be returned.  Specify a 0 (default) to return a file number in the range 1 to 255, inclusive.  Specify a 1 to return a file number in the range 256 to 511.

Remarks

Use FreeFile when you need to supply a file number and you want to make sure the file number is not already in use.


Get Statement

Reads from an open disk file into a variable.

Syntax

Get [#]filenumber,[recnumber],varname

Elements

The Get statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which reading begins.

varname	Valid variable name into which data is read.

Remarks

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on.  If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is read.  Delimiting commas must be included, for example:

Get #4,,FileBuffer

For files opened in Random mode, the following rules apply:

•	If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get still reads subsequent records on record-length boundaries.  The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer.  Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read.

•	If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then the data that goes into the variable.  Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

•	If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then the data that goes into the variable.  For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

•	If the variable being read into is a String Variant (VarType 8), Get reads 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data.  The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

•	If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data.  The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.

•	Get reads elements of user-defined types as if each were being read individually except that there is no padding between elements.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the individual elements.

For files opened in Binary mode, all of the Random rules apply except that:

•	In Binary mode, the Len clause in the Open statement has no effect.  Get reads all variables from disk contiguously; that is, with no padding between records.

•	Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor.  The number of bytes read equals the number of characters already in the string.  For example, the following statements read 10 bytes from file number 1:

VarString = String(10," ")

Get #1,,VarString


 Input # Statement

Reads data from an open sequential file and assigns the data to variables.

Syntax

Input #filenumber,varlist

Elements

The Input # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

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

Remarks

When read, standard string or numeric data is assigned to variables as is.  The following table illustrates how other input data is treated:

Data	Value assigned to variable
Delimiting comma or blank line	Empty.
#NULL#	Null.
#TRUE# or #FALSE#	True or False.
#yyyy-mm-dd hh:mm:ss#	The date and/or time represented by the expression.
#ERROR errornumber#	errornumber (variable is a Variant tagged as an error).
Double quotation marks (") within input data are ignored.

Data items in a file must appear in the same order as the variables in varlist and be matched with variables of the same data type.  If a variable is numeric and the data is not, zero is assigned to the variable.

If the end of the file is reached while a data item is being input, the input is terminated and an error occurs.

Note   In order to correctly read data from a file into variables, you should always use the Write # statement instead of the Print # statement to write the data to the files.  Using Write # ensures that each separate data field is properly delimited.


Input Function

Returns characters (bytes) from an open sequential file.

Syntax

Input(number,[#]filenumber)

Elements

The Input function syntax has these parts:

Part	Description

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

filenumber	Any valid file number.

Remarks

Use this function only with files opened in Input or Binary mode.

Unlike the Input # statement, the Input function returns all of the characters it reads including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

Note   Another function (InputB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of specifying  the number of characters to return, number specifies the number of bytes.  In areas where DBCS is not used, InputB behaves the same as Input.


Line Input # Statement

Reads a line from an open sequential file and assigns it to a string variable.

Syntax

Line Input #filenumber,varname

Elements

The Line Input # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

varname	Valid string variable name.

Remarks

The Line Input # statement reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage return-linefeed sequence.  Carriage return-linefeed sequences are skipped rather than appended to the character string.


Loc Function

Returns the current read/write position within an open file.

Syntax

Loc(filenumber)

Elements

The filenumber named argument is any valid file number.

Remarks

The following describes the return value for each file access mode:

File Access	Return Value

Random	Number of the last record read from or written to the file.

Sequential	Current byte position in the file divided by 128.

Binary	Position of the last byte read or written.


Lock...Unlock Statements

Controls access by other processes to all or part of a file opened using the Open statement.

Syntax

Lock [#]filenumber[,recordrange]
. . .
Unlock [#]filenumber[,recordrange]

Elements

The Lock and Unlock statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recordrange	The range of records to lock or unlock.

The recordrange argument has the following syntax and parts:

recnumber | [start] To end

Part	Description

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.

start	Number of the first record or byte to lock or unlock.

end	Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs.  The arguments to Lock and Unlock must match exactly.

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on.  If you specify just one record, then only that record is locked or unlocked.  If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.

Caution   Be sure to remove all locks with an Unlock statement before closing a file or terminating your program.  Failure to remove locks produces unpredictable results.


LOF Function

Returns the size, in bytes, of a file opened using the Open statement.

Syntax

LOF(filenumber)

Elements

The filenumber named argument is any valid file number.

Remarks

To obtain the length of a file that is not open, use the FileLen function.


Open Statement

Enables input/output (I/O) to a file.

Syntax

Open pathname [For mode] [Access access] [lock] As [#]filenumber [Len=reclength]

Elements

The Open statement syntax has these parts:

Part	Description

pathname	String expression that specifies a file name [image] may include directory or folder, and drive.

mode	Keyword specifying the file mode: Append, Binary, Input, Output, or Random.

access	Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.

lock	Keyword specifying the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, Lock Read Write.

filenumber	A valid file number in the range 1 to 511, inclusive.  Use the FreeFile function to obtain the next available file number.

reclength	Number less than or equal to 32,767 (bytes).  For files opened for random access, this value is the record length.  For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it.  Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important   In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file.  In Append and Output modes, you must close a file before opening it with a different file number.

On the Macintosh, the file mode specified in the Open statement determines the initial Creator and Type property settings:

File mode	Creator 	Type

Output	????	TEXT

Append	????	TEXT

Random	????	OBIN

Binary	????	OBIN

Unspecified	????	OBIN


Print # Statement

Writes display-formatted data to a sequential file.

Syntax

Print #filenumber,[outputlist]

Elements

The Print # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

outputlist	Expression or list of expressions to print.

The outputlist argument has the following syntax and parts:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Part	Description

Spc(n)	Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)	Used to position the insertion point to an absolute column number, where n is the column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.

expression	Numeric or string expressions to print.

charpos	Specifies the insertion point for the next character.  Use a semicolon to specify the insertion point to be immediately after the last character displayed.  Use Tab(n) to position the insertion point to an absolute column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.  If charpos is omitted, the next character is printed on the next line.

Remarks

If you omit outputlist and include only a list separator after filenumber, a blank line prints to the file.  Multiple expressions can be separated with either a space or a semicolon.  A space has the same effect as a semicolon.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are output in the language appropriate for the international locale specified for your system.

For Boolean data, either True or False is printed.  The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written to the file using the standard short date format recognized by your system.  When either the date or the time component is missing or zero, only the provided part gets written to the file.

Nothing is written to the file if outputlist data is Empty.  However, if outputlist data is Null, Null is written to the file.  Again, the Null keyword is translated, as appropriate.

For error data, the output appears as Error errorcode.  The Error keyword is translated, as appropriate, when written to the file.

Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly.  If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file.

Note   If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file.  Using Write # ensures the integrity of each separate data field by properly delimiting it, so that it can be read back in using Input #.  Using Write # also ensures that it can be correctly read in any locale.


Put Statement

Writes from a variable to a disk file.

Syntax

Put [#]filenumber,[recnumber],varname

Elements

The Put statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which writing begins.

varname	Name of variable containing data to be written to disk.

Remarks

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on.  If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is written.  You must include delimiting commas, for example:

Put #4,,FileBuffer

For files opened in Random mode, the following rules apply:

•	If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put still writes subsequent records on record-length boundaries.  The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer.  Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written.

•	If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

•	If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then the variable.  For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

•	If the variable being written is a String Variant (VarType 8), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data.  The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

•	If the variable being written is any other type of variable (not a variable-length string and not a Variant), Put writes only the variable data.  The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.

•	Put writes elements of user-defined types as if each were written individually, except there is no padding between elements.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements.

For files opened in Binary mode, all of the Random rules apply except that:

•	The Len clause in the Open statement has no effect.  Put writes all variables to disk contiguously; that is, with no padding between records.

•	Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor.  The number of bytes written equals the number of characters in the string.  For example, the following statements write 10 bytes to file number 1:

VarString$ = String$(10," ")

Put #1,,VarString$


Reset Statement

Closes all disk files opened using the Open statement.

Syntax

Reset

Remarks

The Reset statement syntax closes all active files opened by the Open statement and writes the contents of all file buffers to disk.


Seek Function

Returns the current read/write position within a file opened using the Open statement.

Syntax

Seek(filenumber)

Elements

The filenumber named argument is any valid file number.

Remarks

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive.  For files open in Random mode, Seek returns the number of the next record read or written.  For files opened in Binary, Output, Append, or Input mode, Seek returns the byte position at which the next operation is to take place.  The first byte in a file is at position 1, the second byte is at position 2, and so on.


Seek Statement

Sets the position for the next read or write within a file opened using the Open statement.

Syntax

Seek [#]filenumber,position

Elements

The Seek statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

position	Number in the range 1 to 2,147,483,647, inclusive, that indicates where the next read or write should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning done by Seek.

Performing a file write after doing a Seek operation beyond the end of a file extends the file.  If you attempt a Seek operation to a negative or zero position, an error occurs.


Spc Function

Used with the Print # statement or the Print method to position output.

Syntax

Spc(n)

Elements

The n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output-line width, the next print position immediately follows the number of spaces printed.  If n is greater than the output-line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, the output-line width is 80 and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80).  If the difference between the current print position and the output-line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to n - (width - currentprintposition).

Note   Make sure your tabular columns are wide enough to accommodate wider letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.


Tab Function

Used with the Print # statement or the Print method to position output.

Syntax

Tab[(n)]

Elements

The n argument is the column number to tab to before displaying or printing the next expression in a list.  If omitted, Tab moves the cursor to the beginning of the next print zone.  This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line.  If n is less than 1, Tab moves the print position to column 1.  If n is greater than the output-line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80).  If n is less than the current print position, printing begins on the next line at the calculated print position.  If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1.  When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note   Make sure your tabular columns are wide enough to accommodate wider letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns.  The width of each column is an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.


Width # Statement

Assigns an output-line width to a file opened using the Open statement.

Syntax

Width #filenumber,width

Elements

The Width statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

width	Numeric expression in the range 0 to 255, inclusive, that indicates how many characters appear on a line before a new line is started.  If width equals 0, there is no limit to the length of a line.  The default value for width is 0.


Write # Statement

Writes raw data to a sequential file.

Syntax

Write #filenumber[,outputlist]

Elements

The Write statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

outputlist	One or more comma-delimited numeric or string expressions to write to a file.

Remarks

If you omit outputlist and include a comma after filenumber, a blank line prints to the file.  Multiple expressions can be separated with a space, a semicolon, or a comma.  A space has the same effect as a semicolon.

When Write # is used to output data to a file, several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

•	Numeric data is always output using the period (.) as the decimal separator.

•	For Boolean data, either #TRUE# or #FALSE# is printed.  The True and False keywords are not translated, regardless of locale.

•	Date data is written to the file using the universal date format.  When either the date or the time component is missing or zero, only the provided part gets written to the file.

•	Nothing is written to the file if outputlist data is Empty.  However, for Null data, #NULL# is output.

•	For error data, the output appears as #ERROR errorcode#.  The Error keyword is not translated, regardless of locale.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file.  You don't have to put explicit delimiters in the list.  Write # inserts a newline character (carriage return or carriage return-linefeed) after it has written the final character in outputlist to the file.


ChDir Statement

Changes the current directory or folder.

Syntax

ChDir path

Elements

The path named argument is a string expression that identifies which directory or folder becomes the new default directory or folder [image] may include drive.  If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks

In Microsoft Windows, the ChDir statement changes the default directory but not the default drive.  For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"

On the Macintosh, the default drive always changes to whatever drive is specified in path.


ChDrive Statement

Changes the current drive.

Syntax

ChDrive drive

Elements

The drive named argument is a string expression that specifies an existing drive.  If you supply a zero-length argument (""), the current drive doesn't change.  In Microsoft Windows, if the argument drive is a multiple-character string, ChDrive uses only the first letter.  On the Macintosh, ChDrive changes the current folder to the root folder of the specifed drive.


CurDir Function

Returns the current path.

Syntax

CurDir[(drive)]

Elements

The drive argument is a string expression that specifies an existing drive.  In Microsoft Windows, if no drive is specified or if drive is zero-length (""), CurDir returns the path for the current drive.  On the Macintosh, CurDir ignores any drive specified and simply returns the path for the current drive.


Dir Function

Returns the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

Syntax

Dir[(pathname[,attributes])]

Elements

The Dir function syntax has these parts:

Part	Description

pathname	String expression that specifies a file name [image] may include directory or folder, and drive.  Null is returned if pathname is not found.

attributes	Constant or numeric expression, the sum of which specifies file attributes.  If omitted, all normal files are returned that match pathname.

The attributes argument has these constants and values:

Constant	Value	File Attribute

vbNormal	0	Normal.

vbHidden	2	Hidden.

vbSystem	4	System [image] not available on the Macintosh.

vbVolume	8	Volume label; if specified, all attributes are ignored [image] not available on the Macintosh.

vbDirectory	16	Directory or folder.

Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

Dir supports the use of '*' (multiple character) and '?' (single character) wildcards to specify multiple files.  However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh does not support wildcards, use the file type to identify groups of files. You can use the MacID function to specify file type instead of using the file names.  For example, the following statement returns the name of the first "TEXT" file in the current folder:

Dir("", MacID("TEXT"))

If you use the MacID function with Dir in Microsoft Windows, an error occurs.

Any attribute value greater than 256 is considered a MacID value.

You must specify pathname the first time you call the Dir function, or an error occurs.  If you also specify file attributes, pathname must be included.

Dir returns the first file name that matches pathname.  To get any additional file names that match pathname, call Dir again with no arguments.  When no more file names match, Dir returns a zero-length string.  Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs.  You can change to a new pathname without retrieving all of the file names that match the current pathname.  However, you can't recursively call the Dir function.

Tip   Because file names are retrieved in no particular order, you may want to store returned file names in an array and then sort the array.


FileCopy Statement

Copies a file.

Syntax

FileCopy source, destination

Elements

The FileCopy statement syntax has these named argument parts:

Part	Description

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

destination	String expression that specifies the target file name [image] may include directory or folder, and drive.

Remarks

Open files can only be copied for read-only access.


FileDateTime Function

Returns a date that indicates the date and time when a file was created or last modified .

Syntax

FileDateTime(pathname)

Elements

The pathname named argument is a string expression that specifies a file name [image] may include directory or folder, and drive.


FileLen Function

Returns the length of a file in bytes.

Syntax

FileLen(pathname)

Elements

The pathname named argument is a string expression that specifies a file name [image] may include directory or folder, and drive.

Remarks

If the specified file is open when the FileLen function is called, the value returned represents the last saved disk size of the file.

To obtain the length of an open file, use the LOF function.


GetAttr Function

Returns a number representing the attributes of a file, directory or folder, or volume label.

Syntax

GetAttr(pathname)

Elements

The pathname named argument is a string expression that specifies a file name [image] may include directory or folder, and drive.

Return Values

The value returned by GetAttr is the sum of the following attribute values:

Value	Constant	File Attribute

0	vbNormal	Normal.

1	vbReadonly	Read-only.

2	vbHidden	Hidden.

4	vbSystem	System file [image] not available on the Macintosh.

8	vbVolume	Volume label [image] not available on the Macintosh.

16	vbDirectory	Directory or folder.

32	vbArchive	File has changed since last backup [image] not available on the Macintosh.

Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

To determine which attributes are set, use the And operator to perform a bit-wise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want.  If the result is not zero, that attribute is set for the named file.  For example, the return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive

A nonzero value is returned if the Archive attribute is set.


Kill Statement

Deletes files from a disk.

Syntax

Kill pathname

Elements

The pathname named argument is a string expression that specifies one or more file names to be deleted [image] may include directory or folder, and drive.

Remarks

Kill supports the use of '*' (multiple character) and '?' (single character) wildcards to specify multiple files.  However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh does not support wildcards, use the file type to identify groups of files to delete.  You can use the MacID function to specify file type instead of repeating the command with separate file names.  For example, the following statement deletes all 'TEXT' files in the current folder.

Kill MacID("TEXT")

If you use the MacID function with Kill in Microsoft Windows, an error occurs.

An error occurs if you try to use Kill to delete an open file.

To delete directories, use the RmDir statement.


MacID Function

Used only on the Macintosh to convert a four-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.

Syntax

MacID(constant)

Elements

The constant named argument consists of four-characters used to specify a resource type, file type, application signature, or Apple Event.  For example, TEXT, OBIN, MSWD (Microsoft Word), XCEL (Microsoft Excel), and so on.

Remarks

MacID is used with Dir and Kill to specify a Macintosh file type.  Since the Macintosh does not support '*' and '?' as wildcards, you can use a four-character constant instead to identify groups of files.  For example, the following statement returns 'TEXT' type files from the current folder:

Dir("", MacID("TEXT"))

MacID is used with Shell and AppActivate to specify an application using the application's unique signature.


MkDir Statement

Creates a new directory or folder.

Syntax

MkDir path

Elements

The path named argument is a string expression that identifies the directory or folder to be created [image] may include drive.  If no drive is specified, MkDir creates the new directory or folder on the current drive.

Remarks

In Microsoft Windows, if you use MkDir to create a directory whose name contains an embedded space, you may be able to access it with some applications, but you can't remove it using standard operating system commands.  To remove such a directory, use the RmDir statement.


Name Statement

Renames a disk file, directory, or folder.

Syntax

Name oldpathname As newpathname

Elements

The Name statement syntax has these parts:

Part	Description

oldpathname	String expression that specifies the existing file name and location [image] may include directory or folder, and drive.

newpathname	String expression that specifies the new file name and location [image] may include directory or folder, and drive.  The file specified by newpathname can't already exist.

Remarks

Both newpathname and oldpathname must be on the same drive.  If the path in newpathname exists and is different from the path in oldpathname, the Name statement moves the file to the new directory or folder and renames the file, if necessary.  If newpathname and oldpathname have different paths and the same file name, Name moves the file to the new location and leaves the file name unchanged.  Using Name, you can move a file from one directory or folder to another, but you can't move a directory or folder.

Name supports the use of '*' (multiple character) and '?' (single character) wildcards.  However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Using Name on an open file produces an error.  You must close an open file before renaming it.


RmDir Statement

Removes an existing directory or folder.

Syntax

RmDir path

Elements

The path named argument is a string expression that identifies the directory or folder to be removed [image] may include drive.  If no drive is specified, RmDir removes the directory or folder on the current drive.

Remarks

An error occurs if you try to use RmDir on a directory or folder containing files.  Use the Kill statement to delete all files before attempting to remove a directory or folder.


SetAttr Statement

Sets attribute information for a file.

Syntax

SetAttr pathname,attributes

Elements

The SetAttr statement syntax has these named-argument parts:

Part	Description

pathname	String expression that specifies a file name [image] may include directory or folder, and drive.

attributes	Constant or numeric expression, the sum of which specifies file attributes.

Constants and values for attributes are:

Constant	Value	File Attribute

vbNormal	0	Normal (default).

vbReadOnly	1	Read-only.

vbHidden	2	Hidden.

vbSystem	4	System [image] not available on the Macintosh.

vbArchive	32	File has changed since last backup [image] not available on the Macintosh.

Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

A run-time error occurs if you try to set the attributes of an open file.


ChDir Statement Example

This example uses the ChDir statement to change the current directory or folder.

' Change current directory or folder to "MYDIR".

ChDir "MYDIR"

' In Microsoft Windows.

' Assume "C:" is the current drive.  The following statement changes

' the default directory on drive "D:". "C:" remains the current drive.

ChDir "D:\WINDOWS\SYSTEM"

' On the Macintosh.

' Changes default folder and default drive.

ChDir "HD:MY FOLDER"


ChDrive Statement Example

This example uses the ChDrive statement to change the current drive.

' In Microsoft Windows.

ChDrive "D"	' Make "D" the current drive.

' On the Macintosh.

' Make "MY DRIVE" the current drive

ChDrive "MY DRIVE:"

' Make "MY DRIVE" the current drive and current folder since its the

' root.

ChDrive "MY DRIVE:MY FOLDER"


CurDir Function Example

This example uses the CurDir function to return the current path.

' In Microsoft Windows.

' Assume current path on C Drive is  "C:\WINDOWS\SYSTEM".

' Assume current path on D Drive is "D:\EXCEL".

' Assume C is the current drive.

MyPath = CurDir	' Returns "C:\WINDOWS\SYSTEM".

MyPath = CurDir("C")	' Returns "C:\WINDOWS\SYSTEM".

MyPath = CurDir("D")	' Returns "D:\EXCEL".

' On the Macintosh.

' Drive letters are ignored. Path for current drive is returned.

' Assume current path on HD Drive is  "HD:MY FOLDER".

' Assume HD is the current drive. Drive MD also exists on the machine.

MyPath = CurDir	' Returns "HD:MY FOLDER".

MyPath = CurDir("HD")	' Returns "HD:MY FOLDER".

MyPath = CurDir("MD")	' Returns "HD:MY FOLDER".


Dir Function Example

This example uses the Dir function to check if certain files and directories exist.  The MacID function may be used on the Macintosh to specify the file type.

' In Microsoft Windows.

' Returns "WIN.INI" if it exists.

MyFile = Dir("C:\WINDOWS\WIN.INI")

' Returns file name with specified extension. If more than one *.ini

' file exists, the first file name found is returned.

MyFile = Dir("C:\WINDOWS\*.ini")

' Call Dir again without arguments to return the next *.ini file in the

' same directory.

MyFile = Dir

' Return first *.txt file with a set hidden attribute.

MyFile = Dir("*.TXT", vbHidden)

' On the Macintosh.

' Use the MacID function to specify file type.

' The following statement returns the first "TEXT" file found in the

' specified directory or folder.

MyFile = Dir("HD:MyFolder:", MacID("TEXT"))


FileCopy Statement Example

This example uses the FileCopy statement to copy one file to another.  For purposes of this example, assume that SRCFILE is a file containing some data.

SourceFile = "SRCFILE"	' Define source file name.

DestinationFile = "DESTFILE"	' Define target file name.

FileCopy SourceFile, DestinationFile	' Copy source to target.


FileDateTime Function Example

This example uses the FileDateTime function to get the date and time when a file was created or last modified.  The format of the date and time displayed is based on the locale settings of your system.

' Assume TESTFILE was last modified on February 12 1993 at 4:35:47 PM.

' Assume United States/English locale settings.

MyStamp = FileDateTime("TESTFILE")	' Returns "2/12/93 4:35:47 PM".


FileLen Function Example

This example uses the FileLen function to return the length of a file in bytes.  For purposes of this example, assume that TESTFILE is a file containing some data.

MySize = FileLen("TESTFILE")	' Returns file length (bytes).


GetAttr Function Example

This example uses the GetAttr statement to determine the attributes of a file and directory or folder.

' Assume file TESTFILE has hidden attribute set.

MyAttr = GetAttr("TESTFILE")	' Returns 2.

' Assume file TESTFILE has hidden and read-only attributes set.

MyAttr = GetAttr("TESTFILE")	' Returns 3.

' Assume MYDIR is a directory or folder.

MyAttr = GetAttr("MYDIR")	' Returns 16.


Kill Statement Example

This example uses the Kill statement to delete a file from a disk.  Since the Macintosh does not support wildcards, you can use the MacID function to specify the file type instead of the file name.

' Assume TESTFILE is a file containing some data.

Kill "TestFile"	' Delete file.

' In Microsoft Windows.

' Delete all *.txt files in current directory.

Kill "*.txt"

' On the Macintosh.

' Use the MacID function to delete all PICT files in current folder

Kill MacID("PICT")


MacID Function Example

This example shows various uses of the MacID function.  The MacID function is not available in Microsoft Windows.

' Return the first text file in folder HD:My Folder.

FileName = Dir("HD:My Folder:", MacID("TEXT"))

' Deletes all "TEXT" files in the current folder.

Kill MacID("TEXT")

' Run Microsoft Excel.

ReturnValue = Shell(MacID("XCEL"))

' Activate Microsoft Word.

AppActivate MacID("MSWD")


MkDir Statement Example

This example uses the MkDir statement to create a directory or folder.  If the drive is not specified, the new directory or folder is created on the current drive.

MkDir "MYDIR"	' Make new directory or folder.


Name Statement Example

This example uses the Name statement to rename a file.  For purposes of this example, assume that the directories or folders that are specified already exist.

OldName = "OLDFILE" : NewName = "NEWFILE"	' Define file names.

Name OldName As NewName	' Rename file.

' In Microsoft Windows.

OldName = "C:\MYDIR\OLDFILE" : NewName = "C:\YOURDIR\NEWFILE"

Name OldName As NewName	' Move and rename file.

' On the Macintosh.

OldName = "HD:MY FOLDER:OLDFILE" : NewName = "HD:YOUR FOLDER:NEWFILE"

Name OldName As NewName	' Move and rename file.


RmDir Statement Example

This example uses the RmDir statement to remove an existing directory or folder.

' Assume that MYDIR is an empty directory or folder.

RmDir "MYDIR"	' Remove MYDIR.


SetAttr Statement Example

This example uses the SetAttr statement to set attributes for a file.

SetAttr "TESTFILE", vbHidden	' Set hidden attribute.

SetAttr "TESTFILE", vbHidden + vbReadOnly	' Set hidden and Read-only

' attributes.


Close Statement Example

This example uses the Close statement to close all three files opened for Output.

For I = 1 To 3	' Loop 3 times.

FileName = "TEST" & I	' Create file name.

Open FileName For Output As #I	' Open file.

Print #I, "This is a test."	' Write string to file.

Next I

Close	' Close all 3 open files.


EOF Function Example

This example uses the EOF function to detect the end of a file.  For purposes of this example, assume that MyFile is a text file with a few lines of text.

Open "MyFile" For Input As #1	' Open file for input.

Do While Not EOF(1)	' Check for end of file.

Line Input #1, InputData	' Read line of data.

Debug.Print InputData	' Print to Debug window.

Loop

Close #1	' Close file.


FileAttr Function Example

This example uses the FileAttr function to return the file mode and file handle of an open file.

FileNum = 1	' Assign file number.

Open "TESTFILE" For Append As FileNum	' Open file.

Handle = FileAttr(FileNum, 1)	' Returns 8 (Append file mode).

Mode = FileAttr(FileNum, 2)	' Returns file handle.

Close FileNum	' Close file.


FreeFile Function Example

This example uses the FreeFile function to return the next available file number.  Five files are opened for output within the loop and some sample data is written to each.

For MyIndex = 1 to 5	' Loop 5 times.

FileNumber = FreeFile	' Get unused file

' number.

Open "TEST" & MyIndex For Output As #FileNumber	' Create file name.

Write #FileNumber, "This is a sample"	' Output text.

Close #FileNumber	' Close file.

Next MyIndex


Get Statement Example

This example uses the Get statement to read data from a disk file into a variable.  For purposes of this example, assume that TESTFILE is a file containing five records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open sample file for random access.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

' Read the sample file using the Get statement.

Position = 3	' Define record number.

Get #1, Position, MyRecord	' Read third record.

Close #1	' Close file.


Input # Statement Example

This example uses the Input # statement to read data from a file into two variables.  For purposes of this example, assume that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).

Open "TESTFILE" For Input As #1	' Open file for input.

Do While Not EOF(1)	' Loop until end of file.

Input #1, MyString, MyNumber	' Read data into variables.

Debug.Print MyString, MyNumber	' Print data to Debug window.

Loop

Close #1	' Close file.


Input Function Example

This example uses the Input function to read one character at a time from a file and print it to the Debug window.  For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1	' Open file.

Do While Not EOF(1)	' Loop until end of file.

MyChar = Input(1, #1)	' Get one character.

Debug.Print MyChar	' Print to Debug window.

Loop

Close #1	' Close file.


Line Input # Statement Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable.  For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1	' Open file.

Do While Not EOF(1)	' Loop until end of file.

Line Input #1, TextLine	' Read line into variable.

Debug.Print TextLine	' Print to Debug window.

Loop

Close #1	' Close file.


Loc Function Example

This example uses the Loc function to return the current read/write position within an open file.  For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1	' Open file just created.

Do While Not EOF(1)	' Loop until end of file.

Line Input #1, MyLine	' Read line into variable.

MyLocation = Loc(1)	' Get current position within file.

' Print to Debug window.

Debug.Print MyLine; Tab; MyLocation

Loop


Lock, Unlock Statements Example

This example illustrates the use of the Lock and Unlock statements.  While a record is being modified, access by other processes to the record is denied.  For purposes of this example, assume that TESTFILE is a file containing five records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open sample file for random access.

Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord)

RecordNumber = 4	' Define record number.

Lock #1, RecordNumber	' Lock record.

Get #1, RecordNumber, MyRecord	' Read record.

MyRecord.ID = 234	' Modify record.

MyRecord.Name = "John Smith"

Put #1, RecordNumber, MyRecord	' Write modified record.

Unlock #1, RecordNumber	' Unlock current record.

Close #1	' Close file.


LOF Function Example

This example uses the LOF function to determine the size of an open disk file.  For purposes of this example, assume that TESTFILE is a text file containing sample data.

Open "TESTFILE" For Input As #1	' Open file.

FileLength = LOF(1)	' Get length of file.

Close #1	' Close file.


Open Statement Example

This example illustrates various uses of the Open statement to enable input/output to a file.

' Open in sequential-input mode.

Open "TESTFILE" For Input As #1

' Open in binary-file mode for writing operations only.

Open "TESTFILE" For Binary Access Write As #1

' Open file in random-access mode. The file contains records of the

' user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

' Open for sequential output; any process can read/write to file.

Open "TESTFILE" For Output Shared As #1

' Open in binary-file mode for reading; other processes can't read

' file.

Open "TESTFILE" For Binary Access Read Lock Read As #1


Print # Statement Example

This example uses the Print # statement to write data to a file.

Open "TESTFILE" For Output As #1	' Open file for output.

Print #1, "This is a test"	' Print text to file.

Print #1,	' Print blank line to file.

Print #1, "Zone 1"; Tab ; "Zone 2"	' Print in two print zones.

Print #1, "Hello" ; " " ; "World"	' Separate strings with space.

Print #1, Spc(5) ; "5 leading spaces "	' Print 5 leading spaces.

Print #1, Tab(10) ; "Hello"	' Print word at col 10.

' Assign Boolean, Date, Null and Error values.

MyBool = False : MyDate = #February 12, 1969# : MyNull = Null

MyError = CVErr(32767)

' True, False, Null and Error are translated using locale settings of

' your system. Date literals are written using standard short date

' format.

Print #1, MyBool ; " is a Boolean value"

Print #1, MyDate ; " is a date"

Print #1, MyNull ; " is a null value"

Print #1, MyError ; " is an error value"

Close #1	' Close file.


Put Statement Example

This example uses the Put statement to write data to a disk file.  Five records of the user-defined type Record are written to the file.

' Define user-defined type.

Type Record

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open file for random access.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

For RecordNumber = 1 To 5	' Loop 5 times.

MyRecord.ID = RecordNumber	' Define ID.

MyRecord.Name = "My Name" & RecordNumber	' Create a string.

Put #1, RecordNumber, MyRecord	' Write record to file.

Next RecordNumber

Close #1	' Close file.


Reset Statement Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk.

For FileNumber = 1 To 5	' Loop 5 times.

' Open file for output.

Open "TEST" & FileNumber For Output As #FileNumber

Write #FileNumber, "Hello World"	' Write data to file.

Next FileNumber

Reset	' Close files and write contents

' to disk.


Seek Function Example

This example uses the Seek function to return the current file position.

' For files opened in random-file mode, Seek returns number of next

' record.  Assume TESTFILE is a file containing records of the

' user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open file in random-file mode.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

Do While Not EOF(1)	' Loop until end of file.

Get #1, , MyRecord	' Read next record.

Debug.Print Seek(1)	' Print record number to Debug

' window.

Loop

Close #1	' Close file.

' For files opened in modes other than random mode, Seek returns the

' byte position at which the next operation will take place. Assume

' TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1	' Open file for reading.

Do While Not EOF(1)	' Loop until end of file.

MyChar = Input(1,#1)	' Read next character of data.

Debug.Print Seek(1)	' Print byte position to Debug

' window.

Loop

Close #1	' Close file.


Seek Statement Example

This example uses the Seek statement to set the position for the next read or write within a file.

' For files opened in random-file mode, Seek sets the next

' record. Assume TESTFILE is a file containing records of the

' user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open file in random-file mode.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

MaxSize = LOF(1) \ Len(MyRecord)	' Get number of records in file.

' The loop reads all records starting from the last.

For RecordNumber = MaxSize To 1 Step - 1

Seek #1, RecordNumber	' Set position.

Get #1, , MyRecord	' Read record.

Next RecordNumber

Close #1	' Close file.

' For files opened in modes other than random mode, Seek sets the

' byte position at which the next operation will take place. Assume

' TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1	' Open file for input.

MaxSize = LOF(1)	' Get size of file in bytes.

' The loop reads all characters starting from the last.

For NextChar = MaxSize To 1 Step -1

Seek #1, NextChar	' Set position.

MyChar = Input(1,#1)	' Read character.

Next NextChar

Close #1	' Close file.


Spc Function Example

This example uses the Spc function to position output in a file and in the Debug window.

' The Spc function can be used with the Print # statement.

Open "TESTFILE" For Output As #1	' Open file for output.

Print #1, "10 spaces between here"; Spc(10); "and here."

Close #1	' Close file.

' The following statement causes the text to be printed in the Debug

' window, preceded by 30 spaces.

Debug.Print Spc(30); "Thirty spaces later..."


Tab Function Example

This example uses the Tab function to position output in a file or in the Debug window.

' The Tab function can be used with the Print # statement.

Open "TESTFILE" For Output As #1	' Open file for output.

' The second word prints at column 20.

Print #1, "Hello"; Tab(20); "World."

' If the argument is omitted, cursor is moved to the next print zone.

Print #1, "Hello"; Tab ; "World"

Close #1	' Close file.

' The Tab function can also be used with the Print method.

' The following statement prints text starting at column 10.

Debug.Print Tab(10); "10 columns from start."


Width # Statement Example

This example uses the Width statement to set the output-line width for a file.

Open "TESTFILE" For Output As #1	' Open file for output.

Width #1, 5	' Set output-line width to 5.

For I = 0 To 9	' Loop 10 times.

Print #1, Chr(48 + I);	' This prints 5 characters per line.

Next I

Close #1	' Close file.


Write # Statement Example

This example uses the Write # statement to write raw data to a sequential file.

Open "TESTFILE" For Output As 1	' Open file for output.

Write #1, "Hello World", 234	' Written data is comma delimited.

Write #1,	' Write blank line.

' Assign Boolean, Date, Null and Error values.

MyBool = False : MyDate = #February 12, 1969# : MyNull = Null

MyError = CVErr(32767)

' Boolean data is written as #TRUE# or #FALSE#. Date literals are

' written in universal date format. Null data is written as #NULL#.

' Error data is written as #ERROR errorcode#.

Write #1, MyBool ; " is a Boolean value"

Write #1, MyDate ; " is a date"

Write #1, MyNull ; " is a null value"

Write #1, MyError ; " is an error value"

Close #1	' Close file.


IsArray Function

Returns a value indicating whether a variable is an array.

Syntax

IsArray(varname)

Elements

The varname named argument can be any variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False.


IsDate Function

Returns a value indicating whether an expression can be converted to a date.

Syntax

IsDate(expression)

Elements

The expression named argument can be any date or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or can legally be converted to a date; otherwise, it returns False.  The range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.


IsEmpty Function

Returns a value indicating whether a variable has been initialized.

Syntax

IsEmpty(expression)

Elements

The expression named argument can be any numeric or string expression.  However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is Empty; otherwise, it returns False.  False is always returned if expression contains more than one variable.


IsError Function

Returns a value indicating whether an expression is an error value.

Syntax

IsError(expression)

Elements

The expression named argument can be any numeric expression used to indicate an error value.

Remarks

Error values are created by converting real numbers to error values using the CVErr function.  The IsError function is used to determine if a numeric expression represents an error.  IsError returns True if the expression argument indicates an error; otherwise, it returns False.


IsMissing Function

Returns a value indicating whether an optional argument has been passed to a procedure.

Syntax

IsMissing(argname)

Elements

The argname named argument is the name of an optional procedure argument.

Remarks

The IsMissing function is used in a procedure that has optional arguments, including ParamArray arguments, to determine whether an argument has been passed to the procedure.  IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False.


IsNull Function

Returns a value that indicates whether an expression contains no valid data (Null).

Syntax

IsNull(expression)

Elements

The expression named argument can be any numeric or string expression.

Remarks

IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False.  If expression consists of more than one variable, Null in any variable causes True to be returned for the entire expression.

The Null value indicates that the Variant contains no valid data.  Null is not the same as Empty, which indicates that a variable has not yet been initialized.  It is also not the same as a zero-length string, which is sometimes referred to as a null string.

Important   Use the IsNull function to determine whether an expression contains a Null value.  Expressions that you might expect to evaluate True under some circumstances, such as If Var = Null and If Var <> Null, are always False.  This is because any expression containing a Null is itself Null and therefore False.


IsNumeric Function

Returns a value indicating whether an expression can be evaluated as a number.

Syntax

IsNumeric(expression)

Elements

The expression named argument can be any numeric or string expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

IsNumeric returns False if expression is a date expression.


IsObject Function

Returns a value indicating whether an expression references a valid OLE Automation object.

Syntax

IsObject(expression)

Elements

The expression named argument can be any expression.

Remarks

IsObject returns True if expression is a valid reference to an actual object; otherwise, it returns False.


TypeName Function

Returns a string that provides information about a variable.

Syntax

TypeName(varname)

Elements

The varname named argument can be any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String Returned	Variable contains
objecttype	An OLE Automation object whose type is objecttype.
Integer	An integer.
Long	A long integer.
Single	A single-precision floating point number.
Double	A double-precision floating point number.
Currency	A currency value.
Date	A date.
String	A string.
Boolean	A Boolean value.
Error	An error value.
Empty	Uninitialized.
Null	No valid data.
Object	An object that doesn't support OLE Automation.
Unknown	An OLE Automation object whose type is unknown.
Nothing	An object variable that doesn't refer to an object.
If varname is an array, the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended.  For example, if varname is an array of integers, TypeName returns "Integer()".


VarType Function

Returns a value indicating the subtype of a variable.

Syntax

VarType(varname)

Elements

The varname named argument can be any variable except a variable of a user-defined type.

Return Values

Value Returned	Constant	Variable Type
0	vbEmpty	Empty (uninitialized).
1	vbNull	Null (no valid data).
2	vbInteger	Integer.
3	vbLong	Long integer.
4	vbSingle	Single-precision floating point number.
5	vbDouble	Double-precision floating point number.
6	vbCurrency	Currency.
7	vbDate	Date.
8	vbString	String.
9	vbObject	OLE Automation object.
10	vbError	Error.
11	vbBoolean	Boolean.
12	vbVariant	Variant (used only with arrays of Variants).
13	vbDataobject	Non-OLE Automation object.
8192	vbArray	Array.
Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

The VarType function never returns the value for vbArray by itself.  It is always added to some other value to indicate an array of a particular type.  The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant.  For example, the value returned for an array of integers is calculated as vbInteger + vbArray, or 8194.


IsArray Function Example

This example uses the IsArray function to check if a variable is an array.

Dim MyArray(1 To 5) As Integer	' Declare array variable.

YourArray = Array(1, 2, 3)	' Use Array function.

MyCheck = IsArray(MyArray)	' Returns True.

MyCheck = IsArray(YourArray)	' Returns True.


IsDate Function Example

This example uses the IsDate function to determine if an expression can be converted to a date.

MyDate = "February 12, 1969" : YourDate = #2/12/69# : NoDate = "Hello"

MyCheck = IsDate(MyDate)	' Returns True.

MyCheck = IsDate(YourDate)	' Returns True.

MyCheck = IsDate(NoDate)	' Returns False.


IsEmpty Function Example

This example uses the IsEmpty function to determine whether or not a variable has been initialized.

MyCheck = IsEmpty(MyVar)	' Returns True.

MyVar = Null	' Assign Null.

MyCheck = IsEmpty(MyVar)	' Returns False.

MyVar = Empty	' Assign Empty.

MyCheck = IsEmpty(MyVar)	' Returns True.


IsError Function Example

This example uses the IsError function to check if a numeric expression is an error value.  The CVErr function is used to return an Error Variant from a user-defined function.

' Assume UserFunction is a user-defined function procedure that returns

' an error value; e.g., return value assigned with the statement

' UserFunction = CVErr(32767) where 32767 is a user-defined number.

ReturnVal = UserFunction()

MyCheck = IsError(ReturnVal)	' Returns True.


IsMissing Function Example

This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure.

' The following statements call the user-defined function procedure.

ReturnValue = ReturnTwice()	' Returns Null.

ReturnValue = ReturnTwice(2)	' Returns 4.

' Function procedure definition.

Function ReturnTwice(Optional A)

If IsMissing(A) Then

' If argument is missing, return a Null.

ReturnTwice = Null

Else

' If argument is present, return twice the value.

ReturnTwice = A * 2

End If

End Function


IsNull Function Example

This example uses the IsNull function to determine if a variable contains a Null.

MyCheck = IsNull(MyVar)	' Returns False.

MyVar = ""

MyCheck = IsNull(MyVar)	' Returns False.

MyVar = Null

MyCheck = IsNull(MyVar)	' Returns True.


IsNumeric Function Example

This example uses the IsNumeric function to determine if a variable can be evaluated as a number.

MyVar = "53"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns True.

MyVar = "459.95"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns True.

MyVar = "45 Help"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns False.


IsObject Function Example

This example uses the IsObject function to determine if a variable references a valid object.  MyObject and YourObject are object variables of the same type.  They are generic names used here for illustration purposes only.

Dim MyInt As Integer	' Declare variable.

Set YourObject = MyObject	' Assign an object reference.

MyCheck = IsObject(YourObject)	' Returns True.

MyCheck = IsObject(MyInt)	' Returns False.


TypeName Function Example

This example uses the TypeName function to return information about a variable.

' Declare variables.

Dim StrVar As String, IntVar As Integer, CurVar As Currency

Dim ArrayVar (1 To 5) As Integer

NullVar = Null	' Assign Null value.

MyType = TypeName(StrVar)	' Returns "String".

MyType = TypeName(IntVar)	' Returns "Integer".

MyType = TypeName(CurVar)	' Returns "Currency".

MyType = TypeName(NullVar)	' Returns "Null".

MyType = TypeName(ArrayVar)	' Returns "Integer()".


VarType Function Example

This example uses VarType to determine the subtype of a variable.

' Initialize variables.

IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69#

MyCheck = VarType(IntVar)	' Returns 2.

MyCheck = VarType(DateVar)	' Returns 7.

MyCheck = VarType(StrVar)	' Returns 8.


As <keyword>
As

The As keyword is used in these contexts:

Const Statement

Declare Statement

Dim Statement

Function Statement

Name Statement

Open Statement

Private Statement

Public Statement

ReDim Statement

Static Statement

Sub Statement

Type Statement


Binary <keyword>
Binary

The Binary keyword is used in these contexts:

Open Statement

Option Compare Statement


ByRef <keyword>
ByRef

The ByRef keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ByVal <keyword>
ByVal

The ByVal keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Date <keyword>
Date

The Date keyword is used in these contexts:

Date Data Type

Date Function

Date Statement


Else <keyword>
Else

The Else keyword is used in these contexts:

If...Then...Else Statement

Select Case Statement


Empty <keyword>
Empty

A Variant subtype indicating an uninitialized variable value.


Err <keyword>
Err

The Err keyword is used in these contexts:

Err Function

Err Statement


Error <keyword>
Error

The Error keyword is used in these contexts:

Error Function

Error Statement

On Error Statement


False <keyword>
False

A restricted keyword whose value is equal to 0.


For <keyword>
For

The For keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

Open Statement


Get <keyword>
Get

The Get keyword is used in these contexts:

Get Statement

Property Get Statement


Input <keyword>
Input

The Input keyword is used in these contexts:

Input Function

Input # Statement

Line Input # Statement


Is <keyword>
Is

The Is keyword is used in these contexts:

Is Operator

Select Case Statement


Let <keyword>
Let

The Let keyword is used in these contexts:

Property Let Statement

Let Statement


Lock <keyword>
Lock

The Lock keyword is used in these contexts:

Lock...Unlock Statement

Open Statement


Mid <keyword>
Mid

The Mid keyword is used in these contexts:

Mid Function

Mid Statement


Next <keyword>
Next

The Next keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

On Error Statement

Resume Statement


Null <keyword>
Null

A Variant subtype indicating that a variable contains no valid data.


On <keyword>
On

The On keyword is used in these contexts:

On Error Statement

On...GoSub Statement

On...GoTo Statement


Option <keyword>
Option

The Option keyword is used in these contexts:

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement


Optional <keyword>
Optional

The Optional keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ParamArray <keyword>
ParamArray

The ParamArray keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Print <keyword>
Print

The Print keyword is used in these contexts:

Print Method

Print # Statement


Private <keyword>
Private

The Private keyword is used in these contexts:

Const Statement

Declare Statement

Function Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement

Type Statement


Property <keyword>
Property

The Property keyword is used in these contexts:

Property Get Statement

Property Let Statement

Property Set Statement


Public <keyword>
Public

The Public keyword is used in these contexts:

Const Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Sub Statement

Type Statement


Resume <keyword>
Resume

The Resume keyword is used in these contexts:

On Error Statement

Resume Statement


Seek <keyword>
Seek

The Seek keyword is used in these contexts:

Seek Function

Seek Statement


Set <keyword>
Set

The Set keyword is used in these contexts:

Set Statement

Property Set Statement


Static <keyword>
Static

The Static keyword is used in these contexts:

Function Statement

Static Statement

Sub Statement


Step <keyword>
Step

The Step keyword is used in these contexts:

For Each...Next Statement

For...Next Statement


String <keyword>
String

The String keyword is used in these contexts:

String Data Type

String Function


To <keyword>
To

The To keyword is used in these contexts:

Dim Statement

For...Next Statement

Lock, Unlock Statements

Private Statement

Public Statement

ReDim Statement

Select Case Statement

Static Statement


Time <keyword>
Time

The Time keyword is used in these contexts:

Time Function

Time Statement


True <keyword>
True

A restricted keyword whose value is equal to -1.


Math Functions

Abs Function

Atn Function

Cos Function

Exp Function

Fix Function

Int Function

Log Function

Rnd Function

Sgn Function

Sin Function

Sqr Function

Tan Function

Derived Math Functions


Abs Function

Returns the absolute value of a number.

Syntax

Abs(number)

Elements

The number argument can be any valid numeric expression.  If number contains no valid data, Null is returned; if it is an uninitialized variable, Empty is returned.

Remarks

The absolute value of a number is its unsigned magnitude.  For example, ABS(-1) and ABS(1) both return 1.


Atn Function

Returns the arctangent of a number.

Syntax

Atn(number)

Elements

The number named argument can be any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians.  The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

The range of the result is -pi/2 to pi/2 radians.

To convert degrees to radians, multiply degrees by pi/180.  To convert radians to degrees, multiply radians by 180/pi.

Note   Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle.  Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent).


Cos Function

Returns the cosine of an angle.

Syntax

Cos(number)

Elements

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle.  The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180.  To convert radians to degrees, multiply radians by 180/pi.


Exp Function

Returns e (the base of natural logarithms) raised to a power.

Syntax

Exp(number)

Elements

The number named argument can be any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs.  The constant e is approximately 2.718282.

Note   The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.


Int Function, Fix Function

Returns the integer portion of a number.

Syntax

Int(number)
Fix(number)

Elements

The number argument can be any valid numeric expression.  If number contains no valid data, Null is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.

The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number.  For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

Fix(number) is equivalent to:

Sgn(number) * Int(Abs(number))


Log Function

Returns the natural logarithm of a number.

Syntax

Log(number)

Elements

The number named argument can be any valid numeric expression greater than 0.

Remarks

The natural logarithm is the logarithm to the base e.  The constant e is approximately 2.718282.

You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:

Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

Static Function Log10(X)

Log10 = Log(X) / Log(10#)

End Function


Randomize Statement

Initializes the random-number generator.

Syntax

Randomize [number]

Elements

The number named argument can be any valid numeric expression.

Remarks

Randomize uses number to initialize a random-number generator, giving it a new seed value.  If you omit number, the value returned by the Timer function is used as the new seed value.

If Randomize is not used, the same initial seed is always used to start the sequence.

Use the Randomize statement without an argument to provide a random seed based on the system timer to initialize the random-number generator before Rnd is called.


Rnd Function

Returns a random number.

Syntax

Rnd[(number)]

Elements

The number named argument can be any valid numeric expression.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to 0.

The value of number determines how Rnd generates a random number:

If number is:	Rnd generates:

Less than zero	The same number every time, using number as the seed.

Greater than zero	The next random number in the sequence.

Equal to zero	The most recently generated number.

Not supplied	The next random number in the sequence.

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Use the Randomize statement without an argument to provide a random seed based on the system timer to initialize the random-number generator before Rnd is called.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.


Sgn Function

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

Elements

The number argument can be any valid numeric expression.

Return Values

If number is	Sgn returns

Greater than zero	1

Equal to zero	0

Less than zero	-1

Remarks

The sign of the number argument determines the return value of the Sgn function.


Sin Function

Returns the sine of an angle.

Syntax

Sin(number)

Elements

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180.  To convert radians to degrees, multiply radians by 180/pi.


Sqr Function

Returns the square root of a number.

Syntax

Sqr(number)

Elements

The number named argument can be any valid numeric expression greater than or equal to 0.


Tan Function

Returns the tangent of an angle.

Syntax

Tan(number)

Elements

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite an angle divided by the length of the side adjacent to the angle.

To convert degrees to radians, multiply degrees by pi/180.  To convert radians to degrees, multiply radians by 180/pi.


Derived Math Functions

The following is a list of nonintrinsic math functions that can be derived from the intrinsic math functions:

Function	Derived equivalents

Secant	Sec(X) = 1 / Cos(X)

Cosecant	Cosec(X) = 1 / Sin(X)

Cotangent	Cotan((X) = 1 / Tan(X)

Inverse Sine	Arcsin(X) = Atn(X / Sqr(-X * X + 1))

Inverse Cosine	Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 1.5708

Inverse Secant	Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * 1.5708

Inverse Cosecant	Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * 1.5708

Inverse Cotangent	Arccotan(X) = Atn(X) + 1.5708

Hyperbolic Sine	HSin(X) = (Exp(X) - Exp(-X)) / 2

Hyperbolic Cosine	HCos(X) = (Exp(X) + Exp(-X)) / 2

Hyperbolic Tangent	HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))

Hyperbolic Secant	HSec(X) = 2 / (Exp(X) + Exp(-X))

Hyperbolic Cosecant	HCosec(X) = 2 / (Exp(X) - Exp(-X))

Hyperbolic Cotangent	HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))

Inverse Hyperbolic Sine	HArcsin(X) = Log(X + Sqr(X * X + 1))

Inverse Hyperbolic Cosine	HArccos(X) = Log(X + Sqr(X * X - 1))

Inverse Hyperbolic Tangent	HArctan(X) = Log((1 + X) / (1 - X)) / 2

Inverse Hyperbolic Secant	HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

Inverse Hyperbolic Cosecant	HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)

Inverse Hyperbolic Cotangent	HArccotan(X) = Log((X + 1) / (X - 1)) / 2

Logarithm to base N	LogN(X) = Log(X) / Log(N)


Abs Function Example

This example uses the Abs function to compute the absolute value of a number.

MyNumber = Abs(50.3)	' Returns 50.3.

MyNumber = Abs(-50.3)	' Returns 50.3.


Atn Example
Atn Function Example

This example uses the Atn function to return the arctangent of a number.

Pi = 4 * Atn(1)	' Calculate the value of pi.


Cos Function Example

This example uses the Cos function to return the cosine of an angle.

MyAngle = 1.3	' Define angle in radians.

MySecant = 1 / Cos(MyAngle)	' Calculate secant.


Exp Function Example

This example uses the Exp function to return e raised to a power.

' Define angle in radians.

MyAngle = 1.3

' Calculate hyperbolic sine.

MyHSin = (Exp(MyAngle) - Exp(- 1 * MyAngle)) / 2


Int Function, Fix Function Example

This example illustrates how the Int and Fix functions return integer portions of numbers.  In the case of a negative number argument, the Int function returns the the first negative integer less than or equal to the number; whereas, the Fix function returns the first negative integer greater than or equal to the number.

MyNumber = Int(99.8)	' Returns 99.

MyNumber = Fix(99.2)	' Returns 99.

MyNumber = Int(-99.8)	' Returns -100.

MyNumber = Fix(-99.8)	' Returns -99.

MyNumber = Int(-99.2)	' Returns -100.

MyNumber = Fix(-99.2)	' Returns -99.


Log Function Example

This example uses the Log function to return the natural logarithm of a number.

' Define angle in radians.

MyAngle = 1.3

' Calculate inverse hyperbolic sine.

MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1))


Randomize Statement Example

This example uses the Randomize statement to initialize the random-number generator.  Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

' Initialize random-number generator.

Randomize

' Generate random value between 1 and 6.

MyAngle = Int((6 * Rnd) + 1)


Rnd Function Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

MyValue = Int((6 * Rnd) + 1)	' Generate random value between 1 and 6.


Sgn Function Example

This example uses the Sgn function to determine the sign of a number.

MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0

MySign = Sgn(MyVar1)	' Returns 1.

MySign = Sgn(MyVar2)	' Returns -1.

MySign = Sgn(MyVar3)	' Returns 0.


Sin Function Example

This example uses the Sin function to return the sine of an angle.

MyAngle = 1.3	' Define angle in radians.

MyCosecant = 1 / Sin(MyAngle)	' Calculate cosecant.


Sqr Function Example

This example uses the Sqr function to calculate the square root of a number.

MySqr = Sqr(4)	' Returns 2.

MySqr = Sqr(23)	' Returns 4.795832.

MySqr = Sqr(0)	' Returns 0.

MySqr = Sqr(-4)	' Generates run-time error.


Tan Function Example

This example uses the Tan function to return the tangent of an angle.

MyAngle = 1.3	' Define angle in radians.

MyCotangent = 1 / Tan(MyAngle)	' Calculate cotangent.


Character Set (0 - 127)

 0	•	 32	[space] 	 64	@	 96	`

 1	•	 33	!	 65	A	 97	a

 2	•	 34	"	 66	B	 98	b

 3	•	 35	#	 67	C	 99	c

 4	•	 36	$	 68	D	 100	d

 5	•	 37	%	 69	E	 101	e

 6	•	 38	&	 70	F	 102	f

 7	•	 39	'	 71	G	 103	g

 8	* *	 40	(	 72	H	 104	h

 9	* *	 41	)	 73	I	 105	i

 10	* *	 42	*	 74	J	 106	j

 11	•	 43	+	 75	K	 107	k

 12	•	 44	,	 76	L	 108	l

 13	* *	 45	-	 77	M	 109	m

 14	•	 46	.	 78	N	 110	n

 15	•	 47	/	 79	O	 111	o

 16	•	 48	0	 80	P	 112	p

 17	•	 49	1	 81	Q	 113	q

 18	•	 50	2	 82	R	 114	r

 19	•	 51	3	 83	S	 115	s

 20	•	 52	4	 84	T	 116	t

 21	•	 53	5	 85	U	 117	u

 22	•	 54	6	 86	V	 118	v

 23	•	 55	7	 87	W	 119	w

 24	•	 56	8	 88	X	 120	x

 25	•	 57	9	 89	Y	 121	y

 26	•	 58	:	 90	Z	 122	z

 27	•	 59	;	 91	[	 123	{

 28	•	 60	<	 92	\	 124	|

 29	•	 61	=	 93	]	 125	}

 30	•	 62	>	 94	^	 126	~

 31	•	 63	?	 95	_	 127	•

* *	Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return characters, respectively.  They have no graphical representation but, depending on the application, may affect the visual display of text.

•	These characters aren't supported by Microsoft Windows.


Restricted Keywords

The following keywords are restricted:

Abs	And	Any	As

B*	BF*	Boolean	ByRef

ByVal	Call	Case	CBool

CCur	CDate	CDbl	CDecl

CInt	Circle*	CLng	Close

Const	Command*	CSng	CStr

CurDir	Currency	CVar	CVDate

CVErr	Date	Debug	Declare

DefBool	DefCur	DefDate	DefDbl

DefInt	DefLng	DefObj	DefSng

DefStr	DefVar	Dim	Dir

Do	Double	Each	Else

ElseIf	Empty	End	EndIf

Environ*	Eqv	Erase	Error

Exit	F*	False	Fix

For	Format	FreeFile	Function

Get	Global*	Go	GoSub

GoTo	If	Imp	In

Input	InputB	Instr	InstrB

Int	Integer	Is	LBound

Len	LenB	Let	Like

Line*	Load*	LoadPicture*	Local*

Lock	Long	Loop	LSet

Me*	Mid	MidB	Mod

Name	New*	Next	Not

Nothing	Null	Object	On

Open	Option	Optional	Or

ParamArray	Point*	Preserve	Print

Private	Property	PSet*	Public

Put	QBColor*	ReDim	Rem

Resume	Return	RSet	Scale*

SavePicture*	Seek	Select	Set

Sgn	Shared	Single	Spc

Static	Stop	StrComp	String

Sub	Tab	Then	To

True	Type	TypeOf*	UBound

Unload*	Unlock	Until	Variant

Wend	While	Width	With

Write	Xor

*Keyword restricted for future expansion of the language or to maintain compatibility with existing editions of Visual Basic.


Keywords

A keyword is a word or symbol recognized as part of the programming language; for example, a statement, function name, or operator.

In Visual Basic, there are two types of keywords:

Type	Description

Restricted	Keywords that should not be used to name procedures.

Unrestricted	Keywords that may be used without restriction.  Many of the unrestricted keywords are system or application-provided functions, methods, properties, and statement names that are unknown to the compiler.  This allows you to define your own procedures with the same name.  For example, if you create a FileCopy procedure and call it from within your application, your version of FileCopy is used, rather than the system-provided FileCopy statement.


CreateObject Function

Creates an OLE Automation object.

Syntax

CreateObject(class)

Elements

The class named argument uses the syntax: "appname.objecttype" and has these parts:

Part	Description

appname	The name of the application providing the object.

objecttype	The type or class of object to create.

Remarks

Note   If an application that supports OLE Automation exposes an object library, it is preferable to use the functions defined within the library for object creation rather than use CreateObject.

Each application that supports OLE Automation provides at least one type of object.  For example, a word processing application may provide an application object, a document object, and a toolbar object.

Use this function to create an OLE Automation object and assign the object to an object variable.  To do this,  use the Set statement to assign the object returned by CreateObject to the object variable.  For example:

Set WordBasicObject = CreateObject("Word.Basic")

When this code is executed, the application creating the object is started, if it is not already running (Microsoft Word in this example), and an object of the specified type is created.  Once an object is created, you reference it in code using the object variable you defined.  In the above example, you access properties and methods of the new object using the object variable, WordBasicObject.  For example:

WordBasicObject.Insert "Hello, world."

WordBasicObject.FilePrint

WordBasicObject.FileSaveAs "C:\DOCS\TEST.DOC"


GetObject Function

Retrieves an OLE Automation object from a file.

Syntax

GetObject([pathname][,class])

Elements

The GetObject function syntax has these named-argument parts:

Part	Description

pathname	The full path and name of the file containing the object to retrieve.  If pathname is omitted, class is required.

class	A string representing the class of the object.

The class argument uses the syntax: "appname.objecttype" and has these parts:

Part	Description

appname	The name of the application providing the object.

objecttype	The type or class of object to create.

Remarks

Note   If an application which supports OLE Automation exposes an object library, it is preferable to use the functions defined within the library for object access rather than use GetObject.

Use the GetObject function to access an OLE Automation object from a file and assign the object to an object variable.  To do this, use the Set statement to assign the object returned by GetObject to the object variable.  For example:

Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified file name is started and the object in the specified file is activated.

If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type.  If the pathname argument is omitted entirely, GetObject returns the currently active object of the specified type.  If no object of the specified type exists, an error occurs.

The above example shows how to activate an entire file.  However, some applications allow you to activate part of a file.  To do this, add an exclamation point (!) to the end of the file name followed by a string that identifies the part of the file you want to activate.  For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file.  You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class, the OLE.DLLs determine the application to invoke and the object to activate based on the file name you provide.  Some files, however, may support more than one class of object.  For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file.  To specify which object in a file you want to activate, use the optional class argument.  For example:

Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the above example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

Once an object is activated, you reference it in code using the object variable you defined.  In the above example, you access properties and methods of the new object using the object variable MyObject.  For example:

MyObject.Line 9, 90

MyObject.InsertText 9, 100, "Hello, world."

MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"


MacScript Statement

Executes an AppleScript script; available on the Macintosh using System 7.0 or later.

Syntax

MacScript script

Elements

The script named argument is a string expression specifying the name of an AppleScript script.

Remarks

Multiline scripts may be created by embedding carriage return characters (Chr(13)).


Visual Basic Constants

The following constants are specified by Visual Basic.  As a result, they can be used anywhere in your code in place of the actual values.

Dir, GetAttr, and SetAttr Constants

MsgBox Constants

StrConv Constants

VarType Constants


VarType Constants (Variant variable type tag)

Constant	Value	Description
vbEmpty	0	Uninitialized.
vbNull	1	Contains no valid data.
vbInteger	2	Integer.
vbLong	3	Long integer.
vbSingle	4	Single-precision floating point number.
vbDouble	5	Double-precision floating point number.
vbCurrency	6	Currency.
vbDate	7	Date.
vbString	8	String.
vbObject	9	OLE Automation object.
vbError	10	Error.
vbBoolean	11	Boolean.
vbVariant	12	Variant (used only for arrays of Variants).
vbDataObject	13	Non-OLE Automation object.
vbArray	8192	Array.


MsgBox Constants

MsgBox Arguments

Constant	Value	Description
vbOKOnly	0	OK button only.
vbOKCancel	1	OK and Cancel buttons.
vbAbortRetryIgnore	2	Abort, Retry, and Ignore buttons.
vbYesNoCancel	3	Yes, No, and Cancel buttons.
vbYesNo	4	Yes and No buttons.
vbRetryCancel	5	Retry and Cancel buttons.
vbCritical	16	Critical message.
vbQuestion	32	Warning query.
vbExclamation	48	Warning message.
vbInformation	64	Information message.
vbApplicationModal	0	Application modal message box.
vbDefaultButton1	0	First button is default.
vbDefaultButton2	256	Second button is default.
vbDefaultButton3	512	Third button is default.
vbSystemModal	4096	System modal message box.
MsgBox return values

Constant	Value	Description
vbOK	1	OK button pressed.
vbCancel	2	Cancel button pressed.
vbAbort	3	Abort button pressed.
vbRetry	4	Retry button pressed.
vbIgnore	5	Ignore button pressed.
vbYes	6	Yes button pressed.
vbNo	7	No button pressed.


Dir, GetAttr, and SetAttr Constants

Constant	Value	Description
vbNormal	0	Normal.
vbReadOnly	1	Read-only.
vbHidden	2	Hidden.
vbSystem	4	System [image] not available on the Macintosh.
vbVolume	8	Volume label [image] not available on the Macintosh.
vbDirectory	16	Directory or folder.
vbArchive	32	File has changed since last backup [image] not available on the Macintosh.


StrConv Constants

Constant	Value	Description
vbUpperCase	1	Uppercases the string.
vbLowerCase	2	Lowercases the string.
vbProperCase	3	Uppercases first letter of every word in string.
vbWide	4	Narrow (single-byte) characters in string converted to wide (double-byte) characters.
vbNarrow	8	Wide (double-byte) characters in string converted to narrow (single-byte) characters.
vbKatakana	16*	Narrow Hiragana characters in string converted to wide Katakana characters.
vbHiragana	32*	Wide Katakana characters in string converted to narrow Hiragana characters.
*Applies to Japan locales only.


IMEStatus Function

Returns the current Input Method Editor (IME) mode of Microsoft Windows; available in Far East versions only.

Syntax

IMEStatus

Return Values

Japanese locale:

Value	Description

0	No operation.

1	IME on.

2	IME off.

3	IME disabled.

4	Hiragana double-byte characters (DBC).

5	Katakana DBC.

6	Katakana single-byte characters (SBC).

7	Alphanumeric DBC.

8	Alphanumeric SBC.

Korean locale:

Value	Description

0	No operation.

1	IME on.

2	IME off.

3	IME disabled.

4	Hangeul DBC.

5	Hanja conversion.

6	Reserved for consistency of IMEStatus information and future Hanja word conversion requirements.

7	Alphanumeric DBC.

8	Alphanumeric SBC.


StrConv Function

Returns a converted string; available in Far East versions only.

Syntax

StrConv(string,conversion)

Elements

The StrConv function syntax has these named-argument parts:

Part	Description

string	The string expression to be converted.

conversion	The sum of values specifying the type of conversion to perform.

The conversion named argument has these constants and values:

Constant	Value	Description

vbUpperCase	1	Uppercases the string.

vbLowerCase	2	Lowercases the string.

vbProperCase	3	Uppercases first letter of every word in string.

vbWide	4	Narrow (single-byte) characters in string converted to wide (double-byte) characters.

vbNarrow	8	Wide (double-byte) characters in string converted to narrow (single-byte) characters.

vbKatakana	16*	Wide Hiragana characters in string converted to wide Katakana characters.

vbHiragana	32*	Wide Katakana characters in string converted to wide Hiragana characters.

*Applies to Japan locales only.

Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.


Document Conventions

Visual Basic uses the following typographic conventions.

Convention	Description

Sub, If, ChDir, Print, True, Debug	Words in bold with initial letter capitalized indicate language-specific keywords.

setup	Words you are instructed to type appear in bold.

object, varname, arglist	Italic, lowercase letters indicate placeholders for information you supply.

pathname, filenumber	Bold, italic, and lowercase letters indicate placeholders for arguments where you can use either positional or named-argument syntax.

[expressionlist]	In syntax, items inside square brackets are optional.

{While | Until}	In syntax, braces and a vertical bar indicate a mandatory choice between two or more items.  You must choose one of the items unless all of the items also are enclosed in square brackets.  For example:

[{This | OrThat}]

VBA.INI, ESC, ENTER	Words in all capital letters indicate file names, keys, and key sequences.

ALT+F1, CTRL+R	A plus sign (+) between key names indicates a combination of keys.  For example, ALT+F1 means to hold down the ALT key while pressing the F1 key.

MyString = "Hello, world!"	This font is used for code, variables, and error message text.

' This is a comment.	An apostrophe (') introduces code comments

MyVar = "This is an " _	SPACE+UNDERSCORE continues a line of code.

& "example" _

& _"of how to continue code"


Constants (Object Browser)

The Constants module displays the predefined constants used with the Dir, GetAttr, MsgBox, and VarType functions and with the SetAttr statement.


Conversion Procedures (Object Browser)

The Conversion module displays the procedures used to perform conversion operations.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


DateTime Procedures (Object Browser)

The DateTime module displays the procedures used to perform date and time operations.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


FileSystem Procedures (Object Browser)

The FileSystem module displays the procedures used to perform file, directory or folder, and system operations.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


Information Procedures (Object Browser)

The Information module displays the procedures used to return, test for, or verify information.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


Interaction Procedures (Object Browser)

The Interaction module displays procedures used to interact with objects, applications, and systems.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


Math Procedures (Object Browser)

The Math module displays procedures used to perform mathematical operations.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


Text Procedures (Object Browser)

The Text module displays procedures used to perform string operations.

To get help on a particular procedure

1.	Select the procedure within the Methods/Properties list box.

2.	Choose the ? button.


AppActivate Statement

Activates an application window.

Syntax

AppActivate title [,wait]

Elements

The AppActivate statement syntax has these named-argument parts:

Part	Description

title	In Microsoft Windows, the title argument is the string in the title bar of the application window you want to activate.

On the Macintosh (System 7.0 or later), the title argument is the application name.  You can use the MacID function to specify an application's signature instead of the application name.  For example,

AppActivate MacID("MSWD")

In addition, the task ID returned by the Shell function can be used, in place of title, to activate an application.

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

Remarks

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized.  Focus moves from the activated application window when the user takes some action to change the focus or close the window.  Use the Shell function to start an application and set the window style.

In trying to find the application to activate, a comparison is made to try to find an application whose title string is an exact match with title.  If unsuccessful, any application's title string that begins with title is activated.  In Microsoft Windows, if there is more than one instance of the application named by title, one is arbitrarily activated.

If you use the MacID function with AppActivate in Microsoft Windows, an error occurs.


Beep Statement

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depends on hardware, which may vary among computers.


InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or choose a button, and returns the contents of the text box.

Syntax

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

Elements

The InputBox function syntax has these named-argument parts:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.  If prompt consists of more than one line, be sure to include a carriage return (character code 13), or carriage return linefeed (character code 10) between each line.

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

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

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

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

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

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

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.

If the user chooses OK or presses Enter, the InputBox function returns whatever is in the text box.  If the user chooses Cancel, the function returns a zero-length string ("").


MsgBox Function

Displays a message in a dialog box, waits for the user to choose a button, and returns a value indicating which button the user has chosen.

Syntax

MsgBox(prompt[,buttons][,title][,helpfile,context])

Elements

The MsgBox function syntax has these named-argument parts:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.  If prompt consists of more than one line, be sure to include a carriage return (character code 13) or carriage return linefeed (character code 10) between each line.

buttons	Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality.  If omitted, the default value for buttons is 0.

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

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

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

The buttons named argument has these values:

Constant	Value	Description

vbOKOnly	0	Display OK button only.

vbOKCancel	1	Display OK and Cancel buttons.

vbAbortRetryIgnore	2	Display Abort, Retry, and Ignore buttons.

vbYesNoCancel	3	Display Yes, No, and Cancel buttons.

vbYesNo	4	Display Yes and No buttons.

vbRetryCancel	5	Display Retry and Cancel buttons.

vbCritical	16	Display Critical Message icon.

vbQuestion	32	Display Warning Query icon.

vbExclamation	48	Display Warning Message icon.

vbInformation	64	Display Information Message icon.

vbDefaultButton1	0	First button is default.

vbDefaultButton2	256	Second button is default.

vbDefaultButton3	512	Third button is default.

vbApplicationModal	0	Application modal; the user must respond to the message box before continuing work in the current application.

vbSystemModal	4096	System modal; all applications are suspended until the user responds to the message box.

The first group of values (0-5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default, and the fourth group (0, 4096) determines the modality of the message box.  When adding numbers to create a final value for the argument buttons, use only one number from each group.

Note   These constants are specified by Visual Basic.  As a result, the names can be used anywhere in your code in place of the actual values.

Return Values

Constant	Value	Button Selected

vbOK	1	OK

vbCancel	2	Cancel

vbAbort	3	Abort

vbRetry	4	Retry

vbIgnore	5	Ignore

vbYes	6	Yes

vbNo	7	No

Remarks

When both helpfile and context are provided, a Help button is automatically added to the dialog box.

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as choosing Cancel.  If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box.  However, no value is returned until one of the other buttons is chosen.


RGB Function

Returns a whole number representing an RGB color value.

Syntax

RGB (red, green, blue)

Elements

The RGB function syntax has these named-argument parts:

Part	Description

red	Whole number in the range 0 to 255, inclusive, that represents the red component of the color.

green	Whole number in the range 0 to 255, inclusive, that represents the green component of the color.

blue	Whole number in the range 0 to 255, inclusive, that represents the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a whole number representing an RGB color value.  An RGB color value specifies the relative intensity of red, green, and blue, which combined cause a specific color to be displayed.

The value for any argument to RGB that exceeds 255 is assumed to be 255.

The following table lists some standard colors and the red, green and blue values they include:

Color	Red Value	Green Value	Blue Value

Black	0	0	0

Blue	0	0	255

Green	0	255	0

Cyan	0	255	255

Red	255	0	0

Magenta	255	0	255

Yellow	255	255	0

White	255	255	255

Note   The RGB values returned by this function are incompatible with those used by the Macintosh operating system.  They may be used within the context of Microsoft applications for the Macintosh, but should not be used when communicating color changes directly to the Macintosh operating system.


SendKeys Statement

Sends one or more keystrokes to the active window as if typed at the keyboard; not available on the Macintosh.

Syntax

SendKeys string[,wait]

Elements

The SendKeys statement syntax has these named-argument parts:

Part	Description

string	String expression specifying the keystroke(s) to send.

wait	Boolean value specifying the wait mode.  If False (default), control is returned to the procedure immediately after the keys are sent.  If True, keystrokes must be processed before control is returned to the procedure.

Remarks

Each key is represented by one or more characters.  To specify a single keyboard character, use the character itself.  For example, to represent the letter A, use "A" for string.  If you want to represent more than one character, append each additional character to the one preceding it.  To represent the letters A, B, and C, use "ABC" for string.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys.  To specify one of these characters, enclose it within braces.  For example, to specify the plus sign, use {+}.  Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces as well, because in other applications, brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs.  To send brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key (such as ENTER or TAB) and keys that represent actions rather than characters, use the codes shown below:

Key	Code

BACKSPACE	{BACKSPACE}, {BS}, or {BKSP}

BREAK	{BREAK}

CAPS LOCK	{CAPSLOCK}

DEL	{DELETE} or {DEL}

DOWN ARROW	{DOWN}

END	{END}

ENTER	{ENTER}

ESC	{ESC}

HELP	{HELP}

HOME	{HOME}

INS	{INSERT}

LEFT ARROW	{LEFT}

NUM LOCK	{NUMLOCK}

PAGE DOWN	{PGDN}

PAGE UP	{PGUP}

PRINT SCREEN	{PRTSC}

RIGHT ARROW	{RIGHT}

SCROLL LOCK	{SCROLLLOCK}

TAB	{TAB}

UP ARROW	{UP}

F1	{F1}

F2	{F2}

F3	{F3}

F4	{F4}

F5	{F5}

F6	{F6}

F7	{F7}

F8	{F8}

F9	{F9}

F10	{F10}

F11	{F11}

F12	{F12}

F13	{F13}

F14	{F14}

F15	{F15}

F16	{F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the regular key code with one or more of the following codes:

Key	Code

SHIFT	+

CTRL (CONTROL)	^

ALT	%

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses.  For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)".  To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

To specify repeating keys, use the form {key number}.  You must put a space between key and number.  For example, {LEFT 42} means press the LEFT ARROW key 42 times; {h 10} means press h 10 times.

Note   SendKeys can't send keystrokes to an application that is not designed to run in Microsoft Windows.  Sendkeys also can't send the PRINT SCREEN (PRTSC) key to any application.


AppActivate Statement Example

This example illustrates various uses of the AppActivate statement to activate an application window.  On the Macintosh, you can use the MacID function to specify the application's signature instead of the application's name.  The AppActivate statement is available with Macintosh System 7.0 or later.

' In Microsoft Windows.

AppActivate "Microsoft Word"	' Activate Word.

' AppActivate can also use the return value of the Shell function.

MyAppID = Shell("C:\WORD\WINWORD.EXE", 1)	' Run Microsoft Word.

AppActivate MyAppID	' Activate Microsoft

' Word.

' On the Macintosh.

AppActivate "Microsoft Word"	' Activate Microsoft

' Word.

' MacID("MSWD") returns signature for Microsoft Word.

AppActivate MacID("MSWD")	' Activate Microsoft

' Word.

' You can also use the return value of the Shell function.

ReturnValue = Shell("Microsoft Excel")	' Run Microsoft Excel.

AppActivate ReturnValue	' Activate Microsoft

' Excel.


Beep Statement Example

This example uses the Beep statement to sound three consecutive tones through the computer's speaker.

For I = 1 to 3	' Loop 3 times.

Beep	' Sound a tone.

Next I


InputBox Function Example

This example shows various ways to use the InputBox function to prompt the user to enter a value.  If the x and y positions are omitted, the dialog is automatically centered for the respective axes.  The variable MyValue contains the value entered by the user if the user chooses OK or presses ENTER.  If the user chooses Cancel, a zero-length string is returned.

Message = "Enter a value between 1 and 3"	' Set prompt.

Title = "InputBox Demo"	' Set title.

Default = "1"	' Set default.

' Display message, title, and default value.

MyValue = InputBox(Message, Title, Default)

' Use helpfile and context. The help button is added automatically.

MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog at position 100,100

MyValue = InputBox(Message, Title, Default, 100, 100)


MsgBox Function Example

The example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons.  The No button is specified as the default response.  The value returned by the MsgBox function depends on the button chosen by the user.  For purposes of this example, assume that DEMO.HLP is a Help file that contains a topic with context number equal to 1000.

Msg = "Do you want to continue ?"	' Define message.

Style = vbYesNo + vbCritical + vbDefaultButton2	' Define buttons.

Title = "MsgBox Demonstration"	' Define title.

Help = "DEMO.HLP"	' Define help file.

Ctxt = 1000	' Define topic

' context.

' Display message.

Response = MsgBox(Msg, Style, Title, Help, Ctxt)

If Response = vbYES Then	' User chose Yes

' button.

MyString = "Yes"	' Perform some action.

Else	' User chose No

' button.

MyString = "No"	' Perform some action.

End If


RGB Function Example

This example shows how the RGB function is used to return a  whole number representing an RGB color value.  It is used for those application methods and properties that accept a color specification.  The object MyObject and its property are used here for illustration purposes only.

Red = RGB(255, 0, 0)	' Return the value for Red.

I = 75	' Initialize offset.

RGBValue = RGB(I, 64 + I, 128 + I) 	' Same as RGB(75, 139, 203).

MyObject.Color = RGB(255, 0, 0)	' Set the Color property of

' MyObject to Red.


SendKeys Statement Example

This example uses the Shell function to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to add some numbers and then quit the Calculator.  The SendKeys statement is not available on the Macintosh.

ReturnValue = Shell("Calc.exe", 1)	' Run Calculator.

AppActivate ReturnValue 	' Activate the Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	' to add each value of I.

SendKeys "=", True	' Get grand total.

SendKeys "%{F4}", True	' Send Alt+F4 to close Calculator.


Print Method

Prints text in the Immediate pane of the Debug window.

Syntax

[object.]Print [outputlist]

Elements

The Print method syntax has these parts:

Part	Description

object	Object expression that evaluates to the Debug object.

outputlist	Expression or list of expressions to print.  If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Part	Description

Spc(n)	Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)	Used to position the insertion point at an absolute column number where n is the column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.

expression	Numeric or string expressions to print.

charpos	Specifies the insertion point for the next character. Use a semicolon to specify the insertion point to immediately follow the last character displayed.  Use Tab(n) to position the insertion point at an absolute column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.  If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon.  A space has the same effect as a semicolon.

All data printed to the Immediate pane is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are output in the language appropriate for the international locale specified for your system.

For Boolean data, either True or False is printed.  The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written using the standard short date format recognized by your system.  When either the date or the time component is missing or zero, only the data provided gets written.

Nothing is written if outputlist data is Empty.  However, if outputlist data is Null, Null is output.  Again, the Null keyword is translated, as appropriate, when output.

For error data, the output appears as Error errorcode.  The Error keyword is translated, as appropriate, when output.

Note   Because the Print method normally prints with proportionally-spaced characters, it is important to remember that there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, a wide letter, such as a "W", occupies more than one fixed-width column, whereas a narrow letter, such as an "i", occupies less.  To account for cases where wider than average characters are used, you must ensure that your tabular columns are positioned far enough apart.  Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.


Debug Object

The Debug object is accessed with the keyword Debug, and is used to send output to the Debug window at run time.


Print Method Example

This example uses the Print method to output text to the Debug object; that is, display text in the Debug window.

For I = 11 To 20	' Loop 10 times.

' Print each value on a new line.

Debug.Print I

Next I

For I = 11 To 20	' Loop 10 times.

' Print values on the same line, next to each other.

Debug.Print I;

Next I

Debug.Print Spc(10) ; "Hello there"	' Print 10 spaces before.

Debug.Print Tab(20) ; "This is a test"	' Print at column 20.

Debug.Print "Hello"; Tab; Tab; "There"	' Print 2 print zones apart.


Operator Summary

Arithmetic Operators

Operators used to perform mathematical calculations.

Comparison Operators

Operators used to perform comparisons.

Concatenation Operators

Operators used to combine strings.

Logical Operators

Operators used to perform logical operations.


Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order.  That order is known as operator precedence.  Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others.  Operations within parentheses are always performed before those outside.  Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.  Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear.  Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic	Comparison	Logical

Exponentiation (^)	Equality (=)	Not

Negation (-)	Inequality (<>)	And

Multiplication and division (*,/)	Less than (<)	Or

Integer division (\)	Greater than (>)	Xor

Modulo arithmetic (Mod)	Less than or Equal to (<=)	Eqv

Addition and subtraction (+,-)	Greater than or Equal to (>=)	Imp

String concatenation (&)	Like

Is

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right.  Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not really an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators.  Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator.  The Is operator is an object reference comparison operator.  It does not compare objects or their values; it checks only to determine if two object references refer to the same object.


Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator


Concatenation Operators

& Operator

+ Operator


Logical Operators

And Operator

Eqv Operator

Imp Operator

Not Operator

Or Operator

Xor Operator


^ Operator

Used to raise a number to the power of an exponent.

Syntax

result = number^exponent

Elements

The ^ operator syntax has these parts:

Part	Description

result	Any numeric variable.

number	Any numeric expression.

exponent	Any numeric expression.

Remarks

Number can be negative only if exponent is an integer value.  When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant containing a Double.  However, if either number or exponent is a Null expression, result is also a Null.


+ Operator

Used to sum two numbers.

Syntax

result = expression1+expression2

Elements

The + operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur.  If at least one expression is not a Variant, the following rules apply:

If	Then
Both expressions are numeric data types (Boolean, Integer, Long, Single, Double, Date or Currency)	Add.
Both expressions are String	Concatenate.
One expression is a numeric data type and the other is any Variant (except a Null)	Add.
One expression is a String and the other is any Variant (except a Null)	Concatenate.
One expression is an  Empty Variant	Return the remaining expression unchanged as result.
One expression is a numeric data type and the other is a String	A Type mismatch error occurs.
Either expression is a Null	result is a Null.
If both expressions are Variant expressions, the underlying type of the expressions determines the behavior of the + operator in the following way:

If	Then
Both Variant expressions are numeric	Add.
Both Variant expressions are strings	Concatenate.
One Variant expression is numeric and the other is a string	Add.
For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression.  The order of precision, from least to most precise, is Integer, Long, Single, Double, and Currency.  The following are exceptions to this order:

•	When a Single and a Long are added together, the data type of result is converted to a Double.

•	When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Double variant.

•	When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

•	When a Date is added to any other data type, the data type of result is always a Date.

If one or both expressions are Null expressions, result is a Null.  If both expressions are Empty, result is an Integer.  However, if only one expression is Empty, the other expression is returned unchanged as result.


- Operator

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

-number

Elements

The - operator syntax has these parts:

Part	Description

result	Any numeric variable.

number	Any numeric expression.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers.  In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

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

•	When subtraction involves a Single and a Long, the data type of result is converted to a Double.

•	When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.

•	When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

•	When subtraction involves a Date and any other data type, the data type of result is a Date.

•	When subtraction involves two Date expressions, the data type of result is Double.

If one or both expressions are Null expressions, result is a Null.  If an expression is Empty, it is treated as if it were 0.


* Operator

Used to multiply two numbers.

Syntax

result = number1*number2

Elements

The * operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

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

•	When multiplication involves a Single and a Long, the data type of result is converted to a Double.

•	When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.

•	When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

If one or both expressions are Null expressions, result is a Null.  If an expression is Empty, it is treated as if it were 0.


/ Operator

Used to divide two numbers and return a floating-point result.

Syntax

result = number1/number2

Elements

The / operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

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

•	When both expressions are Integer or Single expressions, result is a Single unless it overflows its legal range; in which case, an error occurs.

•	When both expressions are Integer or Single variants, result is a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.

If one or both expressions are Null expressions, result is a Null.  Any expression that is Empty is treated as 0.


\ Operator

Used to divide two numbers and return an integer result.

Syntax

result = number1\number2

Elements

The \ operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Integer or Long expressions.

Usually, the data type of result is an Integer, Integer variant, Long, or Long variant, regardless of whether or not result is a whole number.  Any fractional portion is truncated.  However, if any expression is a Null, result is also a Null.  Any expression that is Empty is treated as 0.


Mod Operator

Divides two numbers and returns only the remainder.

Syntax

result = number1 Mod number2

Elements

The Mod operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result.  For example, in the following expression, A (which is result) equals 5.

A = 19 Mod 6.7

Usually, the data type of result is an Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number.  Any fractional portion is truncated.  However, if any expression is a Null, result is also a Null.  Any expression that is Empty is treated as 0.


& Operator

Used to force string concatenation of two expressions.

Syntax

result = expression1 & expression2

Elements

The & operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

Whenever an expression is not a string, it is converted to a String variant.  The data type of result is String if both expressions are String expressions; otherwise, result is a String variant.  If both expressions are Null, result is also Null.  However, if only one expression is a Null, that expression is treated as a zero-length string when concatenated with the other expression.  Any expression that is Empty is also treated as a zero-length string.


Comparison Operators

Used to compare expressions.

Syntax

result = expression1 comparisonoperator expression2
result = object1 Is object2
result = string Like pattern

Elements

Comparison operators have these parts:

Part	Description

result	Any numeric variable.

expression	Any expression.

comparisonoperator	Any comparison operator.

object	Any object name.

string	Any string expression.

pattern	Any string expression or range of characters.

Remarks

The Is and Like operators have specific comparison functionality that differs from the operators in the following table.  The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator	Description	True if	False if	Null if
<	Less than	expression1 < expression2	expression1 >= expression2	expression1 or expression2 = Null
<=	Less than or equal to	expression1 <= expression2	expression1 > expression2	expression1 or expression2 = Null
>	Greater than	expression1 > expression2	expression1 <= expression2	expression1 or expression2 = Null
>=	Greater than or equal to	expression1 >= expression2	expression1 < expression2	expression1 or expression2 = Null
=	Equal to	expression1 = expression2	expression1 <> expression2	expression1 or expression2 = Null
<>	Not equal to	expression1 <> expression2	expression1 = expression2	expression1 or expression2 = Null
When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings.  The following table shows how the expressions are compared or what results when either expression is not a Variant:

If	Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency)	Perform a numeric comparison.
Both expressions are String	Perform a string comparison.
One expression is a numeric data type and the other is a Variant that is, or can be, a number	Perform a numeric comparison.
One expression is a numeric data type and the other is a string Variant that can't be converted to a number	A Type Mismatch error occurs.
One expression is a String and the other is any Variant (except a Null)	Perform a string comparison.
One expression is Empty and the other is a numeric data type	Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String	Perform a string comparison, using a zero-length string as the Empty expression.
If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared.  The following table shows how the expressions are compared or what results from the comparison, depending on the underlying type of the Variant:

If	Then
Both Variant expressions are numeric	Perform a numeric comparison.
Both Variant expressions are strings	Perform a string comparison.
One Variant expression is numeric and the other is a string	The numeric expression is less than the string expression.
One Variant expression is Empty and the other is numeric	Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is a string	Perform a string comparison, using a zero-length string as the Empty expression.
Both Variant expressions are Empty	The expressions are equal.
Note   If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency.  This causes any fractional part of the Single or Double value less than 0.0001 to be lost and may cause two values to compare as equal when they are not.  When a Single is compared to a Double, the Double is rounded to the precision of the Single.


And Operator

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

Elements

The And operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If, and only if, both expressions evaluate True, result is True.  If either expression evaluates False, result is False.  The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result is

True	True	True

True	False	False

True	NulldefNull	Null

False	True	False

False	False	False

False	Null	False

Null	True	Null

Null	False	False

Null	Null	Null

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

If bit in expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	0

1	0	0

1	1	1


Eqv Operator

Used to perform a logical equivalence on two expressions.

Syntax

result = expression1 Eqv expression2

Elements

The Eqv operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If either expression is a Null, result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expression1 is	And expression2 is	The result is

True	True	True

True	False	False

False	True	False

False	False	True

The Eqv operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is	And bit in expression2 is	The result is

0	0	1

0	1	0

1	0	0

1	1	1


Imp Operator

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

Elements

The Imp operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result is

True	True	True

True	False	False

True	Null	Null

False	True	True

False	False	True

False	Null	True

Null	True	True

Null	False	Null

Null	Null	Null

The Imp operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is	And bit in expression2 is	The result is

0	0	1

0	1	1

1	0	0

1	1	1


Not Operator

Used to perform logical negation on an expression.

Syntax

result = Not expression

Elements

The Not operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression	Any expression.

Remarks

The following table illustrates how result is determined:

If expression is	Then result is

True	False

False	True

Null	Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following truth table:

Bit in expression	Bit in result

0	1

1	0


Or Operator

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

Elements

The Or operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If either or both expressions evaluate True, result is True.  The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result is

True	True	True

True	False	True

True	Null	True

False	True	True

False	False	False

False	Null	Null

Null	True	True

Null	False	Null

Null	Null	Null

The Or operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	1

1	0	1

1	1	1


Xor Operator

Used to perform a logical exclusion on two expressions.

Syntax

result = expression1 Xor expression2

Elements

The Xor operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If one, and only one, of the expressions evaluates True, result is True.  However, if either expression is a Null, result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expression1 is	And expression2 is	The result is

True	True	False

True	False	True

False	True	True

False	False	False

The Xor operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	1

1	0	1

1	1	0


Like Operator

Used to compare two strings.

Syntax

result = string Like pattern

Elements

The Like operator syntax has these parts:

Part	Description

result	Any numeric variable.

string	Any string expression.

pattern	Any string expression conforming to the pattern-matching conventions described in the following section.

Remarks

If string matches pattern, result is True; if there is no match, result is False; and if either string or pattern is a Null, result is also a Null.

The behavior of the Like operator depends on the Option Compare statement.  Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. On the Macintosh, sort order is determined by the character set. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e  < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system's locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a)  < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons.  The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings.  The following table shows the characters allowed in pattern and what they match:

Character(s) in pattern	Matches in string

?	Any single character.

*	Zero or more characters.

#	Any single digit (0-9).

[charlist]	Any single character in charlist.

[!charlist]	Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note   The special characters left bracket ([), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets.  The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range.  For example, [A-Z] in pattern results in a match if the corresponding character position in string contains any of the uppercase letters in the range A through Z.  Multiple ranges are included within the brackets without any delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the same example shown above with Option Compare Binary, the range [A-E] matches A, B and E. With Option Compare Text, [A-E] matches A, a, À, à, B, b, E, e.  Note that it does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

•	An exclamation point (!) at the beginning of charlist means that a match is made if any character except the ones in charlist are found in string.  When used outside brackets, the exclamation point matches itself.

•	The hyphen (-) can appear either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself.  In any other location, the hyphen is used to identify a range of characters.

•	When a range of characters is specified, they must appear in ascending sort order (from lowest to highest).  [A-Z] is a valid pattern, but [Z-A] is not.

•	The character sequence [] is ignored; it is considered a zero-length string.


Is Operator

Used to compare two object reference variables.

Syntax

result = object1 Is object2

Elements

The Is operator syntax has these parts:

Part	Description

result	Any numeric variable.

object1	Any object name.

object2	Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

In the following example, A has been set to refer to the same object as B:

Set A = B

The following example makes A and B refer to the same object as C:

Set A = C

Set B = C


^ Operator Example

This example uses the ^ operator to raise a number to the power of an exponent.

MyValue = 2 ^ 2	' Returns 4.

MyValue = 3 ^ 3 ^ 3	' Returns 19683.

MyValue = (-5) ^ 3	' Returns -125.


+ Operator Example

This example uses the + operator to sum numbers.  The + operator can also be used to concatenate strings but to eliminate ambiguity, you should use the & operator instead.

MyNumber = 2 + 2	' Returns 4.

MyNumber = 4257.04 + 98112	' Returns 102369.04.

Var1 = "34" : Var2 = 6	' Initialize variables.

MyNumber = Var1 + Var2	' Returns 40.

Var1 = "34" : Var2 = "6"	' Initialize variables.

MyNumber = Var1 + Var2	' Returns "346" (string concatenation).


- Operator Example

This example uses the - operator to calculate the difference between two numbers.

MyResult = 4 - 2	' Returns 2.

MyResult = 459.35 - 334.90	' Returns 124.45.


* Operator Example

This example uses the * operator to multiply two numbers.

MyValue = 2 * 2	' Returns 4.

MyValue = 459.35 * 334.90 	' Returns 153836.315.


/ Operator Example

This example uses the / operator to perform floating-point division.

MyValue = 10 / 4	' Returns 2.5.

MyValue = 10 / 3	' Returns 3.333333.


\ Operator Example

This example uses the \ operator to perform integer division.

MyValue = 11 \ 4	' Returns 2.

MyValue = 9 \ 3	' Returns 3.

MyValue = 100 \ 3	' Returns 33.


Mod Operator Example

This example uses the Mod operator to divide two numbers and return only the remainder.  If either number is a floating-point number, it is first rounded to an integer.

MyResult = 10 Mod 5	' Returns 0.

MyResult = 10 Mod 3	' Returns 1.

MyResult = 12 Mod 4.3	' Returns 0.

MyResult = 12.6 Mod 5	' Returns 3.


& Operator Example

This example uses the & operator to force string concatenation.

MyStr = "Hello" & " World"	' Returns "Hello World".

MyStr = "Check " & 123 & " Check"	' Returns "Check 123 Check".


Comparison Operators Example

This example shows various uses of comparison operators, which you use to compare expressions.

MyResult = (45 < 35)	' Returns False.

MyResult = (45 = 45)	' Returns True.

MyResult = (4 <> 3)	' Returns True.

MyResult = ("5" > "4")	' Returns True.

Var1 = "5" : Var2 = 4	' Initialize variables.

MyResult = (Var1 > Var2)	' Returns True.

Var1 = 5 : Var2 = Empty

MyResult = (Var1 > Var2)	' Returns True.

Var1 = 0 : Var2 = Empty

MyResult = (Var1 = Var2)	' Returns True.


And Operator Example

This example uses the And operator to perform a logical conjunction on two expressions.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = A > B And B > C	' Returns True.

MyCheck = B > A And B > C	' Returns False.

MyCheck = A > B And B > D	' Returns Null.

MyCheck = A And B	' Returns 8 (bit-wise comparison).


Eqv Operator Example

This example uses the Eqv operator to perform logical equivalence on two expressions.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = A > B Eqv B > C	' Returns True.

MyCheck = B > A Eqv B > C	' Returns False.

MyCheck = A > B Eqv B > D	' Returns Null.

MyCheck = A Eqv B	' Returns -3 (bit-wise comparison).


Imp Operator Example

This example uses the Imp Operator to perform logical implication on two expressions.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = A > B Imp B > C	' Returns True.

MyCheck = A > B Imp C > B	' Returns False.

MyCheck = B > A Imp C > B	' Returns True.

MyCheck = B > A Imp C > D	' Returns True.

MyCheck = C > D Imp B > A	' Returns Null.

MyCheck = B Imp A	' Returns -1 (bit-wise comparison).


Not Operator Example

This example uses the Not operator to perform logical negation on an expression.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = Not(A > B)	' Returns False.

MyCheck = Not(B > A)	' Returns True.

MyCheck = Not(C > D)	' Returns Null.

MyCheck = Not A	' Returns -11 (bit-wise comparison).


Or Operator Example

This example uses the Or operator to perform logical disjunction on two expressions.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = A > B Or B > C	' Returns True.

MyCheck = B > A Or B > C	' Returns True.

MyCheck = A > B Or B > D	' Returns True.

MyCheck = B > D Or B > A	' Returns Null.

MyCheck = A Or B	' Returns 10 (bit-wise comparison).


Xor Operator Example

This example uses the Xor operator to perform logical exclusion on two expressions.

A = 10: B = 8: C = 6 : D = Null	' Initialize variables.

MyCheck = A > B Xor B > C	' Returns False.

MyCheck = B > A Xor B > C	' Returns True.

MyCheck = B > A Xor C > B	' Returns False.

MyCheck = B > D Xor A > B	' Returns Null.

MyCheck = A Xor B	' Returns 2 (bit-wise comparison).


Like Operator Examples
Like Operator Example

This example uses the Like operator to compare a string to a pattern.

MyCheck = "aBBBa" Like "a*a"	' Returns True.

MyCheck = "F" Like "[A-Z]"	' Returns True.

MyCheck = "F" Like "[!A-Z]"	' Returns False.

MyCheck = "a2a" Like "a#a"	' Returns True.

MyCheck = "aM5b" Like "a[L-P]#[!c-e]"	' Returns True.

MyCheck = "BAT123khg" Like "B?T*"	' Returns True.

MyCheck = "CAT123khg" Like "B?T*"	' Returns False.


Is Operator Example

This example uses the Is operator to compare two object references.  All the object variables used here are generic names and for illustration purposes only.

Set YourObject = MyObject	' Assign object references.

Set ThisObject = MyObject

Set ThatObject = OtherObject

MyCheck = YourObject Is ThisObject	' Returns True.

MyCheck = ThatObject Is ThisObject	' Returns False.

' Assume MyObject <> OtherObject

MyCheck = MyObject Is ThatObject	' Returns False.


Code Pane

A code pane is used to display, edit, and write module-level and procedure code.  In a module, the code pane can be split in two.

To split a module

From the Window menu, choose Split.

To remove a split

From the Window menu, choose Split or double-click split bar or drag the split bar to the top or bottom of the window.


Debug Window

Use the Debug window to execute individual lines of code, display variable values, view watch expressions, and perform other debugging tasks.

•	To display the Debug window, choose Debug Window from the View menu.

The Debug window is automatically opened when a breakpoint is encountered or when you manually enter break mode.

•	To close the Debug window:

In Microsoft Windows, double-click the Control menu-box or press CTRL+F4.

On the Macintosh, click the close box.

Note   Statements can't be entered in the code pane of the Debug window while code is executing; however, you can use the Debug object and the Print method to print internal values to look at in the window when execution stops.  For example, the following code prints the value of the variable A to the Debug window:

Debug.Print A

During break mode, however, you can enter statements within the Immediate pane of the Debug window.

The Debug window includes:

Immediate pane

The Immediate pane is where you enter code to execute it immediately.  The Immediate pane is displayed by default the first time you open the Debug window.

To display the Immediate pane when the Watch pane is displayed, select the Immediate tab.

Watch pane

The Watch pane displays information about all defined watch expressions.

To display the Watch pane, select the Watch tab.

Procedure box

During break mode, the Procedure box displays the name of the project, module, and procedure name where execution is stopped.  The button to the right of the Procedure box displays the Calls dialog.

Split bar

The split bar separates the Debug window into two panes.  The upper pane displays the Immediate or Watch pane.  The code pane below the split bar displays the code where execution is stopped.

To size a pane, select the split bar and drag it up or down.

Code pane

The code pane displays the procedure code where execution is stopped.


Immediate Pane

The Immediate pane is where you enter code to execute it immediately.  While working in the Immediate pane, you can type or paste a statement and press ENTER to run it.  For example, the following code displays the value of the variable A, which in this case is 5.

?A

5

In wait mode, code is executed in a global context.  In break mode, code in the Immediate pane is executed within the context displayed in the Debug window title bar.  For example, if you type Print variablename, your output is the value of a local variable.  This is the same as if the Print method had actually occurred in the procedure specified in the Procedure box.

The Immediate pane is displayed by default the first time you open the Debug window.

To display the Immediate pane when the Watch pane is showing, select the Immediate tab.


Scroll Bar

Scroll bars are graphical devices used to scroll parts of a window vertically and horizontally with a mouse. Scroll bars are located at the right and bottom edges of a window.

To scroll within a window

Do one of the following:

To scroll:	Do this:

Up one line	Click the up scroll arrow.

Up one window	Click above the scroll box in the vertical scroll bar.

To an approximate location	Drag the scroll box.

Down one line	Click the down scroll arrow.

Down one window	Click below the scroll box in the vertical scroll bar.

To the left	Click the left scroll arrow.

Left one window	Click left of the scroll box in the horizontal scroll bar.

To the right	Click the right scroll arrow.

Right one window	Click right of the scroll box in the horizontal scroll bar.

A scroll bar includes:

scroll arrow

A button with an arrow that appears at each end of the scroll bar.  The arrow indicates the direction the window contents will move when scrolled.  For example, an up scroll arrow moves towards the top, a down scroll arrow moves towards the bottom, and so on.

scroll box

A square within the scroll bar that indicates your relative position within the window.

•	To move quickly through a window, drag the scroll box along the scroll bar.


Split Bar

The split bar divides a window into two panes that can be scrolled individually.  In the Debug window, the split bar separates the code pane from the Immediate or Watch panes.  In a module, the split bar separates the module into two panes [image] this is useful when you want to view different parts of your code at the same time.

•	To split a window, choose Split from the Window menu.

•	To remove a split bar, choose Split from the Window menu or double-click the split bar.


Watch Pane

The Watch pane displays information about all defined watch expressions including the expression itself, the context of the watch expression, and its value at the time of the transition to break mode.  If the expression is not in scope, the current value is not displayed.

To display the Watch pane

Select the Watch tab in the Debug window.

The following are displayed when the value is not available:

Can't compile module [image] the module where the watch is defined contains a syntax error and can't be compiled, or the watch context is defined as "All Modules" and one of the modules in the context can't be compiled.

Invalid watch expression [image] the watch is not a valid expression.  Valid watch expressions can contain constants, variables, function procedure calls, and elements of user-defined types, but not sub procedure calls or user-defined types.

Out of context [image] the watch value is not available within the current context.  For example, in wait mode all watches are out of context.

Can't evaluate watches on arrays [image] the watch expression is an array.  Only elements of an array may be watched.


Chr Function

Returns the character associated with the specified character code.

Syntax

Chr(charcode)

Elements

The charcode named argument is a number in the range 0 to 255, inclusive, that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes.  For example, Chr(10) returns a linefeed character.


Format Function

Formats an expression according to instructions contained in a format expression.

Syntax

Format(expression[,format])

Elements

The Format function syntax has these parts:

Part	Description

expression	Any valid expression.

format	A valid named or user-defined format expression.

Remarks

To Format These	Do This

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

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

Date and time serial numbers	Use date and time formats or numeric formats.

Strings	Create your own user-defined string formats.

If you try to format a number without specifying format, Format provides the same functionality as the Str function.  However, positive numbers formatted as strings using Format lack the leading space reserved for displaying the sign of the value; whereas, those converted using Str retain the leading space.


Named Numeric Formats (Format Function)

The following table identifies the predefined numeric format names:

Format name	Description

General Number	Display number as is, with no thousand separators.

Currency	Display number with thousand separator, if appropriate; display negative numbers enclosed in parentheses; display two digits to the right of the decimal separator.  Note that output is based on system settings.

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

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

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

Scientific	Use standard scientific notation.

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

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

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


User-Defined Numeric Formats (Format Function)

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

Character	Description

None	No formatting

Display the number with no formatting.

0	Digit placeholder

Display a digit or a zero.  If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros.  If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros.  If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.

#	Digit placeholder

Display a digit or nothing.  If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

.	Decimal placeholder

In some locales, a comma is used as the decimal separator.  The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator.  If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator.  If you always want a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator instead.  The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.

%	Percentage placeholder

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

,	Thousand separator

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

:	Time separator

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

/	Date separator

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

E- E+ e- e+	Scientific format

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

- + $ ( ) space	Display a literal character

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

\	Display the next character in the format string

Many characters in the format expression have a special meaning and can't be displayed as literal characters unless they are preceded by a backslash.  The backslash itself isn't displayed.  Using a backslash is the same as enclosing the next character in double quotation marks.  To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date- and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, and /:), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).

"ABC"	Display the string inside the double quotation marks

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


Different Formats for Diffierent Numeric Values
Different Formats for Different Numeric Values (Format Function)

A format expression for numbers can have from one to four sections separated by semicolons.  (If the format argument contains one of the predefined formats, only one section is allowed.)

If you use	The result is

One section only	The format expression applies to all values.

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

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

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

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.

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

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value.  For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.

"$#,##0;;\Z\e\r\o"


User-Define Numeric Format Examples
User-Defined Numeric Format Examples

Some sample format expressions for numbers are shown below. (These examples all assume that your system's locale setting is English-US.)  The first column contains the format strings.  The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (format)	Positive 5	Negative 5	Decimal .5	Null

Zero-length string	5	-5	0.5

0	5	-5	1

0.00	5.00	-5.00	0.50

#,##0	5	-5	1

#,##0.00;;;Nil	5.00	-5.00	0.50	Nil

$#,##0;($#,##0)	$5	($5)	$1

$#,##0.00;($#,##0.00)	$5.00	($5.00)	$0.50

0%	500%	-500%	50%

0.00%	500.00%	-500.00%	50.00%

0.00E+00	5.00E+00	-5.00E+00	5.00E-01

0.00E-00	5.00E00	-5.00E00	5.00E-01


Named Date/Time Formats (Format Function)

The following table identifies the predefined date and time format names:

Format Name	Description

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

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

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

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

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

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

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


User-Defined Date/Time Formats (Format Function)

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

Character	Description

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

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

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

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

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

ddd	Display the day as an abbreviation (Sun-Sat).

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

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

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

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

ww	Display the week of the year as a number (1-53).

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

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

mmm	Display the month as an abbreviation (Jan-Dec).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


User Defined Date/Time Format Examples
User-Defined Date/Time Format Examples

The following are examples of user-defined date and time formats for December 7, 1958:

Format	Display

m/d/yy	12/7/58

d-mm	7-Dec

d-mmmm-yy	7-December-58

d-mmmm	7 December

mmmm-yy	December 58

hh:mm AM/PM	08:50 PM

h:mm:ss a/p	8:50:35 p

h:mm	20:50

h:mm:ss	20:50:35

m/d/yy h:mm	12/7/58 20:50


User-Defined String Formats (Format Function)

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

Character	Description

@	Character placeholder

Display a character or a space.  If the string has a character in the position where the @ appears in the format string, display it; otherwise, display a space in that position.  Placeholders are filled from right to left unless there is an ! character in the format string.  See below.

&	Character placeholder

Display a character or nothing.  If the string has a character in the position where the & appears, display it; otherwise, display nothing.  Placeholders are filled from right to left unless there is an ! character in the format string.  See below.

<	Force lowercase

Display all characters in lowercase format.

>	Force uppercase

Display all characters in uppercase format.

!	Force left to right fill of placeholders

The default is to fill from right to left.


Different Formats for Different String Values
Different Formats for Different String Values (Format Function)

A format expression for strings can have one section, or two sections separated by a semicolon.

If you use	The result is

One section only	The format applies to all string data.

Two sections	The first section applies to string data, the second to Null values and zero-length strings.


Hex Function

Returns a string representing the hexadecimal value of a number.

Syntax

Hex(number)

Elements

The number named argument is any valid numeric expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is	Hex returns

Null	An error.

Empty	Zero (0).

Any other number	Up to eight hexadecimal characters.

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H.  For example, &H10 represents decimal 16 in hexadecimal notation.


InStr Function

Returns the position of the first occurrence of one string within another.

Syntax

InStr([start,]string1,string2[,compare])

Elements

The InStr function syntax has these parts:

Part	Description

start	Numeric expression that sets the starting position for each search.  If omitted, search begins at the first character position.  If start contains no valid data, an error occurs.  Start is required if compare is specified.

string1	String expression being searched.  If string1 contains no valid data, Null is returned.

string2	String expression sought.  If string2 contains no valid data, Null is returned.

compare	Number specifying the type of string comparison.  Specify 1 to perform a textual case-insensitive comparison.  Specify 0 (default) to perform a binary comparison.  If compare is Null, an error occurs.  Start is required if compare is specified.  If compare is omitted, the setting of Option Compare is used to determine the type of comparison.

Return Values

Value	Description

0	string1 is zero-length.

start	string2 is zero-length.

0	string2 not found.

Position at which match is found	string2 is found within string1.

0	start > string2.

Remarks

Note   When Option Compare Text is specified, comparisons are textual and case-insensitive.  When Option Compare Binary is specified, comparisons are strictly binary.

Note   Another function (InStrB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of returning the character position of  the first occurence of one string within another, InStrB  returns the byte position.  In areas where DBCS is not used, InStrB behaves the same as InStr.


LCase Function

Returns a string that has been converted to lowercase.

Syntax

LCase(string)

Elements

The string named argument is any valid string expression.  If string contains no valid data, Null is returned.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.


Left Function

Returns a specified number of characters from the left side of a string.

Syntax

Left(string,length)

Elements

The Left function syntax has these named-argument parts:

Part	Description

string	String expression from which the leftmost characters are returned.  If string contains no valid data, Null is returned.

length	Numeric expression indicating how many characters to return.  If 0, a zero-length string is returned.  If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note   Another function (LeftB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of specifying  the number of characters to return, length specifies the number of bytes.  In areas where DBCS is not used, LeftB behaves the same as Left.


Len Function

Returns the number of characters in a string or the number of bytes required to store a variable.

Syntax

Len(string | varname)

Elements

The Len function syntax has these parts:

Part	Description

string	Any valid string expression.  If string contains no valid data, Null is returned.

varname	Any valid variable name.  If varname contains no valid data, Null is returned.

Remarks

Caution   Len may not be able to determine the actual number of storage bytes required when used with user-defined data types.

Note   Another function (LenB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.  In areas where DBCS is not used, LenB behaves the same as Len.


LSet Statement

Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax

LSet stringvar = string

LSet varname1 = varname2

Elements

The LSet statement syntax has these parts:

Part	Description

stringvar	Name of string variable.

string	String expression to be left aligned within stringvar.

varname1	Variable name of the user-defined type being copied to.

varname2	Variable name of the user-defined type being copied from.

Remarks

LSet replaces any leftover characters in stringvar with spaces.

If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.

Only user-defined types containing Integer, Long, Double, Single, String (fixed-length), or Currency types may be copied.  The following example copies the contents of RecTwo (a user-defined type variable) to RecOne (a variable of another user-defined type):

Type TwoString

StrFld As String * 2

End Type

Type ThreeString

StrFld As String * 3

End Type

Dim RecOne As TwoString, RecTwo As ThreeString

LSet RecOne = RecTwo

Because RecOne is 2 bytes long, only 2 bytes are copied from RecTwo.  LSet copies only the number of bytes in the shorter of the two user-defined type variables.


LTrim, RTrim, and Trim Functions

Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

Syntax

LTrim(string)

RTrim(string)

Trim(string)

Elements

The string named argument is any valid string expression.  If string contains no valid data, Null is returned.


Mid Function

Returns a specified number of characters from a string.

Syntax

Mid(string,start[,length])

Elements

The Mid function syntax has these parts:

Part	Description

string	String expression from which characters are returned.  If string contains no valid data, Null is returned.

start	Character position in string at which the part to be taken begins.  If start is greater than the number of characters in string, Mid returns a zero-length string.

length	Number of characters to return.  If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

Note   Another function (MidB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of specifying  the number of characters to return, length specifies the number of bytes.  In areas where DBCS is not used, MidB behaves the same as Mid.


Mid Statement

Replaces a specified number of characters in a string variable with characters from another string.

Syntax

Mid(stringvar,start[,length]) =string

Elements

The Mid statement syntax has these parts:

Part	Description

stringvar	Name of string variable to modify.

start	Character position in stringvar where the replacement of text begins.

length	Number of characters to replace.  If omitted, all of string is used.

string	String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.


Oct Function

Returns a string representing the octal value of a number.

Syntax

Oct(number)

Elements

The number named argument is any valid numeric expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is	Oct returns

Null	An error.

Empty	Zero (0).

Any other number	Up to 11 octal characters.

You can represent octal numbers directly by preceding numbers in the proper range with &O.  For example, &O10 is the octal notation for decimal 8.


Right Function

Returns a specified number of characters from the right side of a string.

Syntax

Right(string,length)

Elements

The Right function syntax has these named-argument parts:

Part	Description

string	String expression from which the rightmost characters are returned.  If string contains no valid data, Null is returned.

length	Numeric expression indicating how many characters to return.  If 0, a zero-length string is returned.  If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note   Another function (RightB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales.  Instead of specifying  the number of characters to return, length specifies the number of bytes.  In areas where DBCS is not used, RightB behaves the same as Right.


RSet Statement

Right aligns a string within a string variable.

Syntax

RSet stringvar = string

Elements

The RSet statement syntax has these parts:

Part	Description

stringvar	Name of a string variable.

string	String expression to be right aligned within stringvar.

Remarks

RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

RSet can't be used with user-defined types.


Space Function

Returns a string consisting of the specified number of spaces.

Syntax

Space(number)

Elements

The number named argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.


Str Function

Returns a string representation of a number.

Syntax

Str(number)

Elements

The number named argument is any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number.  If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats.  Unlike Str, the Format function doesn't include a leading space for the sign of number.

Note   The Str function recognizes only the period (.) as a valid decimal separator.  When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CStr to convert a number to a string.


StrComp Function

Returns a value indicating the result of a string comparison.

Syntax

StrComp(string1,string2[,compare])

Elements

The StrComp function syntax has these parts:

Part	Description

string1	Any valid string expression.

string2	Any valid string expression.

compare	Number specifying the type of string comparison.  Specify a 1 to perform a textual comparison.  Specify a 0 (default) to perform a binary comparison.  If compare is Null, an error occurs.  If compare is omitted, the setting of Option Compare is used to determine the type of comparison.

Return Values

Value	Description

-1	string1 is less than string2.

0	string1 is equal to string2.

1	string1 is greater than string2.

Null	string1 or string2 is Null.

Remarks

Note   When Option Compare Text is specified, comparisons are textual and case-insensitive.  When Option Compare Binary is specified, comparisons are strictly binary.


String Function

Returns a repeating character string of the length specified.

Syntax

String(number,character)

Elements

The String function syntax has these named-argument parts:

Part	Description

number	Length of the returned string.  If number contains no valid data, Null is returned.

character	Character code specifying the character or string expression whose first character is used to build the return string.  If character contains no valid data, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256


UCase Function

Returns a string that has been converted to uppercase.

Syntax

UCase(string)

Elements

The string named argument is any valid string expression.  If string contains no valid data, Null is returned.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.


Chr Function Example

This example uses the Chr function to return the character associated with the specified character code.

MyChar = Chr(65)	' Returns A.

MyChar = Chr(97)	' Returns a.

MyChar = Chr(62)	' Returns >.

MyChar = Chr(37)	' Returns %.


Format Function Example

This example shows various uses of the Format function to format values using both named and user-defined formats.  For the date separator (/), time separator (:) and AM/ PM literal, the actual formatted output displayed by your system depends on the settings at the time.  When times and dates are listed back in the development environment, the short time and short date formats of the code locale are used.  When displayed by running code, the short time and short date formats of the system locale are used, which may be different from the code locale.  For this example, English - US is assumed.

' MyTime and MyDate will be displayed in the development environment

' using current system short time and short date settings.

MyTime = #17:04:23#

MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.

MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.

MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")	' Returns "17:4:23".

MyStr = Format(MyTime, "hh:mm:ss AMPM")	' Returns "05:04:23 PM".

MyStr = Format(MyDate, "dddd, mmm d yyyy")	' Returns

' "Wednesday, Jan 27 1993".

' If format is not supplied, a string is returned.

MyStr = Format(23)	' Returns "23".

' User-defined formats.

MyStr = Format(5459.4, "##,##0.00")	' Returns "5,459.40".

MyStr = Format(334.9, "###0.00")	' Returns "334.90".

MyStr = Format(5, "0.00%")	' Returns "500.00%".

MyStr = Format("HELLO", "<")	' Returns "hello".

MyStr = Format("This is it", ">")	' Returns "THIS IS IT".


Hex Function Example

This example uses the Hex function to return the hexadecimal value of a number.

MyHex = Hex(5)	' Returns 5.

MyHex = Hex(10)	' Returns A.

MyHex = Hex(459)	' Returns 1CB.


InStr Function Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

SearchString ="XXpXXpXXPXXP"	' String to search in.

SearchChar = "P"	' Search for "P".

' A textual comparison starting at position 4. Returns 6.

MyPos = InStr(4, SearchString, SearchChar, 1)

' A binary comparison starting at position 1. Returns 9.

MyPos = InStr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (if last argument is omitted).

MyPos = InStr(SearchString, SearchChar)	' Returns 9.

MyPos = InStr(1, SearchString, "W")	' Returns 0.


LCase Function Example

This example uses the LCase function to return a lowercase version of a string.

Uppercase = "Hello World 1234"	' String to convert.

Lowercase = LCase(UpperCase)	' Returns "hello world 1234".


Left Function Example

This example uses the Left function to return a specified number of characters from the left side of a string.

AnyString = "Hello World"	' Define string.

MyStr = Left(AnyString, 1)	' Returns "H".

MyStr = Left(AnyString, 7)	' Returns "Hello W".

MyStr = Left(AnyString, 20)	' Returns "Hello World".


Len Function Example

This example uses the Len function to return the number of characters in a string or the number of bytes required to store a variable.

Type CustomerRecord	' Define user-defined type.

ID As Integer

Name As String * 10

Address As String * 30

End Type

Dim Customer As CustomerRecord	' Declare variables.

Dim MyInt As Integer, MyCur As Currency

MyString = "Hello World"	' Initialize.

MyLen = Len(MyInt)	' Returns 2.

MyLen = Len(Customer)	' Returns 42.

MyLen = Len(MyString)	' Returns 11.

MyLen = Len(MyCur)	' Returns 8.


LSet Statement Example

This example uses the LSet statement to left align a string within a string variable and to copy a variable of one user-defined type to another variable of a different user-defined type.

MyString = "0123456789"	' Initialize string.

LSet MyString = "<-Left"	' MyString contains "<-Left    ".

' LSet is also used to copy a variable of one user-defined type to

' another variable of a different user-defined type.

' Module level.

Type AType	' Define types.

AName As String * 10

AAdd As String * 10

End Type

Type BType

BName As String * 5

BAdd As String * 5

End Type

' Procedure level.

Dim AVar As AType, BVar As BType	' Declare variables.

AVar.AName = "John Smith"	' Define fields.

AVar.AAdd = "Rodeo Drv."

LSet BVar = AVar	' Copy variables.

' After copying, values are truncated.

Debug.Print BVar.BName	' Prints "John ".

Debug.Print BVar.BAdd	' Prints "Smith".


LTrim, RTrim, and Trim Functions Example

This example uses the LTrim and RTrim functions to strip leading and trailing spaces from a string variable.  Using the Trim function alone achieves the same result.

MyString = "  <-Trim->  "   	' Initialize.

TrimString = LTrim(MyString)	' TrimString = "<-Trim->  ".

TrimString = RTrim(MyString)	' TrimString = "  <-Trim->".

TrimString = LTrim(RTrim(MyString))	' TrimString = "<-Trim->".

' Using the Trim function alone achieves the same result.

TrimString = Trim(MyString)	' TrimString = "<-Trim->".


Mid Function Example

This example uses the Mid function to return a specified number of characters from a string.

MyString = "Mid Function Demo"	' Create text string.

FirstWord = Mid(MyString, 1, 3)	' Returns "Mid".

LastWord = Mid(MyString, 14, 4)	' Returns "Demo".

MidWords = Mid(MyString, 5)	' Returns "Function Demo".


Mid Statement Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

MyString = "The dog jumps"	' Initialize string.

Mid(MyString, 5, 3) = "fox"	' MyString = "The fox jumps".

Mid(MyString, 5) = "cow"	' MyString = "The cow jumps".

Mid(MyString, 5) = "cow jumped over"	' MyString = "The cow jumpe".

Mid(MyString, 5, 3) = "duck"	' MyString = "The duc jumps".


Oct Function Example

This example uses the Oct function to return the octal value of a number.

MyOct = Oct(4) 	' Returns 4.

MyOct = Oct(8)	' Returns 10.

MyOct = Oct(459)	' Returns 713.


Right Function Example

This example uses the Right function to return a specified number of characters from the right side of a string.

AnyString = "Hello World"	' Define string.

MyStr = Right(AnyString, 1)	' Returns "d".

MyStr = Right(AnyString, 6)	' Returns " World".

MyStr = Right(AnyString, 20)	' Returns "Hello World".


RSet Statement Example

This example uses the RSet statement to right align a string within a string variable.

MyString = "0123456789"	' Initialize string.

RSet MyString = "Right->"	' MyString contains "   Right->".


Space Function Example

This example uses the Space function to return a string consisting of a specified number of spaces.

' Returns a string with 10 spaces.

MyString = Space(10)

' Insert 10 spaces between 2 strings.

MyString = "Hello" & Space(10) & "World"


Str Function Example

This example uses Str to return a string representation of a number.  When a number is converted to a string, a leading space is always reserved for its sign.

MyString = Str(459)	' Returns " 459".

MyString = Str(-459.65)	' Returns "-459.65".

MyString = Str(459.001)	' Returns " 459.001".


StrComp Function Example

This example uses the StrComp function to return the results of a string comparison.  If 1 is supplied as the third argument, a textual comparison is performed; whereas, if the third argument is 0 or omitted, a binary comparison is performed.

MyStr1 = "ABCD": MyStr2 = "abcd"	' Define variables.

MyComp = StrComp(MyStr1, MyStr2, 1)	' Returns 0.

MyComp = StrComp(MyStr1, MyStr2, 0)	' Returns -1.

MyComp = StrComp(MyStr2, MyStr1)	' Returns 1.


String Function Example

This example uses the String function to return repeating character strings of the length specified.

MyString = String(5, "*")	' Returns "*****".

MyString = String(5, 42)	' Returns "*****".

MyString = String(10, "ABC")	' Returns "AAAAAAAAAA".


UCase Function Example

This example uses the UCase function to return an uppercase version of a string.

LowerCase = "Hello World 1234"	' String to convert.

UpperCase = UCase(LowerCase)	' Returns "HELLO WORLD 1234".


Character Set (128 - 255)

 128	•	 160	[space]	 192	À	 224	à

 129	•	 161	¡	 193	Á	 225	á

 130	•	 162	¢	 194	Â	 226	â

 131	•	 163	£	 195	Ã	 227	ã

 132	•	 164	¤	 196	Ä	 228	ä

 133	•	 165	¥	 197	Å	 229	å

 134	•	 166	¦	 198	Æ	 230	æ

 135	•	 167	§	 199	Ç	 231	ç

 136	•	 168	¨	 200	È	 232	è

 137	•	 169	©	 201	É	 233	é

 138	•	 170	ª	 202	Ê	 234	ê

 139	•	 171	«	 203	Ë	 235	ë

 140	•	 172	¬	 204	Ì	 236	ì

 141	•	 173	­	 205	Í	 237	í

 142	•	 174	®	 206	Î	 238	î

 143	•	 175	¯	 207	Ï	 239	ï

 144	•	 176	°	 208	Ð	 240	ð

 145	‘	 177	±	 209	Ñ	 241	ñ

 146	’	 178	²	 210	Ò	 242	ò

 147	•	 179	³	 211	Ó	 243	ó

 148	•	 180	´	 212	Ô	 244	ô

 149	•	 181	µ	 213	Õ	 245	õ

 150	•	 182	¶	 214	Ö	 246	ö

 151	•	 183	·	 215	×	 247	÷

 152	•	 184	¸	 216	Ø	 248	ø

 153	•	 185	¹	 217	Ù	 249	ù

 154	•	 186	º	 218	Ú	 250	ú

 155	•	 187	»	 219	Û	 251	û

 156	•	 188	¼	 220	Ü	 252	ü

 157	•	 189	½	 221	Ý	 253	ý

 158	•	 190	¾	 222	Þ	 254	þ

 159	•	 191	¿	 223	ß	 255	ÿ

•	These characters aren't supported by Microsoft Windows.


Glossary

A

ANSI Character Set

argument

array

ASCII Character Set

automatic formatting

B

bit-wise comparison

Boolean expression

break mode

breakpoint

by reference

by value

C

character code

Clipboard

close box

collection

comment

comparison operator

compile time

constant

Control Panel

Control-menu box

D

data type

data type ranges

date expression

date literal

date separators

dates and times

declaration

dynamic-link library (DLL)

E-F-G

Empty

error number

expression

file number

H-I-J-K

host application

insertion point

keyword

L

line label

line number

line-continuation character

locale

logic error

M

member

method

module

module level

module variable

N

named argument

Null

numeric expression

numeric type

O-P-Q

object expression

object type

parameter

path

pathname

pi

print zone

procedure

procedure level

project

property

R

referenced project

run time

run-time error

S

scope

seed

sort order

split bar

statement

string comparison

string constant

string expression

string literal

string type

syntax checking

syntax error

T

time expression

title bar

type-declaration character

U

universal date format

user-defined type

V

variable

variable name

VarType

W-X-Y-Z

wait mode

watch expression


Arrays Keyword Summary

See Also

Action	Keywords

Verify an array.	IsArray

Create an array.	Array

Change default lower limit.	Option Base

Declare and initialize an array.	Dim, Public, Private, ReDim, Static

Find the limits of an array.	LBound, UBound

Reinitialize an array.	Erase, ReDim


Conversion Keyword Summary

See Also

Action	Keywords

ANSI value to string.	Chr

Convert to lowercase or uppercase.	Format, LCase, UCase

Date to serial number.	DateSerial, DateValue

Decimal number to other bases.	Hex, Oct

Number to string.	Format, Str

One data type to another.	CBool, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr,Fix, Int

Serial number to date.	Date, Month, Weekday, Year

Serial number to time.	Hour, Minute, Second

String to ASCII value.	Asc

String to number.	Val

Time to serial number.	TimeSerial, TimeValue


Data Types Keyword Summary

See Also

Action	Keywords

Convert between data types.	CBool, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr,Fix, Int

Setting intrinsic data types.	Boolean, Integer, Long, Currency, Single, Double, Date, String, Object, Variant (default)

Verifying data types.	IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject


Dates and Times Keyword Summary

See Also

Action	Keywords

Get the current date or time.	Date, Now, Time

Return a date.	DateSerial, DateValue

Return a time.	TimeSerial, TimeValue

Set the date or time.	Date, Time

Time a process.	Timer


Control Flow Keyword Summary

See Also

Action	Keywords

Branch.	GoSub...Return, GoTo, On Error, On...GoSub, On...GoTo

Exit or pause the program.	DoEvents, End, Stop

Loop.	Do...Loop, For...Next, For Each...Next, While...Wend

Make decisions.	If...Then...Else, Select Case


Directories and Files Keyword Summary

See Also

Action	Keywords

Change directory or folder.	ChDir

Change the drive.	ChDrive

Copy a file.	FileCopy

Make directory or folder.	MkDir

Remove directory or folder.	RmDir

Return current path.	CurDir

Return file, directory, label attributes.	GetAttr

Return file name or volume label.	Dir

Return file date/time stamp.	FileDateTime

Rename a file, directory, or folder.	Name

Set attribute information for a file.	SetAttr


Errors Keyword Summary

See Also

Action	Keywords

Get error messages.	Error

Get error-status data.	Erl, Err

Simulate run-time errors.	Error

Trap errors during run time.	On Error, Resume

Type verification.	IsError

Return Error variant.	CVErr


Input and Output Keyword Summary

See Also

Action	Keywords

Access or create a file.	Open

Close files.	Close, Reset

Control output appearance.	Format, Print, Print #, Spc, Tab, Width #

Copy a file.	FileCopy

Get information about a file.	EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF, Seek

Manage files.	Dir, Kill, Lock...Unlock, Name

Read from a file.	Get, Input, Input #, Line Input #

Return length of a file.	FileLen

Set or get file attributes.	FileAttr, GetAttr, SetAttr

Set read-write position in a file.	Seek

Write to a file.	Print #, Put, Write #


Math Keyword Summary

See Also

Action	Keywords

Derive trigonometric functions.	Atn, Cos, Sin, Tan

General calculations.	Exp, Log, Sqr

Generate random numbers.	Randomize, Rnd

Get absolute value.	Abs

Get the sign of an expression.	Sgn

Perform numeric conversions.	Fix, Int


Miscellaneous Keyword Summary

See Also

Action	Keywords

Process pending events.	DoEvents

Run other programs.	AppActivate, Shell

Send keystrokes to an application.	SendKeys

Sound a beep from computer.	Beep


Operators Keyword Summary

See Also

Action	Keywords

Arithmetic.	^, -, *,  /, \, Mod, +, &

Comparison.	=, <>, <, >, <=, >=, Like, Is

Logical operations.	Not, And, Or, Xor, Eqv, Imp


String Manipulation Keyword Summary

See Also

Action	Keywords

Compare two strings.	StrComp

Convert to lowercase or uppercase.	Format, LCase, UCase

Create string of repeating character.	Space, String

Find length of a string.	Len

Format a string.	Format

Justify a string.	LSet, RSet

Manipulate strings.	Instr, Left, LTrim, Mid, Right, RTrim, Trim

Set string comparison rules.	Option Compare

Work with ASCII and ANSI values.	Asc, Chr


Variables and Constants Keyword Summary

See Also

Action	Keywords

Assign value.	Let

Declare variables or constants.	Const, Dim, Private, Public, Static

Declare module as private.	Option Private Module

Get information about a variant.	IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject, TypeName, VarType

Require explicit variable declarations.	Option Explicit

Set default data type.	Deftype


Trappable Errors

Trappable errors can occur while an application is running.  Some of these can also occur during development or compile time.  You can test and respond to trappable errors using the On Error statement and the Err function.

Code	Message

3	Return without GoSub

5	Invalid procedure call

6	Overflow

7	Out of memory

9	Subscript out of range

10	Duplicate definition

11	Division by zero

13	Type mismatch

14	Out of string space

16	String formula too complex

17	Can't perform requested operation

18	User interrupt occurred

20	Resume without error

28	Out of stack space

35	Sub or Function not defined

48	Error in loading DLL

49	Bad DLL calling convention

51	Internal error

52	Bad file name or number

53	File not found

54	Bad file mode

55	File already open

57	Device I/O error

58	File already exists

59	Bad record length

61	Disk full

62	Input past end of file

63	Bad record number

67	Too many files

68	Device unavailable

70	Permission denied

71	Disk not ready

74	Can't rename with different drive

75	Path/File access error

76	Path not found

91	Object variable not set

92	For loop not initialized

93	Invalid pattern string

94	Invalid use of Null

95	User-defined error

323	Can't load module; invalid format

423	Property or method not found

424	Object required

430	Class does not support OLE Automation

438	Object doesn't support this property or method

440	OLE Automation error

445	Object doesn't support this action

446	Object doesn't support named arguments

447	Object doesn't support current locale setting

448	Named argument not found

449	Argument not optional

450	Wrong number of arguments

451	Object not a collection

452	Invalid ordinal

453	Specified DLL function not found

454	Code resource not found

455	Code resource lock error


Keyword Not Found

The keyword you've selected can't be found in Visual Basic Help. You may have misspelled the keyword, selected too much or too little text, or asked for help on a word that is not a valid Visual Basic keyword.

The easiest way to get help on a specific keyword is to position the insertion point anywhere within the keyword you want help on and press F1. You do not need to select the keyword. In fact, if you select only a portion of the keyword, or more than a single word, Help will not find what you're looking for.

The Value property topic is displayed when you press F1 with the insertion point between the "a" and the "l" in the Value keyword as shown in the following example.

To use the built-in Help search dialog box, press the "Help Topics" button on the toolbar.