|  | Click Here!

Search the site:
EXPERT SEARCH

| Programming Languages
| Databases
| Security
| Web Services
| Network Services
| Middleware
| Components
| Operating Systems
| User Interfaces
| Groupware & Collaboration
| Content Management
| Productivity Applications
| Hardware
| Fun & Games

EarthWeb sites
Crossnodes
Datamation
Developer.com
DICE
EarthWeb.com
EarthWeb Direct
ERP Hub
Gamelan
GoCertify.com
HTMLGoodies
Intranet Journal
IT Knowledge
IT Library
JavaGoodies
JARS
JavaScripts.com
open source IT
RoadCoders
Y2K Info

# Chapter 3

# VBScript Functions

by Brian Johnson

CONTENTS

- Introduction
- Procedures in Scripts
  - `Sub` Procedures and `Function` Procedures
  - Arguments to Procedures
  - Creating and Calling Functions
- Intrinsic Functions
- Basic Functions
  - `InputBox`
  - `len`
  - `MsgBox`
  - `VarType`
- String Functions
  - `Asc`
  - `Chr`
  - `InStr`
  - `LCase`
  - `Left`
  - `LTrim`
  - `Mid`
  - `Right`
  - `RTrim`
  - `Str()`
  - `StrComp`
  - `String`
  - `Trim`
  - `UCase`
  - `Val`
- Conversion Functions
  - `CByte`
  - `CDbl`
  - `CInt`
  - `CLng`
  - `CStr`
  - `CVErr`
- Math Functions
  - `Abs`
  - `Array`
  - `Atn`
  - `Exp`
  - `Hex`
  - `Int`
  - `Fix`
  - `Log`
  - `Oct`
  - `Rnd`
  - `Sgn`
  - `Sqr`
  - `Sin`
  - `Tan`
- Time and Date Functions
  - `Date`
  - `DateSerial`
  - `DateValue`
  - `Day`
  - `Hour`
  - `Year`
  - `Weekday`
  - `Minute`
  - `Month`
  - `Now`
  - `Second`
  - `Time`
  - `TimeSerial`
  - `TimeValue`
- Boolean Functions
- Review

## Introduction

Procedures are the building blocks of VBScript. So far, we've created a number of scripts in HTML documents. We've used procedures in most of them, but we haven't really discussed the topic in detail. We'll do that in this chapter.

In this chapter, you will

- Learn about procedures and how they are used in VBS scripts
- Learn about the difference between a `Sub` procedure and a `Function` procedure
- Learn about VBScript's intrinsic functions
- Learn how to utilize VBS functions in your own scripts

## Procedures in Scripts

Procedures are the logical parts into which a program is divided. The code inside a procedure is run when the procedure is called. A procedure can be called with a `Call` statement in another procedure, or it can be triggered by an event such as a button click.

Events are triggered when messages are sent from the operating system to VBScript. In graphical operating systems, such as Windows, the way that different applications interact with the operating system is by sending and receiving. The operating system is the controlling force in the graphical environment, and the scripts that you write will depend in large part on the resources and messages made available to you from Windows. You'll learn more about events in Chapter 4 "Intrinsic Controls."

### `Sub` Procedures and `Function` Procedures

There are two types of procedures in VBScript: `Sub` procedures and `Function` procedures. `Sub` procedures are blocks of code that are wrapped in the `Sub...End Sub` keywords. A `Sub` can take arguments and process them within the `Sub` procedure. A `Sub` can call other procedures, but it can't return a value generated to the calling procedure directly.

A `Function` procedure works just like a `Sub` procedure. It can take arguments and call other procedures. Most importantly, `Function` procedures return a value to the calling procedure. Figure 3.1 shows the relationship between procedures in a typical script. The value returned is then processed by the calling procedure as if the code had been in the same block.

Figure 3.1 : Calling one procedure from another.

Let's take a look at some sample code. Listing 3.1 contains three procedures. We'll use message boxes to track the program flow.

