You are on page 1of 19

Date/Time Functions

Function Description
CDate Converts a valid date and time expression to the variant of
subtype Date
Date Returns the current system date
DateAdd Returns a date to which a specified time interval has been added
DateDiff Returns the number of intervals between two dates
DatePart Returns the specified part of a given date
DateSerial Returns the date for a specified year, month, and day
DateValue Returns a date
Day Returns a number that represents the day of the month
(between 1 and 31, inclusive)
FormatDateTime Returns an expression formatted as a date or time
Hour Returns a number that represents the hour of the day (between
0 and 23, inclusive)
IsDate Returns a Boolean value that indicates if the evaluated
expression can be converted to a date
Minute Returns a number that represents the minute of the hour
(between 0 and 59, inclusive)
Month Returns a number that represents the month of the year
(between 1 and 12, inclusive)
MonthName Returns the name of a specified month
Now Returns the current system date and time
Second Returns a number that represents the second of the minute
(between 0 and 59, inclusive)
Time Returns the current system time
Timer Returns the number of seconds since 12:00 AM
TimeSerial Returns the time for a specific hour, minute, and second
TimeValue Returns a time
Weekday Returns a number that represents the day of the week (between
1 and 7, inclusive)
WeekdayName Returns the weekday name of a specified day of the week
Year Returns a number that represents the year

Conversion Functions
Function Description
Asc Converts the first letter in a string to ANSI code
CBool Converts an expression to a variant of subtype Boolean
CByte Converts an expression to a variant of subtype Byte
CCur Converts an expression to a variant of subtype Currency
CDate Converts a valid date and time expression to the variant of
subtype Date
CDbl Converts an expression to a variant of subtype Double
Chr Converts the specified ANSI code to a character
CInt Converts an expression to a variant of subtype Integer
CLng Converts an expression to a variant of subtype Long
CSng Converts an expression to a variant of subtype Single
CStr Converts an expression to a variant of subtype String
Hex Returns the hexadecimal value of a specified number
Oct Returns the octal value of a specified number

Format Functions
Function Description
FormatCurrency Returns an expression formatted as a currency value
FormatDateTime Returns an expression formatted as a date or time
FormatNumber Returns an expression formatted as a number
FormatPercent Returns an expression formatted as a percentage

Math Functions
Function Description
Abs Returns the absolute value of a specified number
Atn Returns the arctangent of a specified number
Cos Returns the cosine of a specified number (angle)
Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number
Int Returns the integer part of a specified number
Fix Returns the integer part of a specified number
Log Returns the natural logarithm of a specified number
Oct Returns the octal value of a specified number
Rnd Returns a random number less than 1 but greater or equal to 0
Sgn Returns an integer that indicates the sign of a specified number
Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified number
Tan Returns the tangent of a specified number (angle)

Array Functions
Function Description
Array Returns a variant containing an array
Filter Returns a zero-based array that contains a subset of a string
array based on a filter criteria
IsArray Returns a Boolean value that indicates whether a specified
variable is an array
Join Returns a string that consists of a number of substrings in an
array
LBound Returns the smallest subscript for the indicated dimension of an
array
Split Returns a zero-based, one-dimensional array that contains a
specified number of substrings
UBound Returns the largest subscript for the indicated dimension of an
array

String Functions
Function Description
InStr Returns the position of the first occurrence of one string within
another. The search begins at the first character of the string
InStrRev Returns the position of the first occurrence of one string within
another. The search begins at the last character of the string
LCase Converts a specified string to lowercase
Left Returns a specified number of characters from the left side of a
string
Len Returns the number of characters in a string
LTrim Removes spaces on the left side of a string
RTrim Removes spaces on the right side of a string
Trim Removes spaces on both the left and the right side of a string
Mid Returns a specified number of characters from a string
Replace Replaces a specified part of a string with another string a
specified number of times
Right Returns a specified number of characters from the right side of a
string
Space Returns a string that consists of a specified number of spaces
StrComp Compares two strings and returns a value that represents the
result of the comparison
String Returns a string that contains a repeating character of a
specified length
StrReverse Reverses a string
UCase Converts a specified string to uppercase

