You are on page 1of 18

Array Statements & Functions

Statement
What it Does
Array(arguments)
Returns aVariant data item
that contains an array.

Dim
Erase arraylist

LBound (arrayname[, dimension])

Option Base [0|1]


ReDim [Preserve]
[varname(subscripts) _
[As type]][, varname(subscripts) _
[Astype]][,...
Static [varname(subscripts) _
[As [New]type]] _
[, varname(subscripts) _
[As [New]type]] ...
Ubound(arrayname[, dimension])

Reinitializes elements in
one or more fixed-size
arrays and frees up the
dynamic-array storage
space occupied by the
array(s).
Returns a Long value that s
the smallest subscript for a
dimensioned array
(arrayname).
Declares the default lower
bound of array subscripts.
Redimensions one or more
dynamic array variables and
reallocates their storage
space.
Declares one or more static
variables that retain their
values as long as the
program is running.
Returns a Long value that's
the largest subscript for a
dimensioned array
(arrayname).

Conversion Functions
Use:
To Convert:
CBool(expression Any Variant argument
)
CByte(expression Any Variant argument
)
CCur(expression) Any Variant argument
CDate(expression Any Variant argument
)
CDbl(expression) Any Variant argument
CDec(expression) Any Variant argument
CInt(expression)
Any Variant argument
CLng(expression)
CSng(expression)
CStr(expression)

Any Variant argument


Any Variant argument
Any Variant argument

CVar(expression)

Any Variant argument

Hex(expression)

A Numeric argument

Int(expression)

A Numeric argumen
t
A Numeric argument

Str(expression)

Comments
arguments refers to a comma-delimited list of values that
are the elements of the array; the first value corresponds
to the first array element, the second value to the second
array element, etc.
See Entry in Declaration Statements
arraylist is one or more comma-delimited array names.

For multidimensional arrays, dimensionis included to


specify which dimension should be used.

Option Base can only be used at module level.


(optional) Preserve is used to keep the contents of
the array intact when it's being
redimensioned. varname is the variable name,
and Astype(optional) indicates its data type.
subscripts are the dimensions of the array variable.
varname is the variable name, and (optional) As
[New]type is its data type. If New is used, then an
implicit creation of the object is made.
(optional) subscripts are the array's dimensions
For multidimensional arrays, dimensionis included to
specify which dimension should be used.

To :
An equivalent Boolean data type

Comments
expression can be a string
or numeric

An equivalent Byte data type


An equivalent Currency data type
An equivalent Date data type
An equivalent Double data type
A Decimal
Rounds the fractional part of the argument to the
next highest Integer
An equivalent Long data type
An equivalent Single data type
Depends on the data type of
theexpressionargument:
ForBooleans,CStr returns Trueor False.
For Dates,it returns a date based on the
short date format on your system.
For Errors, it returns the word "Error"
followed by the error
number.Numericexpression values return a
string containing the number.
An equivalent Variant data type
A Hexadecimal (Base 16) number
equivalent
A number rounded down to the integer less than
or equal to its argument
A Variant that can be used as a string.

The string
that CStrreturns
ifexpression isEmpty is
a zero-length string. If
theexpression has
aNull value, a runtime
error will result.

expression can be a string


or numeric

Adds a leading blank


before positive numbers

that Cstr() does not


Oct(expression)
Val(string)

A Numeric argumen
t
A String argument

An Octal(Base 8) number equivalent


Numeric

Data Inspection Functions


Function
What it Does
IsArray(varname)
Returns a Boolean indicating whethervarnameis an Array.
IsDate(varname)
Returns a Boolean indicating whethervarnameis capable
of being converted toDate.
IsEmpty(varname)
Returns a Boolean indicating whethervarnamehas been
initialized.
IsError(varname)
Returns a Boolean indicating whethervarnameis an Error.
IsMissing(vntname)
Returns a Boolean indicating whether an
optional Variant(vntname) has been passed to a procedure.
IsNull(varname)
Returns a Boolean indicating whethervarnamecontains
no data or is Null.

IsNumeric(varname)

If the string does not


contain numeric data, then
the Valfunction returns a
zero

Comments

Use this for both number and string


variables
Returns True if no value has
been provided for vntname
You cannot test for a Null value
by using a statement like:
If (vntB = NULL)
This latter test will always fail.

Returns a Boolean indicating whethervarnamecan be


evaluated as a Numeric.
IsObject(varname)
Returns a Boolean indicating whethervarnamerepresents
an Object
Date/Time Statements and Functions
Function
What It Does
Comments
Date = Date
Sets the current system date as
For Windows 9x systems, Date must be a valid
specified in Date
date between 1 Jan 80 and 31 Dec, 2099. For NT
systems: between 1 Jan 80 and 31 Dec 2079
Date()
Returns a Variant that holds the
current system date
Returns a new date after a value is
DateAdd(interval, _
added to a date
numbercode, oldDate)
DateDiff(interval, _
Returns a Variant that represents the interval returns a code that represents the time
date1, date2_
difference between two dates.
unit. firstdayofweekandfirstweekofyear are used
[,firstdayofweek]_[,firstweekofyear
to specify how the date should be calculated
])
when certain codes are used
Returns part (an element) from a
interval returns a code that represents the time
DatePart(interval, date_
[,firstdayofweek]_[,firstweekofyear given date.
unit. firstdayofweekandfirstweekofyear are used
])
to specify how the date should be calculated
when certain codes are used
DateSerial(year, month, day)
Returns a Variant containing the
Year, month, and day are numeric values.
internal representation of a date or
time.
DateValue(stringDate)
Returns a Variant containing the
internal representation of a date or
time based on stringDate.
Day(date)
Returns a Variant which represents
Sunday is 1, Monday is 2, Tuesday is 3, etc.
the conversion of date to a day
number
Hour(time)
Returns a Variant of subtype Integer
representing the hour (0-23)
component of the time value
specified by time.
Minute(time)
Returns a Variant representing the
minute component (0-59) of the time
value specified by time.
Month(date)
Returns a Variant representing the
month number (1-12) component of
date value specified by date.
Now()
Returns today s date as a Variant

Second(time)

Time
Time = time
Timer

TimeSerial(hour, minute, second)


TimeValue(stringTimeExpression)
Weekday (date,[firstdayofweek])

Year(date)
Declaration Statements
Statement
[Public|Private]
Const constname_
[As type] = expression
[Public|Private]Declare
Sub name _
Lib "libname" _
[Alias "aliasname"] _ [arglist]

DefBool letterrange[, letterrange]. .


.

DefByte letterrange[,
letterrange]. . .

DefCur letterrange[, letterrange]. . .

DefDate letterrange[,
letterrange]. . .

DefDbl letterrange[, letterrange]. . .

Returns a Variant representing


the second component (0-59) of the
time value specified by time.
Returns Variant containing the
current system time.
Sets the system time to the time
specified by the time argument.
Returns Single representing the
number of seconds that have elapsed
since midnight.
Similar to DateSerial, only this
one works on time
Similar to DateValue, only this
one works on time.
Returns, as a Variant, the number of
the day of the week for the
given date
Returns a Variant which is the year
for the value specified by date
What It Does
Declares a constant with the
name constantname and
assigns it the value of
expression
Declares references
to Subor Function proced
ures in an external DLL
(dynamic-link library).

Declares all variables and


function return values
beginning with the letters
specified by letterrangeare
automatically defined
asBoolean
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asByte
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asCurrency
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asDate
Declares all variables and
function return values
beginning with the letters
specified by letterrange are

If firstdayofweek is not specified, Sunday is 1,


Monday is 2, Tuesday is 3, etc.

Comments
If As type is missing, the constant will be assigned a
data type matching that of expression

Public and Private define the procedure's


scope. name is the procedure's
name, and libnamespecifies the DLL containing
the procedure. aliasname specifies an alternate
name for the procedure in the DLL. arglist is an
argument list passed to the procedure. For
Function procedures, the As type specifies the
data type of the value returned by the
Function. Declare statements can only be used
at module level.
Each letterrange should be constructed as
letter1[-letter2], whereletter1 is the first (or only)
letter in the range, and letter2 is the last letter in
the range. DefBool can only be used at module
level.
Each letterrange should be constructed as
letter1[-letter2], whereletter1 is the first (or only)
letter in the range, and letter2 is the last letter in
the range. DefByte can only be used at module
level.
Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefCur can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefDate can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefDbl can only be used at module level.

automatically defined
asDouble

DefDec letterrange[, letterrange]. . .

DefInt letterrange[, letterrange]. . .

DefLng letterrange[, letterrange]. . .

DefObj letterrange[, letterrange]. . .

DefSng letterrange[, letterrange]. . .

DefStr letterrange[, letterrange]. . .

DefVar letterrange[, letterrange]. . .

Dim
[WithEvents] varname(subscripts)
_
[As[New]type] [,[WithEvents] _
varname(subscripts)
[As[New] type]]...

[Public|Private]
Enum namemember-1_
[= constantexpression] member-2_
[= constantexpression] _
...

Declares all variables and


function return values
beginning with the letters
specified by letterrange are
automatically defined
asDecimal
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asInteger
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asLong
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asObject
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asSingle
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asString
Declares all variables and
function return values
beginning with the letters
specified by letterrange are
automatically defined
asVariant
Declares one or more
variables or objects.

Declares name an
enumeration composed of
one or more members
(member-1, member-2,
. . . , member-n )

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefDec can only be used at module level.

Each letterrange should be constructed as


letter1[-letter2], whereletter1 is the first (or only)
letter in the range, and letter2 is the last letter in
the range. DefInt can only be used at module
level.
Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefLng can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefObj can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefSng can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.DefStr can only be used at module level.

Each letterrange should be constructed as letter1[letter2], where letter1 is the first (or only) letter in
the range, and letter2 is the last letter in the
range.Defvar can only be used at module level.

varname is the variable name, and As


[New] type (optional) indicates its data type.
If New is used, then an implicit creation of the
object is made.WithEvents (optional) valid only
when the Dim statement is used in class
modules indicates varname is an object variable
that responds to events triggered by an ActiveX
object.subscripts (optional) are the dimensions of
an array variable.
Members can be assigned values
using constantexpression. Public andPrivate (op
tional) define the enumeration's scope.

[Public]Event procname[(arglist)]

Declares a user-defined event


with the name specified
byprocname.

Public indicates the Event will be visible


throughout the project (the default). (arglist)
(optional)should contain one or more arguments
defined using the syntax:
[ByVal | ByRef]varname _
[As type]

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

Declares the various parts of a


Function procedure..

where varname is the argument name,As type is


the data type of the argument, and
(optional) ByRef orByVal specify whether the
argument should be passed by reference or by
value. If ByRef and ByVal are not specified, then
the argument will be passed by reference. (In
VB.NET, the argument will be passed ByVal)
(optional) Public,Private, and Friendare used to
define the Function's scope, and
(optional) Static indicates that the procedure's
local variables are preserved between calls to
theFunction. name specifies
theFunction procedure and is assigned a value
(name = expression) that's returned by the
procedure. As typespecifies the return value's
data type. (optional) Exit Function is used to
immediately exit the Functionprocedure.
(optional) arglist defines the arguments that will
be passed to the procedure. Arguments use the
following syntax:
[Optional] _
[ByVal|ByRef] _ [ParamArray] _
varname() [As type] _
[=default value]
where Optional specifies that the argument is
not required (default valueassigns the
argument's default),ByVal and ByRef determine
whether the argument is passed by value (default
in VB.NET) or by reference (default in VB6),
and ParamArrayspecifies that the argument is
an Optional array of Variant
elements.ParamArray is only used with the last
argument in the argument list.

Implements[interfacename|class]

Option Compare(Binary|Text|
Database)
Option Explicit

Option Private

Private [WithEvents] _
varname(subscripts) _
[As[New]type] [,[WithEvents] _
varname(subscripts) _
[As[New]type]]...

Specifies an interface
(interfacename) or class
(class) that ll be used in the
class module where
theImplements statement
is used.
Declares the default method
used for string comparisons.
Forces all variables to be
explicitly declared
in Dimstatements
Prevents a module's contents
(i.e., variables and objects)
from being used outside its
project.
Declares one or more Private
variables. Triggered by an
ActiveX object. The Private
statement can only be used at
module level, and variables

Option Compare can only be used at module


level.

Option Private is only necessary when working


with host applications that allow variables and
objects to be referenced across multiple projects.
varname specifies the name of the variable
being declared, and subscripts are the array
variable's dimensions. As [New] type (optional)
is used to specify the variable's data type, with
New enabling implicit creation of an

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

declared with it cannot be


used outside their own
module.

object. WithEvents(optional) specifies that the


variable being declared is used to respond to
events

Declares the various parts


of a Property
Getprocedure, which is
used to obtain the value of
a property.

(optional ) Public, Private, andFriend keywords


define the procedure's scope, and
(optional)Static states that the procedure's local
variables are to be preserved between procedure
calls. namespecifies the property to be retrieved
and is assigned a value (name =expression) to
be returned as the property's value. The
property's data type is specified using As type.
(optional) Exit Property is used to immediately
exit the Property Getprocedure. The optional
(arglist) defines the arguments that will be
passed to the procedure. Those arguments
should use the following syntax:
[Optional] [ByVal|ByRef] _
[ParamArray] varname[()] _
[As type] [=default value]

[Public|Private|Friend] _
[Static]Property
Let name([arglist,]value)
[statements]
[ExitProperty]
[statements]
End Property

Declares the various parts


of a Property
Letprocedure, which is
used to obtain the value of
a property.

where Optional specifies the argument is not


required (default valueassigns the argument's
default),ByVal and ByRef indicate the argument
is to be passed by value (default in VB.NET) or
by reference (default in VB6),
and ParamArrayspecifies the argument is an
Optional Variant array . ParamArray is only used
with the last argument in the argument list.
(optional ) Public, Private, andFriend keywords
define the procedure's scope, and
(optional)Static states that the procedure's local
variables are to be preserved between procedure
calls. namespecifies the property to be retrieved
and is assigned a value (name =expression) to
be returned as the property's value. The
property's data type is specified using As type.
(optional) Exit Property is used to immediately
exit the Property Letprocedure. The optional
(arglist) defines the arguments that will be
passed to the procedure. Those arguments
should use the following syntax:
[Optional] [ByVal|ByRef] _
[ParamArray] varname[()] _
[As type] [=default value]
where Optional specifies the argument is not
required (default valueassigns the argument's
default),ByVal and ByRef indicate the argument
is to be passed by value (default in VB.NET) or
by reference (default in VB6),
and ParamArrayspecifies the argument is an
Optional Variant array. ParamArray is only used
with the last argument in the argument list.

[Public|Private|Friend] [Static] _
Property Set name [(arglist)][As ty
pe]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property

Declares the various parts


of a Property
Setprocedure, which is
used to obtain the value of
a property.

(optional ) Public, Private, andFriend keywords


define the procedure's scope, and
(optional)Static states that the procedure's local
variables are to be preserved between procedure
calls. namespecifies the property to be retrieved
and is assigned a value (name =expression) to
be returned as the property's value. The
property's data type is specified using As type.
(optional) Exit Property is used to immediately
exit the Property Setprocedure. The optional
(arglist) defines the arguments that will be
passed to the procedure. Those arguments
should use the following syntax:
[Optional] [ByVal|ByRef] _
[ParamArray] varname[()] _
[As type] [=default value]

Public [WithEvents] _
varname[subscripts] _
[As[New]type] [,[WithEvents] _
varname[subscripts]
[As[New]type]]...

Declares one or more Public


variables.
The varnameargument
specifies the name of the
variable being declared, and
subscripts are the dimensions
for an array variable.

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

Declares the various parts


of a Sub procedure.

where Optional specifies the argument is not


required (default valueassigns the argument's
default),ByVal and ByRef indicate the argument
is to be passed by value (default in VB.NET) or
by reference (default in VB6),
and ParamArrayspecifies the argument is an
Optional Variant array . ParamArray is only used
with the last argument in the argument list.
(optional) As [New] type is used to specify the
variable's data type, withNew enabling implicit
creation of an object.
(optional ) WithEventsspecifies the variable
declared is an object variable used to respond to
events triggered by an ActiveX object.
The Public statement can only be used at
module level, and variables declared with it can
be used outside their own module.
(optional) Public, Private, and Friendare used
to define the Sub's scope, and
(optional) Static indicates that the procedure's
local variables are preserved between calls to
the Sub.name specifies the name of
the Subprocedure. (optional) Exit Sub is used to
immediately exit the Subprocedure.
The optional list (arglist) defines what arguments
will be passed to the procedure. Those
arguments must use the following syntax:
[Optional] [ByVal|
ByRef] _[ParamArray] varname[()] _
[As type] [=default value]

[Private|Public] Type varname _


elementname(subscripts) As type]
_

Defines a user-defined type


(UDT) structure that contains
one or more elements

where Optional specifies the argument is not


required (default valueassigns the argument's
default),ByVal and ByRef control whether the
argument is passed by value (default in VB.NET)
or by reference (default in VB6),
and ParamArray specifies the argument is
an Optional array of Variant
elements. ParamArray is only used with the last
item in an argument list.
(optional) Public and Private specify the UDT's
scope, and varname is theUDT's name.
Elements can be arrays (by

[elementname(subscripts) As type]
...
End Type

(elementname).

specifying subscripts), and their data type must


be defined using theAs type clause.
The Type statement can only be used at module
level.

Error Handling Statements & Functions


Function
What it Does to the Argument
CVErr(errornumber)
Returns a Variant containing an error number
Error errornumber
Forces an error to occur.
Error(errornumber)

Comments
errornumber indicates the type of
error that should occur.

Returns a string value containing the error message that


corresponds toerrornumber
On Error GoTo line
When an error results, the statement at the label or line
number specified by line is jumped to immediately
On Error Resume Next When an error results the program continues on to the next
line of code rather than jumping elsewhere
On Error GoTo 0
Disables all error handling
File, Folder and Directory Statements
Statement
What it Does
Comments
ChDir path
Changes the current directory to Changes only the directory, not the drive
the one specified by path
Changes the current drive to the Changes only the drive, not the directory
ChDrive drive
one specified by drive
Close filenumberlist
Closes any files opened with
Files closed correspond to the numbers specified
the Open statement
in filenumberlist
Copies the filename and path
FileCopy source, dest
specified by source to the
filename and path specified by
dest
Get [#]filenumber_
Reads data from an open disk
Works with files open as Random or Binary. For Random
{, recnumber} varname
file corresponding
files, a record number, recnumber, must be specified. For
to filenumber into a variable
Binary files, recnumber is used to specify the byte
specified by varname
position from which the data s to be read
Reads data from the open file
varlistcontains one or more comma- delimited variables
Input #filenumber, _varlist
associated with
the filenumberargument and
places it in the varlist argument
Kill pathname
Deletes the file(s) or directory
pathname can contain wildcards
represented by pathname
Reads a line of data (ending
Line
The data is stored in a String or Variantspecified
with a carriage return or
Input #_filenumber, varname
by varname
linefeed) from the open file
corresponding tofilenumber
Lock [#] filenumber_
Prevents another process from
recnumber specifies the recordnumber (for Random files)
[,recnumber | start To end]
accessing all or part of the open or byte position (for Binary files) where locking should
file corresponding to
begin.
the filenumber
Alternatively, start To end specifies the range of records
(or bytes) that should be locked.
Load object
Loads an object, such as a
form or control, into memory.
MkDir path
Creates the new directory or
folder specified by path
Renames the file, directory, or
Name oldpath As newpath
folder specified by oldpathto
one specified by newpath
Open strfilename _
Opens a file for input or output
strfilename is a string value or variable containing a file
[For mode] As #intfilenumber
and assigned it to a
name. mode must beAppend, Input, or Output
given intfilenumber

Print # filenumber_
[Spaces(n)|Tab(n)]_
[expression][charpos]

Put [#] filenumber_


[, recnumber], varname

Writes data to the open


sequential file that corresponds
to filenumber

Spaces specifies that the printer should write n spaces.


Tab indicates that the carriage return should be advanced
to the nth character position. expressioncan be used to
specify the data to be written and charpos can specify the
insertion position for the next character.

Writes data to the open disk file


associated with filenumber from
a variable varname
Reset
Closes all files opened with an
Writes buffer contents (if any) to disk before closing
Open statement
Removes the directory or folder
RmDir path
specified by path
Seek [#]filenumber, _position
Sets the record or
byte position of the open file
associated with filenumber
When dealing with Random files, Seek returns the
Seek (filenumber)
Returns a Long specifying the
number of the next record to be read or written. For all
current record or byte position
other file types, Seek returns a byte position.
for the open file associated
withfilenumber.
Sets attributes for the file or
Attributes are specified by VB constants
SetAddr pathname, attributes
directory specified
(vbNormal,vbReadOnly, vbArchive,vbSystem,
by pathname
vbHidden,vbDirectory)
Unload object
Unloads an object (such as a
form or control) from memory
and frees up any resources
being used by the object.
Removes locking that prevents
For Random files, recnumber is the record number; for
Unlock [#]filenumber_
another process from accessing Binary files, it's the byte position. Alternatively, starting
[, recnumber|[start]To end)]
all or part of the open file
or ending record numbers (for Random files) or byte
designated by filenumber
positions (for Binary files) can be specified.
Width #filenumber, width
Specifies the output line
character width for the open file
corresponding to filenumber
Writes data to the open
The outputlist should contain one or more commaWrite # filenumber, [outputlist]
sequential file corresponding
delimited variables that constitute what s to be output to
to filenumber
the file
File, Folder and Directory Functions
File, Folder, and Directory Functions
Function
What it Does
Comments
Dir(pathname_
Returns a String value containing the When the Dir function is first called, it returns the
[, attributes])
name of a file, directory, or folder
name of a file based on the pathname and
matching the pattern
attributes arguments. If the function is called again and
specified pathnameand/or a file
no arguments are given, it returns the second file
attribute (as specified in attributes). name for the givenpathname and attributes, etc.
EOF(filenumber)
Returns a True or False value
(Integer) indicating whether the
end of file marker has been
reached for the Random or Input
file associated filenumber.
FileAttr(filenumber,
Returns a Long value representing
filenumber is the file number for the open file, and
_ returntype)
the file mode for a file opened via the returntypeis the type of information to be returned..
Possible values returned by the FileAttr function for
Open statement.
indicating file type are: 1 for Input, 2 for Output, 4 for
Random, 8 for Append, and 32 for Binary.
FileDateTime()
Returns a Variant that gives the date
and time when the file specified
by pathnamewas lastmodified.
FileLen()
Returns a Long value giving the size
(in bytes) of the file specified
by pathname.
rangenumber (optional) is used to specify which range of
FreeFile[rangenumber] Returns an Integer value the
file numbers should be used: 0 (the default) for file
represents the next file number
numbers in the range of 1-255, or 1 for file numbers in the
available for use with the Open
range of 256-511.
statement.

GetAttr(pathname)

LoadPicture( _
[stringexpression])

Returns an Integer value that


represents the attributes for the file,
directory, or folder specified
by pathname.
Loads the image specified
bystringexpressionand returns it.

LoadResData(index,
_ format)

Loads data from the resource (.RES)


file with the identifier of index

LoadResPicture _
(index,format)

Loads a bitmap, icon, or cursor from


the resource (.RES) file with the
identifier ofindex.

LoadResString(index)

Loads a string from the resource


(.RES) file with the identifier
of index.
Returns a Long value that s the
current byte position within the open
file that corresponds to filenumber.
Returns a Boolean value that's the
byte size of the open file that
corresponds tofilenumber.
Saves an graphic image from an
object's Picture or Image property to
a file.

Loc(filenumber)

LOF(filenumber)

SavePicture picture,
_stringexpression

Financial Functions
Function
DDB(cost, salvage, _
life,period[, factor])

FV(rate, nper, pmt[,pv[,type]])

IPmt (rate, per,nper, pv[,fv[, type]])

IRR[values()[, guess]]

MIRR(values(), finrate, reinvrate)

To determine which attributes are set, the value


returned can be compared bitwise with various VB
constants (vbNormal, vbReadOnly, vbHidden,
vbSystem, vbDirectory, and vbArchive).
Permits pictures to be loaded and assigned to a
Form's Picture property, a PictureBox control, or an
Image control. If nostringexpression argument is
given, then LoadPicture returns an empty picture.
format is the format of the data (1 = cursors, 2 =
bitmaps, 3 = icons, 4 = menus, 5 = dialog boxes, 6 =
strings, 7 = font directories, 8 = fonts, 9 = accelerator
tables, 10 = user-defined resources, 12 = group
cursors, and 14 = group icons). Data returned
byLoadResData can be assigned to a variable or
object of the appropriate type.
format specifies the format of the data (0 = bitmaps, 1
= icons, and 2 = cursors). The data returned
byLoadResPicture can be assigned to an object of
the appropriate type.
The string that is returned can be assigned to
a String or Variant.

picture specifies the control from which the graphics file


(Picture or Image) is to be created ,
andstringexpression specifies the path and filename to
which the image is saved.

What It Does
Returns a Double value that s an
asset s depreciation for a specified
time using a given method of
depreciation.

Returns a Double value that


represents the future value of an
annuity based on a number of
periodic fixed payment amounts
(pmt) and a fixed interest rate
(rate)
Returns a Double value that
indicates the interest payment for a
fixed-period annuity based on a
number (nper) of periodic fixed
payments (per) and a fixed interest
rate (rate).
Returns a Double value indicating
the internal rate of return for an
array ofvalues that represent cash
flow.
Returns a Double value that s the
modified internal rate of return for
an array of values representing
cash flow.

Comments
cost is the asset's initial cost, salvage is the asset's
value at the end of its working lifetime, life is the
asset's lifetime, and period is the period (in
months) for which the depreciation is
calculated. factor(optional) is the rate the
balance declines if it's is omitted, then the
double-declining depreciation method is used.
The pv argument specifies a present value or lump
sum of a series of future payments, and type
specifies when payments are due. Defaults to 0 for
end of payment. 1 represents the beginning of the
payment period.
pv specifies the present value of a series of
payments.fv (optional) specifies the future value or
cash balance left after the final
payment.type (optional) specifies when payments
are due (0 = end of the payment period, the default;
1 = beginning of the payment period).
The values() array must contain at least one
negative value (payment) and one positive value
(receipt). guess (optional) specifies an estimate to
be returned by IRR (default estimate is .1).
The values() array must contain at least one
negative value (payment) and one positive value
(receipt). The finrate argument is the interest rate
paid for financing, and reinvrate is the interest
rate received on gains from cash
reinvestment.

Nper (rate, pmt,pv[, fv[,type]])

Returns a Double value that


indicates the number of periods for
an annuity based on periodic fixed
payments (pmt) and a fixed interest
rate (rate).

NPV(rate, values ())

Returns a Doublevalue
representing the present value of
an investment based on a discount
rate (rate) and an array of
valuesthat represent cash flow.
Returns a Double value that
indicates the payment for an
annuity based on a number
(nper)of periodic fixed payments
and a fixed interest rate (rate).

Pmt(rate, nper, pv[,fv[, type]])

PPmt(rate, per,nper, pv[,fv[, type]]


)

PV(rate, nper,pmt[, fv[, type]])

Rate(nper, pmt,pv[,
fv[,type[, guess]]])

SLN(cost, salvage, life)

Returns a Double value that


indicates the principle payment for
a given period (per) of an annuity
based on a number (nper) of
periodic fixed payments and a
fixed interest rate (rate).
Returns a Double value that
indicates the present value of an
annuity based on a number (nper)
of periodic fixed payments (pmt)
and a fixed interest rate (rate).
Returns a Double value that
indicates the fixed interest rate per
period for an annuity based on a
number (nper) of periodic fixed
payments (pmt).

pv specifies the present value of a series of


payments or receipts.fv (optional) specifies the
future value or cash balance left after the final
payment.type(optional) specifies when payments
are due (0 = end of the payment period, the default;
1 = beginning of the payment period).
The values() array must contain at least one
negative value (payment) and one positive value
(receipt).

pv specifies the present value of a series of


payments or receipts. fv (optional) specifies the
future value or cash balance left after the final
payment. type(optional) specifies when payments
are due (0 = end of the payment period, the default;
1 = beginning of the payment period).
pv specifies the present value of a series of
payments or receipts. fv (optional) specifies the
future value or cash balance left after the final
payment. type(optional) specifies when payments
are due (0 = end of the payment period, the default;
1 = beginning of the payment period).
fv (optional) specifies the future value or cash
balance left after the final payment.type (optional)
specifies when payments are due (0 = end of the
payment period, the default; 1 = beginning of the
payment period).
fv (optional) specifies the future value or cash
balance left after the final payment. type
(optional) specifies when payments are due (0
= end of the payment period, the default; 1 =
beginning of the payment
period). guess (optional) specifies an estimate
to be returned by Rate (default estimate is .1).

Returns a Double value


representing an asset s straight-line
depreciation, given its initial cost,
salvage value at the end of its
useful life, and life span.
SYD(cost, salvage, _ life, period)
Returns a Double value that s an
asset s sum-of-years' digits
depreciation given its initial cost,
salvage value at the end of its
useful life, life span, and period for
which depreciation is calculated.
Math Statements & Functions
Function
What It Does
Comments
Returns the Absolute Value
The data type of the value returned is identical to that of number
Abs(number)
of number
Atn(number)
Returns a Double value which
is the arctangent of number in
radians
Cos(number)
Returns a Double value which
is the cosine of number in
radians
Exp(number)
Returns a Double value
If the value of the number is greater than 709.782712893,
of e (2.718282) raised to the
an error is generated
power of the argument
Returns the integer portion
If the number is negative, it returns the first negative integer
Fix(number)
greater than or equal to the number
of number as anInteger value
Log(number)
Returns a Double value
which represents the natural

logarithm (base e) of number


Partition(number,
start, _
stop, interval)

Returns a Variant describing a


range of numbers in which
the number argument falls.

Randomize [number]

Initializes the random number


generator, using number as a
seed value.
Rounds a numeric
expression

Round(expression
_ [numdecplaces])

Rnd(number)

Sgn(number)
Sin(number)

Sqr(number)
Tan(number)

Returns a Single value that's a


randomly generated number
less than 1 but greater than or
equal to zero.
Returns a Variant thats the
sign of number.
Returns a Double value that' s
the sine in radians of a given
angle (specified bynumber).
Returns a Double value that' s
the square root of number.
Returns a Double value that' s
the tangent in radians of a given
angle (specified bynumber).

startandstop specify the overall range of numbers, split up into


smaller ranges as specified by theintervalargument. Partition
returns a string representation of the smaller range in which the
number is found, such as " 1: 10" for a number that falls in the
range of 1 to 10.
If number is omitted, a value returned by the system timer is
used as the seed value.
Optional numdeplaces indicates how many places to the
right of the decimal point the number should be rounded to.
If numdeplaces is not specified, the number is rounded to an
integer.
number (optional) determines how Rnd generates the random
number. Each time the same seed number is used, the same
sequence of numbers is returned.

Miscellaneous Other Functions and Statements


Function
What It Does
Generates a beep
Beep
Call name [arguments]
Runs a sub, function, or DLL
(procedure)

Command()

CreateObject(class)

Environ(envstring|number)

Returns any command-line


arguments specified when
launching the VB interpreter (F5
operation). For compiled
programs, Command returns the
command-line arguments
specified when the program is
launched
Creates and returns a reference to
an ActiveX object of type class.

Returns the String value of the


operating system
variable envstring or the numeric
order of the environment string
in the environment-string table
specified by number.

Comments
name is the name of the procedure; arguments
are an optional list of comma-delimited
parameters to be passed to the procedure.
Keywords ByVal or ByRef can be used, but
only when calling a DLL procedure

class uses the syntax appname.objecttype,


whereappname is the name of the application
providing the object, and objecttype is the class
of the object to be created.
If envstring can't be found in the environment
string table, a zero length string will be
returned.

object.GetAutoServerSettings _
([progid], [clsid])

Returns a Variant array


containing information
concerning the state of an
ActiveX object's registration..

(optional) progid and clsid specify the object's


ProgID and CLSID, respectively. The elements
of the Variant array that are returned
byGetAutoServerSettings are, in order:

GetObject([pathname][,class])

Returns a reference to an object


of typeclass.

Input(number, [#]filenumber)

Returns a String containing


characters read in from the open
file that corresponds
to filenumber.

InputBox()
Format()
[Let]varname = expression
MsgBox()
RaiseEvent eventname [(argumentlist)
]

RGB(red, green,blue)

SendKeys string[, wait]

Triggers an event.

Returns a Long representing an


RGB color value as specified by
the red, green, and blue color
parameters.
Generates one or more
keystrokes as if they came from
the keyboard

Set objectvar = {[New]


_objectexpression|Nothing}

Assigns an object reference


(objectexpression) to a variable
or property (objectvar).

Shell(pathname[, windowstyle])

Runs the executable program


specified by
the pathname argument and
returns a Variant representing the
program's task ID.
Inserts n spaces when writing or
displaying text using the Print #
statement or the Print method.
Positions output to the nth column
when writing or displaying text
using the Print # statement or the
Print method.
Returns an Integer data type
representing the subtype of the
variable specified invarname

Spc(n)

Tab(n)

VarType(varname)

Program Control--Loops, Structures, & Other Tools


Structure

local/remote registration of object


(True if the object is registered
remotely) the remote machine name,
the RPC network protocol name, and
the RPC authentication level
pathname specifies the path and filename from
which the object should be retrieved; however,
if it's omitted, the class name must be
specified.
The number of characters read in is specified
by the numberargument. This function is only
used with Input or Binary files.
See InputBox Page
See Format Page
Not really used much if at all any more
See MsgBox Page
(optional) argumentlistspecifies one or more
comma-delimited arguments to be passed to
the event procedure. The event procedure must
be declared in the same module as the
RaiseEvent function or an error occurs.

string determines which keystrokes to send,


and (optional) wait, a Boolean, specifies
whether keystrokes must be processed before
control is returned to the procedure. False, the
default, forces control to be returned to the
procedure after the keystrokes are sent.
(optional) New is used to indicate the object
should be created implicitly. To
disassociate objectvar with a specific object
and free up the resources it's using, assign it
theNothing keyword.
If Shell is unsuccessful, it returns zero. The
(optional)windowstyle determines the style of
the window in which the shelled program runs.

Several VB constants are used to define the


data types returned by the VarType function,
including: vbEmpty, vbNull, vbInteger,
vbLong, vbSingle, vbDouble, vbCurrency,
vbDate, vbString, vbObject, vbError,
vbBoolean, vbVariant, vbDataObject,
vbDecimal, vbByte, andvbArray.
Comments

Choose(index, choice-1[, choice-2 ...


[choice-n])

Do Events ()

Do Until condition
Program statement(s)
Loop
Do While condition
Program statement(s)
Loop
Do . . .
Program statement(s)
Loop Until condition
Do . . .
Program statement(s)
Loop While condition
End
End Function
End If
End Property
End Select
End Sub
End Type
End With
Exit Do
Exit For
Exit Function
Exit Sub

For counter-variable=start To end (Step


increment)
Program statement(s)
Next
For Each element In group
Program statement(s)
Next element
GoSub line
Program statement(s)
line:
Program statement(s)
Return
GoTo line

If condition Then statement


If condition Then
Program statement(s)
ElseIf condition2 Then
Program statement(s)
Else
Program statement(s)
EndIf

Returns a value from a list of choices (specified by the arguments choice1 through choice-n) based on the value of index. If index is 1, then the value
returned by the function will be represented by choice-1; if index is 2, then the
value returned will be choice-2; etc.
Gives the Operating System temporary control so it can process other events.
Typically this is used inside loops so that a program doesn't monopolize system
resources
Performs comparison against test condition at the TOP of the loop. Continues to
process the loop as long as condition is False. Use when you don't know how
many times the program will need to loop.
Performs comparison against test condition at the TOP of the loop. Continues to
process the loop as long as condition is True. Use when you don't know how
many times the program will need to loop.
Performs comparison against test condition at the BOTTOM of the loop.
Continues to process the loop as long as condition is False. Use when you don't
know how many times the program will need to loop.
Performs comparison against test condition at the BOTTOM of the loop.
Continues to process the loop as long as condition is True. Use when you don t
know how many times the program will need to loop.
Ends a program
Ends a function
Ends a program block
Ends a procedure
Ends a Select Case program block
Ends a subroutine
Ends a type structure
Ends a With program block
Used to exit a Do Loop early
Used to exit a For Loop early
Used to exit a Function early
Used to exit a Subroutine early
Placed inside a loop, these statements allow the program to exit directly from a
loop before the loop naturally finishes. Avoid using these if at all possible.
Use when you know how many times the program will need to loop.

This block of code is entered if there's at least one element in the group. When
there are no more elements in the group, this block of code is exited and the
statement after the Next is executed
Transfers control to the subroutine indicated by the label or line
number lineuntilReturn is reached; then returns control to the line of code
immediately following GoSub.

Transfers control to the line of code specified by line. The label or line number
specified by line must be inside the procedure containing the GoTo . Use
sparingly.
There can be any number of ElseIf or Else statements. Tedious to read; tedious to
understand avoid using this structure if at all possible.

IIF (condition, TrueBody, FalseBody)

Works like a spreadsheet @if function. Example:


curBonus = IIF(curRevenue < 5000.00, 0.00, 75.00) is equivalent to:
If (curRevenue < 5000.00 _
Then
curBonus = 0.00
Else
curBonus = 75.00
EndIf

On condition GoSub destinationlist

On condition GoTo destinationlist

Select Case Index


Case 1 program
statement(s)
Case 2 program statement(s)
Case 3 program statement(s)
[Case Else
program statement(s)]
End Select
Select Case Expression
Case is relation
program statement(s)
Case is relation
program statement(s)
Case is relation
program statement(s)
[Case Else
program statement(s)]
End Select
Select Case Expression
Case Expression1 To Expression2
program statement(s)
Case Expression1 To Expression2
program statement(s)
Case Expression1 To Expression2
program statement(s)
[Case Else
program statement(s)]
End Select
InputBox ()
MsgBox ()
Resume [0]
Resume Next
Resume line

Stop

Avoid using this if at all possible it's just too cryptic to be easily readable.
Evaluates condition and, depending on its value, transfers program control to a
certain subroutine. destinationlist contains one or more comma-delimited line
labels or line numbers representing possible subroutines. If conditionequals 1,
then the first subroutine in the destinationlist is used; if it's 2, then the second
subroutine in thedestinationlist is used; and so on. When a Returnstatement is
encountered, control is transferred to the line of code immediately following
the On...GoSub.
Evaluates condition and, depending on its value, transfers program control to a
certain line label or line number. destinationlist contains one or more commadelimited line labels or line numbers representing possible transfer points.
If condition equals 1, then the first line label in the destinationlist is used; if it's 2,
then the second line label in the destinationlist is used; and so on.
Known as a Select Case structure.

Known as an Is Select Case structure.


relation is any test performed against Expression.

Known as a To Select Case structure.


Usually used when dealing with ranges of data the expressions represent the
starting and ending values for each range.

Receives text which has been typed into a dialog box by the user (see InputBox
Page)
Returns one of seven numerical values signifying the following (see MsgBox
Page)
Resumes program execution after an error-handling routine finishes. Resume by
itself causes execution to resume with the statement that caused the error or, if the
error occurred in a called procedure, the statement that last called the errorhandling procedure. Resume Nextresumes execution with the statement
immediately following the one that caused the error. Resume linetransfers control
to the line label or line number specified by line.
Suspends program execution; but it doesn't close any files or clear variables
unless it's in a compiled program

Switch(expr-1, value-1[, expr-2, _


value-2 ...[, expr-n, _ value-n]])

Evaluates a list of expressions (expr-1, expr-2,...expr-n) and returns a Variant


corresponding to the first expression evaluating as True. If expr1 is True, Switch returnsvalue-1; if expr-2 is True, Switch returns value-2; etc.
Repeats one or more statements while condition remainsTrue.
When condition becomes False, control is passed to the line of code immediately
following the While...Wendstructure.

While condition
program statement(s)
Wend
Note: End While instead of Wend under
VB.Net
With Object
Executes one or more statements on a specified object or user-defined type
program statement(s)
without having to respecify the name of the object. Once a With block is
End With
entered, object cannot change. Nested With blocks are allowed
Registry Statements & Functions
Function
What it Does
Comments
DeleteSetting appname,
Deletes an application's
appname specifies the application name, and section is the
section or key setting entries section name to be deleted. If key(optional) is used, only
section[, key]
from the System Registry.
that key (and not the whole section) will be deleted.
GetAllSetting (appname, section) Returns a list of key settings appname is the application name, and sectionis the section
and their values from an
name
application and section in
the System Registry.
GetSetting (appname, section, _
Returns a single key setting
appname is the application name, and section is the section
from an application entry
name.If no value is set for the key setting specified, then
key[, default])
and section in the System
the optional defaultvalue can be returned. If default is
Registry
omitted, then the default returned is a zero-length string.
Saves or creates an
appname is the application name, section is the section
SaveSetting (appname,
application entry, section,
name, key is the key setting and setting is the setting value
section, key, _
key
setting,
and
value
in
the
setting)
System Registry.
String Manipulation Statements & Functions
Function
What it Does
Comments
Asc(string)
Returns an Integer value
corresponding to the ASCII code for
the first character of string
Chr(charcode)
Returns a one-character String that
represents the ASCII character of the
number specified by charcode
See Entry in Conversion Functions
Cstr()
Instr([start, ]
Returns a Variant specifying the
(optional) start specifies from which character in
_ string1, string2 _
starting position of the first occurrence string2 to start searching; the default is 1, the
[,compare])
of a substring (string2) within another 1st character). (optional) compare indicates the string
string (string1).
comparison that to be made (0 = binary or 1 = noncase-sensitive text).
InstrRev(string1,
Searches for a substring (string2)
The compare agrument can take on the
_ string2[,start[,compare]]))
within a string (string1) and returns following values:vbUseCompareOption,
the position of that substring from
vbBinaryCompare, vbTextCompare,
the end of the string
vbDatabaseCompare,
Left(string, length)
Returns a String value that
s lengthcharacters long, taken from the
left side of string.
Returns string as all lower case
Good for reducing the number of string comparisons
LCase (string)
that might need to be made against user text input
strings
Len(string|varname)
Determines the length of a string
(string) or numeric (varname)
Assigns a string value to a String
LSet stringvar= string
variable (stringvar), left-aligning the
string to the String variable.
LSet varname1=varname2
Copies a variable (varname2) from
one user-defined type (UDT) to a
variable (varname1) in another userdefined type (UDT).
LTrim (string)
Returns a Variant containing a copy
ofstring with any leading spaces
removed.

Mid(string, start [,length])

Returns a String of one or more


characters (as determined by
thestartposition and length
parameters), taken from string.

Mid(stringvar, start[,length])=
_ string

Replaces one or more characters in a


String variable (stringvar) with string.

Right(string, length)

Returns
a String value lengthcharacters long
taken from the right side of string.
Assigns a string value to
aString(stringvar), right-aligning the
string to theString.
Returns
a Variant containing stringwith any
trailing spaces removed.
Returns a Variant containing
a numberof spaces.

RSet stringvar= string

RTrim (string)

Space(number)
Str(number)
StrComp(string1, string2[,
_ compare])

Returns a Variant containing the result


of a comparison between two strings
(string1 and string2).

StrConv (string, conversion)

Returns a Variant, converted


fromstring as specified by conversion.

String(number, character)

Returns a Variant of the length


specified by number and is filled with
a given character
Returns a string in which the order
of the characters is reversed

StrReverse(string1)

TypeName(varname)

Returns a String indicating the data


type of a given variable (varname).

Trim(string)

Returns
a Variant containing stringwith any
leading and trailing spaces removed.
Returns string as all upper case

UCase(string)

Val()
Arithmetic Operators
Processed?
Operator
1st
( . . .)
2nd
3rd
4th

7th

^
*
/
\
Mod
+
&

8th

IS

5th
6th

startspecifies the position withinstring where the


new String is to be obtained, and
(optional) length specifies how many characters are
to be taken from string. If no length is specified,
then the entire string (starting at the position
by start) is used.
startspecifies the position withinstringvar to place
the new string, and (optional) length specifies how
many characters of string should be used. If no
length is specified, then the entire stringis used.

See Entry in Conversion Functions


(optional) compare specifies how strings are to be
compared, with 0 = binary comparison and 1 = a
non-case-sensitive text comparison.
conversion uses a VB constants to specify the
type of conversion, such
as vbUpperCase,vbLowerCase,
andvbProperCase.

If string1 is a zero length string, a zero length


string is returned. Ifstring1 is Null, an error
occurs.
Possible return values are:
Byte, Integer, Long, Single, Double, Currency,
Decimal, Date, String, Boolean, Error, Empty,
Null, Object, Unknown, Nothing, or an Object.

Good for reducing the number of string comparisons


that might need to be made against user text input
strings
See Conversion Functions

Description
Whatever's enclosed by parentheses gets processed first (use these to avoid any
ambiguity)
Negation--indicates a negative expression
Exponentiation-- raising a number to a power
Multiplication
Normal Division
Integer Division
Modulo Operator-- returns a remainder
Subtraction
Addition
Although not strictly an arithmetic operator, the string concatenation operator is
evaluated before comparison and logical operators
Actually an object reference operator, tests whether one object is identical to another

NOTES:
When addition and subtraction both occur in an expression, evaluation of the expression proceeds from
left to right.
Within parentheses, left-to-right precedence applies.
Comparison Operators
Processed?
Operator
Description
All have equal precedence; so they're evaluated in
=
Equal to
Not Equal to
<>
the left-to-right order in which they appear
<
Less than
Greater than
>
<=
Less than or equal to
Greater than or equal to
>=
LIKE
Actually a pattern matching operator, tests
whether two expressions are equal
Logical Operators
Processed?
Operator
1st
Not
2nd
rd

And

Description
Reverses the value of a logical expression. (Avoid using if at all possible using it tends to
make the code harder to understand)
If both expressions are true, the result is true

Or

If one of the expressions is true, the result is true

4th

Xor

Exclusive OR

th

Eqv

Performs a bitwise comparison by bit position between two numeric expressions. If either
expression is Null, the result is also Null. If neither expression is null then the result is
determined using the following:
If
And Then
expr1 is expr 2 is the result is
True
True
True
True
False
False
False
True
False
False
False
True
6th
Imp
Performs a bitwise comparison by bit position between two numeric expressions. The result
of an imp operation is determined as follows:
If
And Then
expr1 is expr 2 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
http://www.therthdimension.org/Computers/VB/VB6_Commands/vb6_commands.htm
Compiled by Bumi

You might also like