> Listing 3.1. `Flow.htm`.

>     <HTML>

>     <HEAD>

>     <TITLE>Tracking Procedures</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBS</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

>     <SCRIPT LANGUAGE="VBScript">

>     <!--

>     Sub Btn1_OnClick

>         Dim Message, x

>         x=100

>         Message="Sub Btn1_OnClick"

>         MsgBox Message, 0,"Procedure Result"

>         Message = "Sub MySub"

>         MySub(Message)

>         x = ReturnCount(x)

>         Message = "Function returned " + CStr(x)

>         MsgBox Message, 0, "Procedure Result"

>     End Sub

>     Sub MySub(Msg)

>         MsgBox Msg, 0, "Procedure Result"

>     End Sub

>     Function ReturnCount(Num)

>         ReturnCount = Num + 1

>     End Function

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

Let's track Listing 3.1 and see where it's going. Using our tester template, we create two procedures to go with the `Sub Btn1_OnClick` procedure that was already in place. The `MySub` procedure takes an argument called `Msg` and in turn passes that value to a `MsgBox` function. The other new procedure is the `Function ReturnCount`, which simply takes an argument, `Num`, and adds 1 to it.

If you take a look at how the program flows, you'll see that it all begins in `Sub Btn1_OnClick`. The variable `Message` is assigned the name `Sub Btn1_OnClick`, and a `MsgBox` function is called with `Message` as one of the arguments. Notice that the flow of the `Sub Btn1_OnClick` procedure is halted until the message box is dismissed.

After the message box is closed, the value of `Message` is set to the name of the second procedure in the script, `Sub MySub`. The `MySub` procedure is called, with `Message` as an argument. The argument `Message` is then called in another `MsgBox` function call from within `MySub`. Again, program flow is stopped while the message box is displayed.

Finally, the variable `x`, having previously been set to a value of `100`, is used as an argument in the call to the function `ReturnCount`. `ReturnCount` adds 1 to `x` and returns the value to the calling procedure. We then make `x` part of the `Message` variable. Notice that the argument we pass to the `MsgBox` function must be a string, so we need to convert the value of `x` to a string before it can be made part of `Message`. The message box is then displayed with the message "Function returned 101." When the message box is closed, `End Sub` is hit, and the script ends.

### Arguments to Procedures

Arguments can be used to pass data to either `Sub` or `Function` procedures. When calling a procedure, you can simply use the procedure name followed by arguments, which are separated by commas:

>     MyProcedure Arg1, Arg2, Arg3

Or you can use the `Call` statement, in which case the argument list must be enclosed by parentheses:

>     Call MyProcedure(Arg1, Arg2)

You can also call the procedure without the `Call` statement and still include parentheses.

### Creating and Calling Functions

When you create and use a function, the return value of the function is held by a variable with the name of the function. For example, if you create a function that converts pennies to dollars, you might name the function `Dollar`:

>     Function Dollar(Cents)

>         Dollar = Cents/100

>     End Function

The function returns the value of `Dollar` to the calling procedure.

To call the `Dollar` function from another procedure, you must use a variable of some sort to hold the return value. If you call `Dollar` from the following code, the value `Dollars` will hold the returned value of the function:

>     Dollars = Dollar(2456)

Function procedures are great tools for working with data in a VBS script. When you create functions that you know you might want to use again, be sure to save them, so that you can easily reuse them in new scripts.

## Intrinsic Functions

In addition to creating your own function procedures for use in your scripts, you can use a number of intrinsic function procedures that are built into VBScript. These functions include string operations, conversions, math functions, time and date functions, and Boolean functions. Understanding these functions will benefit you greatly as you begin to write larger and more complex scripts.

First, let's talk about the basic utility functions available to you.

## Basic Functions

The intrinsic functions in VBScript aren't actually broken into categories, but I've divided them up so that you'll remember them more easily. What I've called the basic functions don't easily fit into any of the other categories I've created.

The message box is one of the most useful functions in VBScript. The two types of message boxes available to you are the message box and the input box.