Other Functions
Function Description
CreateObject Creates an object of a specified type
Eval Evaluates an expression and returns the result. Evaluates a
string and return the result of the string expression.
GetLocale Returns the current locale ID
GetObject Returns a reference to an automation object from a file
GetRef Allows you to connect a VBScript procedure to a DHTML event on
your pages
InputBox Displays a dialog box, where the user can write some input
and/or click on a button, and returns the contents
IsEmpty Returns a Boolean value that indicates whether a specified
variable has been initialized or not
IsNull Returns a Boolean value that indicates whether a specified
expression contains no valid data (Null)
IsNumeric Returns a Boolean value that indicates whether a specified
expression can be evaluated as a number
IsObject Returns a Boolean value that indicates whether the specified
expression is an automation object
LoadPicture Returns a picture object. Available only on 32-bit platforms
MsgBox Displays a message box, waits for the user to click a button, and
returns a value that indicates which button the user clicked
RGB Returns a number that represents an RGB color value
Round Rounds a number
ScriptEngine Returns the scripting language in use
ScriptEngineBuildVersion Returns the build version number of the scripting engine in use
ScriptEngineMajorVersion Returns the major version number of the scripting engine in use
ScriptEngineMinorVersion Returns the minor version number of the scripting engine in use
SetLocale Sets the locale ID and returns the previous locale ID
TypeName Returns the subtype of a specified variable
VarType Returns a value that indicates the subtype of a specified variable
Execute Executes one or more statements in a string expression and
enables creation of dynamic code.

VBScript Keywords
Keyword Description
Empty Used to indicate an uninitialized variable value. A variable value
is uninitialized when it is first created and no value is assigned to
it, or when a variable value is explicitly set to empty.

Example:
Dim x 'the variable x is uninitialized!
x="ff" 'the variable x is NOT uninitialized anymore
x=Empty 'the variable x is uninitialized!

Note: This is not the same as Null!!


IsEmpty Used to test if a variable is uninitialized.

Example: If (IsEmpty(x)) 'is x uninitialized?


Used to indicate an uninitialized object value, or to disassociate
Nothing an object variable from an object to release system resources.
Example: Set myObject=Nothing
Is Nothing Used to test if a value is an initialized object.

Example: If (myObject Is Nothing) 'is it unset?

Note: If you compare a value to Nothing, you will not get the
right result! Example: If (myObject = Nothing) 'always false!
Null Used to indicate that a variable contains no valid data.

One way to think of Null is that someone has explicitly set the
value to "invalid", unlike Empty where the value is "not set".

Note: This is not the same as Empty or Nothing!!

Example: x=Null 'x contains no valid data


IsNull Used to test if a value contains invalid data.

Example: if (IsNull(x)) 'is x invalid?


True Used to indicate a Boolean condition that is correct (True has a
value of -1)
False Used to indicate a Boolean condition that is not correct (False
has a value of 0)

Table C.1 VBScript Keywords