### `InputBox`

The `InputBox` function makes it possible for you to get input from a user without placing a text control on the form. (See Figure 3.2.) It takes seven possible parameters:

Figure 3.2 : The input box in a VBScript-enabled page.

>     InputBox(prompt, title, default, xpos, ypos, helpfile, context)

All the arguments of the `InputBox` function are optional except `prompt`. Let's take a look at each of these parameters in detail.

#### `prompt`

The `prompt` argument is a string containing the question that you are asking your user:

>     InputBox("What is your name?")

#### `Title`

The `Title` argument determines the title of the dialog. This argument must be a string expression. If the title isn't specified, the title of the dialog defaults to the application name.

#### `default`

The `default` argument specifies a string that appears in the input box on the dialog when the dialog is displayed. Leave this parameter blank if you don't want the dialog to display default text.

#### `xpos` and `ypos`

The `xpos` and `ypos` arguments specify where in relation to the screen the dialog is displayed. These arguments are made in twips. The `xpos` argument specifies the horizontal value, and the `ypos` argument specifies the vertical value.

#### `helpfile` and `context`

The `helpfile` argument specifies a Windows Help file to open if the user presses the f1 button. If you specify a Help file, you also need to specify a context id.

The `context` argument specifies a Help context id number for the file called in the `helpfile` argument. The Help context id number opens the corresponding Help topic.

### `len`

The `len` function returns the length of a string or the number of bytes in a variable.

### `MsgBox`

You've been using the `MsgBox` function to test the VBScript language features that we've discussed so far. The message box is useful when you want to notify a user that an event has occurred. You can specify the buttons shown in the dialog, and the function returns a value that indicates which button was clicked:

>     MsgBox(prompt, buttons, title, helpfile, context)

The `helpfile` and `context` arguments in the `MsgBox` function are optional.

#### `prompt`

The `prompt` argument is a string value of up to 1024 characters. As with the `InputBox` function, you can use the carriage return line-feed combination `(Chr(13)& Chr(10))`, a carriage return `(Chr(13))`, or a line feed `(Chr(10))` to break the prompt into multiple lines:

>     Dim Message

>     Message = "This text is broken" + (Chr(13)& Chr(10)) + "into multiple lines."

>     MsgBox (Message, 0, "Message Title")

Figure 3.3 : Message box with a multiline caption.

#### `buttons`

The `buttons` argument is a VBScript constant or a numeric value that determines which buttons are displayed on the dialog. Table 3.1 lists the values and constants that you can use when calling this function.

Table 3.1. Settings for the `buttons` argument.

Value | Buttons shown
`0` | OK
`1` | OK, Cancel
`2` | Abort, Retry, Ignore
`3` | Yes, No, Cancel
`4` | Yes, No
`5` | Yes, No, Cancel
`16` | (Critical Message Icon)
`32` | (Warning Query Icon)
`48` | (Warning Message Icon)
`64` | (Information Message Icon)
`0` | (First button default)
`256` | (Second button default)
`512` | (Third button default)
`0` | (User must respond before continuing with application)
`4096` | (User must respond before continuing with the operating system)

#### `title`

The `title` argument is a string that specifies the text shown in the titlebar of the message box. If no title is specified, the title of the calling application is displayed.

#### `Helpfile` and `Context`

These arguments work the same as for `InputBox`. `Helpfile` specifies a Windows Help file, and `context` specifies the Help context id for the topic.

#### Return Values

The return values for the `MsgBox` function are the numeric or constant values of the button pressed. Table 3.2 lists the possible return values for the `MsgBox` function.

Table 3.2. Possible return values for the `MsgBox` function.

Button Clicked | Value
OK | `1`
Cancel | `2`
Abort | `3`
Retry | `4`
Ignore | `5`
Yes | `6`
No | `7`

Let's take a look at a procedure, shown in Listing 3.2, that does something with the return value from a `MsgBox` function.

> Listing 3.2. `MsgBox` return value.

>     <HTML>

>     <HEAD>

>     <TITLE>The MsgBox Returns</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBS</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

>     <SCRIPT LANGUAGE="VBScript">

>     <!--

>     Sub Btn1_OnClick()

>     Dim strQuestion, intReturn

>     Do Until intReturn = 7

>     strQuestion = "Do you want to see another dialog?"

>     intReturn=MsgBox(strQuestion, 4, "Question" )

>     Loop

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

In this script, the button on the page is clicked, and a yes/no message box is displayed asking whether the user wishes to see the message box repeated. If the answer stored in `intReturn` holds a value of `Yes` (6), then the dialog is redisplayed. If the user clicks `No` (7), the message box is closed and the script is ended until the button is pushed again.

### `VarType`

The `VarType` function returns the subvalue of a variable. This function is useful for verifying the contents of a variable or for checking the type of variable before trying to operate on it. Table 3.3 shows the possible return values for the `VarType` function.

Table 3.3. Possible return values for the `VarType` function.

Subtype | Value
(empty) | `0`
(null) | `1`
Integer | `2`
Long | `3`
Single | `4`
Double | `5`
Currency | `6`
Date | `7`
String | `8`
OLE Object | `9`
Error | `10`
Boolean | `11`
Variant | `12`
Non-OLE Object | `13`
Byte | `17`
Array | `8192`

You can use either the value or the constant to determine the return type. When the variable on which you're running the function is an array, the function returns the `vbArray` value added to the variable type in the array.

## String Functions

The following string functions act on string data to allow you to manipulate and parse strings. Parsing textual data means dividing it into logical divisions. Let's take a look at the various string-related functions and then look at an example that utilizes some of the functions.

### `Asc`

The `Asc` function takes a string as a parameter and returns the ASCII character code for the first character in the string:

>     Dim strData, intCharCode

>     strData = "This is a string"

>     intCharCode = Asc(strData)

In this code example, the function returns the value of `T`, which is 84. If you run this function on an empty string, it generates a runtime error.

### `Chr`

The `Chr` function takes a character code as a parameter and returns the corresponding character. Keep in mind that the characters for codes 0 to 31 are nonprintable:

>     StrMyString = "This is my two line" + (Chr(13) + Chr(10)) + "text string example."

In this example line, the string has a carriage return and a line feed added to the middle of the text. This will cause a break in the string, displaying it on two lines.

### `InStr`

The `InStr` function is a powerful text-searching tool that finds the position of text substrings within strings of text. This is a fairly complex function, so you should first be familiar with the function's syntax:

>     position = InStr(startpos, string1, string2, type)

The `InStr` function returns the position of the substring within the string. In this case, the return value is held by the variable position. Let's go through the other arguments individually.

#### `Startpos`

The `startpos` argument is a numeric value that tells the function where to start searching. This is an important argument because if you're thinking about adding search functions to your own string operations, you'll need to adjust the number as you find multiple occurrences of the search string in a large body of text.

#### `String1`

The `string1` argument is the string in which you are searching for the `string2` string.

#### `String2`

`String2` is the text for which you're searching.

#### `Type`

The `type` argument specifies the string comparison that you're performing. This argument can have a value of `0` (default) or `1`. A type `0` comparison is a binary comparison. The function will return a position only in the case of an exact match. An argument of `1` will do a non-case-sensitive, textual search.

We can see the difference between the two types of searches in the following code:

>     Dim strBigString, strSearchString, intReturn0, intReturn1

>     strBigString = "This is the BIG string"

>     strSearchString = "big"

>     intReturn0 = InStr( , strBigString, strSearchString, 0)

>     intReturn1 = InStr( , strBigString, strSearchString, 1)

In this sample, the `intReturn0` variable is set to `0` because the function does not find the string `"big"` in `strBigString`. The variable `inReturn1` is set to `13` because `strSearchString` is found in the non-case-sensitive search.

Table 3.4. Return values for the `InStr` function.