Keyword/Feature Description
Array handling
IsArray Returns True if a variable is an array
Erase Reinitializes a fixed-size array
LBound Returns the lower bound of an array
UBound Returns the upper bound of an array
Assignments
= Assigns a value to a variable
Let Assigns a value to a variable
Set Assigns an object to a variable
Comments
` Includes inline comments in your script
Rem Includes comments in your script
Constants/Literals
Empty Indicates an uninitialized variable
Nothing Disassociates a variable with an object
Null Indicates a variable with no data
True Boolean True
False Boolean False
Control flow
Do...Loop Repeats a block of statements
For...Next Repeats a block of statements
For Each...Next Repeats a block of statements
If...Then...Else Conditionally executes statements
Select Case Conditionally executes statements
While...Wend Repeats a block of statements
Conversions
Abs Returns absolute value of a number
Asc Returns the ASCII code of a character
AscB Returns the ASCII code of a character
AscW Returns the ASCII code of a character
Chr Returns a character from an ASCII code
ChrB Returns a character from an ASCII code
ChrW Returns a character from an ASCII code
CBool Converts a variant to a Boolean
CByte Converts a variant to a byte
CDate Converts a variant to a date
CDbl Converts a variant to a double
Cint Converts a variant to an integer
CLng Converts a variant to a long
CSng Converts a variant to a single
CStr Converts a variant to a string
DateSerial Converts a variant to a date
DateValue Converts a variant to a date
Hex Converts a variant to a hex string
Oct Converts a variant to an octal string
Fix Converts a variant to a fixed string
Int Converts a variant to an integer string
Sgn Converts a variant to a single string
TimeSerial Converts a variant to a time
TimeValue Converts a variant to a time
Dates/Times
Date Returns the current date
Time Returns the current time
DateSerial Returns a date from its parts
DateValue Returns a date from its value
Day Returns day from a date
Month Returns month from a date
Weekday Returns weekday from a date
Year Returns year from a date
Hour Returns hour from a time
Minute Returns minute from a time
Second Returns seconds from a time
Now Returns current date and time
TimeSerial Returns a time from its parts
TimeValue Returns a time from its value
Declarations
Dim Declares a variable
Private Declares script-level private variable
Public Declares public-level public variable
ReDim Reallocates an array
Function Declares a function
Sub Declares a subprocedure
Error Handling
On Error Enables error handling
Err Contains information about last error
Input/Output
InputBox Prompts the user for input
MsgBox Displays a message to the user
Math
Atn Returns the Arctangent of a number
Cos Returns the cosine of a number
Sin Returns the sine of a number
Tan Returns the tangent of a number
Exp Returns the exponent of a number
Log Returns the logarithm of a number
Sqr Returns the square root of a number
Randomize Reseeds the randomizer
Rnd Returns a random number
Operators
+ Addition
- Subtraction
^ Exponentiation
Mod Modulus arithmetic
* Multiplication
/ Division
\ Integer Division
- Negation
& String concatenation
= Equality
<> Inequality
< Less Than
<= Less Than or Equal To
> Greater Than
>= Greater Than or Equal To
Is Compares expressions
And Compares expressions
Or Compares expressions
Xor Compares expressions
Eqv Compares expressions
Imp Compares expressions
Objects
CreateObject Creates reference to an OLE object
IsObject Returns True if object is valid
Options
Option Explicit Forces explicit variable declaration
Procedures
Call Invokes a subprocedure
Function Declares a function
Sub Declares a subprocedure
Strings
InStr Returns index of a string in another
InStrB Returns index of a string in another
Len Returns the length of a string
LenB Returns the length of a string
Lcase Converts a string to lowercase
Ucase Converts a string to uppercase
Left Returns the left portion of a string
LeftB Returns the left portion of a string
Mid Returns the mid portion of a string
MidB Returns the mid portion of a string
Right Returns the right portion of a string
RightB Returns the right portion of a string
Space Pads a string with spaces
StrComp Compares two strings
String Pads a string with a character
Ltrim Removes leading spaces from a string
Rtrim Removes trailing spaces from a string
Trim Removes leading and trailing spaces
Variants
IsArray Returns True if variable is an array
IsDate Returns True if variable is a date
IsEmpty Returns True if variable is empty
IsNull Returns True if variable is null.
IsNumeric Returns True if variable is a number
IsObject Returns True if variable is an object
VarType Indicates a variable's type

Function: Len
Description: Returns a Long containing the length of the specified string
Syntax: Len(string)
Where string is the string whose length (number of characters) is to be
returned.
Example: lngLen = Len("Visual Basic") ' lngLen = 12
Function: Mid$ (or Mid)
Description: Returns a substring containing a specified number of characters from a
string.
Syntax: Mid$(string, start[, length])

The Mid$ function syntax has these parts:

string Required. String expression from which characters are returned.

start Required; Long. 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 Optional; Long. 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.
strSubstr = Mid$("Visual Basic", 3, 4) '
strSubstr = "sual"
Example:
Note: Mid$ can also be used on the left side of an assignment statement,
where you can replace a substring within a string.

strTest = "Visual Basic"


Mid$(strTest, 3, 4) = "xxxx"

'strTest now contains "Vixxxx Basic"


In VB6, the Replace$ function was introduced, which can also be used
to replace characters within a string.

Function: Left$ (or Left)


Description: Returns a substring containing a specified number of characters from the
beginning (left side) of a string.
Syntax: Left$(string, length)

The Left$ function syntax has these parts:

String Required. String expression from which the leftmost characters


are returned.

Length Required; Long. 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.

Example: strSubstr = Left$("Visual Basic", 3) ' strSubstr =


"Vis"

' Note that the same thing could be accomplished with


Mid$:
strSubstr = Mid$("Visual Basic", 1, 3)

Function: Right$ (or Right)


Description: Returns a substring containing a specified number of characters from the
end (right side) of a string.
Syntax: Right$(string, length)

The Right$ function syntax has these parts:

string Required. String expression from which the rightmost characters


are returned.

length Required; Long. 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.
Example: strSubstr = Right$("Visual Basic", 3) ' strSubstr =
"sic"

' Note that the same thing could be accomplished with


Mid$:
strSubstr = Mid$("Visual Basic", 10, 3)

Function: UCase$ (or UCase)


Description: Converts all lowercase letters in a string to uppercase. Any existing
uppercase letters and non-alpha characters remain unchanged.
Syntax: UCase$(string)
Example: strNew = UCase$("Visual Basic") ' strNew =
"VISUAL BASIC"

Function: LCase$ (or LCase)


Description: Converts all uppercase letters in a string to lowercase. Any existing
lowercase letters and non-alpha characters remain unchanged.
Syntax: LCase$(string)
Example: strNew = LCase$("Visual Basic") ' strNew =
"visual basic"

Function: InStr
Description: Returns a Long specifying the position of one string within another. The
search starts either at the first character position or at the position
specified by the start argument, and proceeds forward toward the end of
the string (stopping when either string2 is found or when the end of the
string1 is reached).
Syntax: InStr([start,] string1, string2 [, compare])

The InStr function syntax has these parts:

Start Optional. Numeric expression that sets the starting position for
each search. If omitted, search begins at the first character position. The
start argument is required if compare is specified.

String1 Required. String expression being searched.

String2 Required. String expression sought.

Compare Optional; numeric. A value of 0 (the default) specifies a binary


(case-sensitive) search. A value of 1 specifies a textual (case-
insensitive) search.
Examples: lngPos = Instr("Visual Basic", "a")
' lngPos = 5

lngPos = Instr(6, "Visual Basic", "a")


' lngPos = 9 (starting at position 6)

lngPos = Instr("Visual Basic", "A")


' lngPos = 0 (case-sensitive search)

lngPos = Instr(1, "Visual Basic", "A", 1)


' lngPos = 5 (case-insensitive search)

Function: InstrRev
Description: Returns a Long specifying the position of one string within another. The
search starts either at the last character position or at the position
specified by the start argument, and proceeds backward toward the
beginning of the string (stopping when either string2 is found or when
the beginning of the string1 is reached).
Introduced in VB 6.
Syntax: InStrRev(string1, string2[, start, [, compare]])

The InStr function syntax has these parts:

String1 Required. String expression being searched.

String2 Required. String expression sought.

Start Optional. Numeric expression that sets the starting position for
each search. If omitted, search begins at the last character
position.

Compare Optional; numeric. A value of 0 (the default) specifies a binary


(case-sensitive) search. A value of 1 specifies a textual (case-
insensitive) search.
Examples: lngPos = InstrRev("Visual Basic", "a")
' lngPos = 9

lngPos = InstrRev("Visual Basic", "a", 6)


' lngPos = 5 (starting at position 6)

lngPos = InstrRev("Visual Basic", "A")


' lngPos = 0 (case-sensitive search)

lngPos = InstrRev("Visual Basic", "A", , 1)


' lngPos = 9 (case-insensitive search)
' Note that this last example leaves a placeholder
for the start argument

Function: String$ (or String)


Description: Returns a string containing a repeating character string of the length
specified.
Syntax: String$(number, character)

The String$ function syntax has these parts:

Number Required; Long. Length of the returned string.

Character Required; Variant. This argument can either be a number from


0 to 255 (representing the ASCII character code* of the
character to be repeated) or a string expression whose first
character is used to build the return string.
Examples: strTest = String$(5, "a")
' strTest = "aaaaa"

strTest = String$(5, 97)


' strTest = "aaaaa" (97 is the ASCII code for "a")

Function: Space$ (or Space)


Description: Returns a string containing the specified number of blank spaces.
Syntax: Space$(number)

Where number is the number of blank spaces desired.

Examples: strTest = Space$(5) ' strTest = " "

Function: Replace$ (or Replace)


Description: Returns a string in which a specified substring has been replaced with
another substring a specified number of times.
Introduced in VB 6.
Syntax: Replace$(expression, find, replacewith[, start[, count[, compare]]])

The Replace$ function syntax has these parts:

Expression Required. String expression containing substring to replace.

Find Required. Substring being searched for.

Replacewith Required. Replacement substring.

Start Optional. Position within expression where substring search is to


begin. If omitted, 1 is assumed.

Count Optional. Number of substring substitutions to perform. If


omitted, the default value is 1, which means make all
possible substitutions.

Compare Optional. Numeric value indicating the kind of comparison to


use when evaluating substrings. (0 = case sensitive, 1 =
case-insensitive)
Built-in "vb" constants can be used for the compare argument:

vbBinaryCompare for 0 (case-sensitive search)


vbTextCompare for 1 (case-insensitive search)
Examples: strNewDate = Replace$("08/31/2001", "/", "-")
' strNewDate = "08-31-2001"

Function: StrReverse$ (or StrReverse)


Description: Returns a string in which the character order of a specified string is
reversed.
Introduced in VB 6.
Syntax: StrReverse$(string)
Examples: strTest = StrReverse$("Visual Basic") ' strTest
= "cisaBlausiV"

Function: LTrim$ (or LTrim)


Description: Removes leading blank spaces from a string.
Syntax: LTrim$(string)
Examples: strTest = LTrim$(" Visual Basic ")
' strTest = "Visual Basic "

Function: RTrim$ (or RTrim)


Description: Removes trailing blank spaces from a string.
Syntax: RTrim$(string)
Examples: strTest = RTrim$("Visual Basic") ' strTest = "Visual
Basic"

Function: Trim$ (or Trim)


Description: Removes both leading and trailing blank spaces from a string.
Syntax: Trim$(string)
Examples: strTest = Trim$(" Visual Basic ") ' strTest =
"Visual Basic"
' Note: Trim$(x) accomplishes the same thing as LTrim$
(RTrim$(x))

Function: Asc
Description: Returns an Integer representing the ASCII character code corresponding
to the first letter in a string.
Syntax: Asc(string)
Examples: intCode = Asc("*") ' intCode = 42
intCode = Asc("ABC") ' intCode = 65

Function: Chr$ (or Chr)


Description: Returns a string containing the character associated with the specified
character code.
Syntax: Chr$(charcode)
Where charcode is a number from 0 to 255 that identifies the
character.
Examples: strChar = Chr$(65) ' strChar = "A"

(i)The Len Function


The length function returns an integer value which is the length of a phrase or a
sentence, including the empty spaces. The format is
Len (Phrase)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22
The Len function can also return the number of digits or memory locations of a
number that is stored in the computer. For example,
Private sub Form_Activate ( )
X=sqr (16)
Y=1234
Z#=10#
Print Len(x), Len(y), and Len (z)
End Sub

Will produce the output 1, 4, 8. The reason why the last value is 8 is because z# is a
double precision number and so it is allocated more memory spaces.

(ii) The Right Function

The Right function extracts the right portion of a phrase. The format is
Right (Phrase, n)

Where n is the starting position from the right of the phase where the portion of the
phrase is going to be extracted. For example,

Right (Visual Basic, 4) = asic

(iii)The Left Function

The Left$ function extract the left portion of a phrase. The format is

Left (Phrase, n)

Where n is the starting position from the left of the phase where the portion of the
phrase is going to be extracted. For example,

Left (Visual Basic, 4) = Visu

(iv) The Ltrim Function

The Ltrim function trims the empty spaces of the left portion of the phrase. The
format is

Ltrim (Phrase)

.For example,

Ltrim (Visual Basic, 4) = Visual basic

(v) The Rtrim Function

The Rtrim function trims the empty spaces of the right portion of the phrase. The
format is

Rtrim (Phrase)

.For example,

Rtrim (Visual Basic , 4) = Visual basic

(vi) The Trim function

The Ttrim function trims the empty spaces on both side of the phrase. The format is

Trim (Phrase)

.For example,

Trim (Visual Basic) = Visual basic

(viii) The Mid Function

The Mid function extracts a substring from the original phrase or string. It takes the
following format:

Mid (phrase, position, n)

Where position is the starting position of the phrase from which the extraction
process will start and n is the number of characters to be extracted. For example,
Mid (Visual Basic, 3, 6) = ual Bas

(ix) The InStr function

The InStr function looks for a phrase that is embedded within the original phrase
and returns the starting position of the embedded phrase. The format is

Instr (n, original phase, embedded phrase)

Where n is the position where the Instr function will begin to look for the embedded
phrase. For example

Instr (1, Visual Basic, Basic) =8

(x) The Ucase and the Lcase functions

The Ucase function converts all the characters of a string to capital letters. On the
other hand, the Lcase function converts all the characters of a string to small letters.
For example,

Ucase (Visual Basic) =VISUAL BASiC

Lcase (Visual Basic) =visual basic

(xi) The Str and Val functions

The Str is the function that converts a number to a string while the Val function
converts a string to a number. The two functions are important when we need to
perform mathematical operations.

(xii) The Chr and the Asc functions

The Chr function returns the string that corresponds to an ASCII code while the Asc
function converts an ASCII character or symbol to the corresponding ASCII code.
ASCII stands for American Standard Code for Information Interchange. Altogether
there are 255 ASCII codes and as many ASCII characters. Some of the characters
may not be displayed as they may represent some actions such as the pressing of a
key or produce a beep sound. The format of the Chr function is

Chr (charcode)

And the format of the Asc function is

Asc (Character)

The following are some examples:

Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(B)=66, Asc(&)=38


Split(expression[,delimiter[,count[,compare]]])

Parameter Description
expression Required. A string expression that contains substrings and delimiters
delimiter Optional. A string character used to identify substring limits. Default is
the space character
count Optional. The number of substrings to be returned. -1 indicates that all
substrings are returned
compare Optional. Specifies the string comparison to use.

Can have one of the following values:

0 = vbBinaryCompare - Perform a binary comparison

1 = vbTextCompare - Perform a textual comparison

Eval Function and Execute Statement


Eval returns a Boolean value whereas Execute function performs a variable assignment.
x = 10
y = 10
BIsEqual = Eval ("x = y") compare variables (Will return Boolean value, if x= y, True
Else False.)
Execute "x = y" variable assignment
MsgBox "x value is" & x
MsgBox "bIsEqual: " & bIsEqual
MsgBox "X is no longer 9. It is: & x

You might also like