String Values | Return Values
`mainstring` length is 0 | `0`
`mainstring` is Null | Null
`searchstring` length is 0 | `startpos`
`searchstring` is Null | Null
`searchstring` not found | `0`
`searchstring` found | (position of string in `mainstring`)

If the value of `startpos` is greater than the length of `mainstring`, the function returns a `0`.

### `LCase`

The `LCase` function takes a string and converts all the characters to lowercase. It takes a string as an argument and returns the converted string.

### `Left`

The `Left` function returns a string containing the characters from the left side of the string, up to a specified number. The function takes two arguments, string and length:

>     Dim strMyString, strMain

>     strMain = "The rain in Spain..."

>     strMyString = Left(strMain, 15)

In this sample, the string variable `strMyString` would be set to `The r`, the first five characters of the string. If the number you specify in the length argument is greater than or equal to the length of the string, the function will return the entire string.

### `LTrim`

The `LTrim` function returns a copy of the string argument with the leading spaces removed from the string:

>     Dim strMyString, strMain

>     strMain = "    There are four leading spaces here."

>     strMyString = LTrim(strMain)

In this example, the functions returns the string, `"There are four leading spaces here."`

### `Mid`

The `Mid` function returns a substring of a specified length from another string. This function takes three parameters: string, start, and length. The length argument is optional.

>     Dim strMyString, strMain

>     strMain = "Ask not what your country can do for you..."

>     strMyString = Mid(strMain, 8, 10)

In this example, we're looking for a string that starts at character 8 and is 10 characters in length. The string value contained in `strMyString` is equal to `what your` .

### `Right`

The `Right` function works like the `Left` function, but it returns a specified number of characters starting from the last character in the string. This function takes the number of characters as an argument and returns a string:

>     Dim strMyString, strMain

>     strMain = "How now brown cow?"

>     strMyString = Right(strMain, 10)

In this example, `strMyString` is set to the last 10 characters of `strMain`, or `brown cow?`.

### `RTrim`

The `Rtrim` function works like the `Ltrim` function. It removes trailing spaces from a string. It takes a single argument, string, and returns a string.

### `Str()`

The `Str()`function takes a number as an argument and returns a string value representing the number. The first character in the resulting string is always a space that acts as a placeholder for the sign of the number. If you want to use a numeric value in a string or a function that takes a string as a parameter, you'll need to use this function or the `CStr` function to make the conversion first.

### `StrComp`

The `StrComp` function takes two strings as arguments and compares them, based on the third argument, which defines the type of comparison:

>     Dim RetVal, strString1, strString2

>     strString1 = "This is a string."

>     strString2 = "This is a STRING."

>     RetVal = StrComp(strString1, strString2, 1)

The `StrComp` function returns a numeric value that indicates whether the items are the same. The comparison type has two possible values: `0` (default) is a binary comparison, and `1` is non-case-sensitive. Table 3.5 show the return values for the `StrComp` function.

Table 3.5. Return values for the `StrComp` function.

Return Value | Description
`-1` | `String1 < String2`
`0` | `String1 = String2`
`1` | `String1 > String2`
`NULL` | One of the strings is null

### `String`

The `String` function takes a number and character code argument and returns the character, repeated a number of times:

>     Dim strRetString

>     strRetString = String(3, 97)

This example returns the string `"aaa"`. If the character code argument is greater than 255, the code is automatically converted to a valid character using the `formula charcode = (char Mod 256)`.

### `Trim`

The `Trim` function returns the string argument, with leading and trailing spaced removed.

### `UCase`

The `UCase` function converts all the characters in the string argument to uppercase.

### `Val`

The `Val` function takes a string argument and returns numbers from the string. The function stops retrieving numbers as soon as it hits a non-numeric character:

>     Dim MyNumber, strMyString

>     MyString = "300 South Street"

>     MyNumber = Val(strMyString)

In this example, the function returns the number 300. The `Val` function recognizes decimal points and radix prefixes. A radix prefix is a prefix that defines an alternative numbering system. The `&O` prefix is used for octal values and `&H` for hexadecimal.

## Conversion Functions

Conversion functions enable you to change the subtype of a variable. Although VBScript uses the variant type for all variables, in many cases an argument of a certain type is required. An example would be a function that takes a string argument. If you want to be able to use numeric data, you'll need to convert it to a string before calling the function.

### `CByte`

The `Cbyte` function converts an expression to the subtype byte.

### `CDbl`

The `CDbl` function converts an expression to the subtype double.

### `CInt`

The `CInt` function converts an expression to the subtype integer.

### `CLng`

The `CLng` function converts an expression to the subtype long.

### `CStr`

The `CStr` function returns a string from a valid expression. Table 3.6 lists the return values for various expression types.

Table 3.6. Return values for the `CStr` function.

Return Value | Expression Type
True or False | Boolean
Short-Date | Date
Runtime Error | Null
" " | Empty
Error(#) | Error
Number | Number

### `CVErr`

The `CVErr` function returns the subtype error. It takes any valid error number as an argument.

## Math Functions

Math functions enable you to perform operations on numbers in your VBS scripts. You'll find these functions fairly straightforward.

### `Abs`

The `Abs` function takes a number as a parameter and returns its absolute value. The absolute value of a number is the numerical value of a number without considering its sign. An argument of `-7` would return the value `7`.

### `Array`

The `Array` function returns a variant value containing an array. The array can be of any subtype. This function takes a list of values separated by commas as a parameter.

### `Atn`

The `Atn` function returns the arctangent of a number, a trigonometric function that is used to determine angles in triangles. This function is the inverse of tangent (`Tan`), which calculates the ratio of sides in a right triangle. It takes a number as an argument.

### `Exp`

The `Exp` function takes a numeric argument and returns `e` (the base of natural logarithms) raised to a power.

### `Hex`

The `Hex` function returns a string value containing the value of an argument converted to hexadecimal form. If the argument is a fractional value, it is rounded to the nearest whole number before the function returns the string.

Keep in mind that this function returns a string. If you want to perform mathematical operations on the returned value, you must first convert the string back into a numerical value. Hexadecimal numbers are represented in VBScript using the `&H` prefix.

### `Int`

The `Int` function returns the whole number portion of an argument. If the argument is negative, `Int` returns the first integer value that is less than or equal to the argument.

### `Fix`

The `Fix` function works like the `Int` function, returning the whole number portion of an argument. The difference is that if the number argument is negative, `Fix` returns the first integer value that is greater than or equal to the argument.

### `Log`

The `Log` function returns the natural logarithm of a numeric argument. The numeric argument that this function processes must be greater than zero.

### `Oct`

The `Oct` function returns a string representing the octal value of a numeric argument. If the numeric argument is fractional, it is rounded up before the function returns a value. As with the `Hex` function, the returned string must be converted back to numeric form before you can perform mathematical operations on it. To use an octal value mathematically, you use the `&O` prefix.

### `Rnd`

The `Rnd` function takes a numeric argument and returns a value between zero and one. The number generated depends on the numeric argument in relation to the values in Table 3.7.

Table 3.7. Number value determines generation technique.

Number Value | Generates
`<0` | Same number every time
`>0` | Next random number
`=0` | Last generated number
`""` | Next random value in sequence

If you want to generate a range of random numbers, use the following formula:

>     Int((upperbound - lowerbound + 1)*Rnd + lowerbound)

Let's use the `Rnd` function to create a program (see Listing 3.3) that generates random numbers. Random numbers are often used in computer games and simulations. We'll use this function to create a page that generates random Lotto numbers. Figure 3.4 shows the page in action.

Figure 3.4 : The Play 3 generator in action.

> Listing 3.3. `Lotto.htm`.

>     <HTML>

>     <HEAD>

>     <TITLE>Play 3 Generator</TITLE>

>     </HEAD>

>     <BODY><CENTER>

>     <H1>Play 3 Generator</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click for the lucky numbers!"><BR><BR>

>     <INPUT TYPE="SUBMIT" NAME="BtnBall1" VALUE="">

>     <INPUT TYPE="SUBMIT" NAME="BtnBall2" VALUE="">

>     <INPUT TYPE="SUBMIT" NAME="BtnBall3" VALUE="">

>     <SCRIPT LANGUAGE="VBScript">

>     <!--

>     Sub Btn1_OnClick()

>         BtnBall1.Value = RndBall()

>         BtnBall2.Value = RndBall()

>         BtnBall3.Value = RndBall()

>     End Sub

>     Function RndBall()

>         RndBall = (Int((9-0+1)*Rnd+0))

>     End Function

>     -->

>     </SCRIPT>

>     </CENTER>

>     </BODY>

>     </HTML>

You'll find that random number generation can really spice up your pages. You'll see more random number examples later in this book when we work with other controls that can be manipulated dynamically.

### `Sgn`

The `Sgn` function returns a numeric value representing the sign of a number argument. It returns `1` if the number is greater than zero, `0` if equal to zero, and `-1` if less than zero.

### `Sqr`

The `Sqr` function returns the square root of a numeric argument. The argument value must be greater than or equal to zero.

### `Sin`

The `Sin` function returns the sine of an angle.

### `Tan`

The `Tan` function returns the tangent of an angle.

## Time and Date Functions

You'll find time and date functions extremely useful in customizing your Web pages. You can add automatic time and date stamping to pages, and you can write programs that provide useful calendar functions.

### `Date`

The `Date` function takes no arguments and returns the current system date. In Figure 3.5, the `Date` function returns the date value in the tester page.

Figure 3.5 : The Date function returns the date value in the tester page.

### `DateSerial`

The `DateSerial` function takes year, month, and day arguments and returns a variant of subtype date. The year argument can be any year between 100 and 9999. The month and day arguments are numeric values.

### `DateValue`

The `DateValue` function takes a string argument containing a valid date and returns a variant of subtype date. This is an extremely useful function, because it interprets a number of formatted date strings. For example, you could use "January 1, 1999," "1/1/99," or "Jan 1, 1999" as an argument. Once the date is a variant of subtype date, other date functions can be used on it.

### `Day`

The `Day` function takes a date argument and returns the day as a numeric value between 1 and 31.

### `Hour`

The `Hour` function takes a time argument and returns an hour value between 0 and 23.

### `Year`

The `Year` function takes a date value and returns the year.

### `Weekday`

The `Weekday` function takes a date and optionally a `firstdayofweek` argument and returns a numeric value representing the day of the week. If `firstdayofweek` isn't specified, the function defaults to Sunday. The settings for `firstdayofweek` are shown in Table 3.8.

Table 3.8. Day constants.

Day | Numeric Value
System * | `0`
Sunday | `1`
Monday | `2`
Tuesday | `3`
Wednesday | `4`
Thursday | `5`
Friday | `6`
Saturday | `7`

*This value is used only in the `firstdayofweek` argument and is not a return value.

Listing 3.4 takes a string that you enter, converts the string to date format, and then runs the `Day` function against the date. The return value is then converted to a string that sends the day of the week to the message box. There is no error checking built into the script, so a nonvalid date entry will result in a runtime error. Figure 3.6 shows the results of Listing 3.4.

Figure 3.6 : What day did it happen?

> Listing 3.4. `Day.htm`.

>     <HTML>

>     <HEAD>

>     <TITLE>Day of the week</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>What day did it happen?</H1>

>     <HR COLOR="BLUE">

>     Enter any valid date and click the button to find out what day it was!<BR>

>     <INPUT TYPE="TEXT" NAME="TxtDate"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Tell me the day of the week">

>     <SCRIPT LANGUAGE="VBScript">

>     <!--

>     Sub Btn1_OnClick()

>         Dim DayVal, Message, MyDate

>         MyDate = DateValue(TxtDate.Value)

>         DayVal = Weekday(MyDate)

>             If DayVal = 1 then Message = "Sunday"

>             If DayVal = 2 then Message = "Monday"

>             If DayVal = 3 then Message = "Tuesday"

>             If DayVal = 4 then Message = "Wednesday"

>             If DayVal = 5 then Message = "Thursday"

>             If DayVal = 6 then Message = "Friday"

>             If DayVal = 7 then Message = "Saturday"

>         Message = "It happened on a " + Message + "."

>         MsgBox Message, 64,"When did it happen?"

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

### `Minute`

The `Minute` function retrieves the minute value of a time value.

### `Month`

The `Month` function returns a numeric value for the month from a valid date.

### `Now`

The `Now` function returns the current date and time from the client machine. This function takes no arguments.

### `Second`

The `Second` function returns the seconds value from a time value.

### `Time`

The `Time` function returns the current system time as a date subtype variant.

### `TimeSerial`

The `TimeSerial` function takes hours, minutes, and seconds as arguments and returns a variant of subtype date. The hour argument is an integer between 0 and 23.

### `TimeValue`

The `TimeValue` function takes a string containing a valid time and returns a variant of subtype date containing the time.

You can use this function to get input from the user and convert it to a date format. Valid values for the time argument include times from 12- and 24-hour clocks.

## Boolean Functions

Boolean functions always return a value of `true` or `false`. Each of the functions listed in Table 3.9 tests for the truth of a condition.

Table 3.9. Boolean functions.

Function | Tests
`IsArray` | Is variable an array?
`IsDate` | Is expression a date?
`IsEmpty` | Has the variable been initialized?
`IsError` | Is this an error value?
`IsNull` | Is this a null value?
`IsNumeric` | Is this a numeric value?
`IsObject` | Is this variable an object?

These Boolean functions are important because VBScript has little built-in error checking and no debugger other than Internet Explorer. You can use the Boolean functions to test data before trying to feed the data into functions where it might cause an error.

Listing 3.4 had no built-in error checking. Listing 3.5 shows the same program with a feature to check whether the data from the text input box is a valid date.

> Listing 3.5. `DayChk.htm`.

>     <HTML>

>     <HEAD>

>     <TITLE>Day of the week</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>What day did it happen?</H1>

>     <HR COLOR="BLUE">

>     Enter any valid date and click the button to find out what day it was!<BR>

>     <INPUT TYPE="TEXT" NAME="TxtDate"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Tell me the day of the week">

>     <SCRIPT LANGUAGE="VBS">

>     <!--

>     Sub Btn1_OnClick()

>         Dim DayVal, Message, MyDate, blnCheck

>     blnCheck = IsDate(TxtDate.Value)

>     If blnCheck = True then

>         MyDate = DateValue(TxtDate.Value)

>         DayVal = Weekday(MyDate)

>             If DayVal = 1 then Message = "Sunday"

>             If DayVal = 2 then Message = "Monday"

>             If DayVal = 3 then Message = "Tuesday"

>             If DayVal = 4 then Message = "Wednesday"

>             If DayVal = 5 then Message = "Thursday"

>             If DayVal = 6 then Message = "Friday"

>             If DayVal = 7 then Message = "Saturday"

>         Message = "It happened on a " + Message + "."

>         MsgBox Message, 64,"When did it happen?"

>     Else

>     Message = "You must enter a valid date."

>     MsgBox Message, 48,"Error"

>     End If

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

If you run `DayChk.htm` and enter an invalid date, instead of having the script crash with a runtime error, you'll see a message box telling you that the date you entered was not valid. You'll learn more about techniques that you can use to deliver error-free code in Chapter 11, "Optimizing Code."

## Review

In this chapter, you learned about procedures in VBScript. You read about functions intrinsic to VBScript and looked at some examples that illustrate the usefulness of functions.

In the next chapter, you'll learn about VBScript's built-in controls and how these basic controls are used to create powerful HTML documents.

| Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details.