Skip navigation

Understanding VBScript: Built-In and User-Defined Functions

Downloads
6185.zip

As I mentioned last month, a function is a block of instructions that affects the data a script is handling. In a script, you can use the functions that VBScript provides (i.e., built-in functions) or you can create unique functions (i.e., user-defined functions).

If you've read previous installments of this column, you've already learned about a few built-in functions, such as the IsNumeric and Array functions. This month, I analyze two popular built-in functions that let users provide input: MsgBox and InputBox. MsgBox displays a dialog box in which users can click buttons to provide input. InputBox displays a dialog box in which users can type text to provide input. However, before I discuss these two functions, you first need to know how to call them into action.

The Call Statement
You use the Call statement to prompt a built-in or user-defined function into action. The Call statement's syntax is

\[Call\] function name \[arguments\]

As the syntax shows, the Call keyword isn't mandatory. (In VBScript syntax, square brackets specify that the enclosed element is optional.) Thus, both of these statements call MsgBox:

Call MsgBox ("Hi")
MsgBox "Hi"

Note the difference in how you treat the optional argument "Hi". If you use the Call keyword, you must put arguments in parentheses.

The MsgBox Function
MsgBox lets you display a dialog box that has a title bar, message, icon, and one or more buttons. The function's syntax is

MsgBox(prompt\[, buttons\]\[, title\] _
   \[, helpfile, context\])

As the syntax shows, MsgBox has four arguments: prompt, buttons, title, and helpfile-context.

Prompt. The mandatory prompt argument contains the text you want the dialog box to display. You can include the text in the function with code such as

MsgBox "Hi"

Or, you can assign the text to a string variable and include that variable in the function:

strMessage = "Hi"
MsgBox strMessage

Including the text in the function is best if the dialog box's message isn't subject to change.

Buttons. The optional buttons argument evaluates to a number that denotes the characteristics of the dialog box. One characteristic is the type of buttons you want. Table 1, page 2, shows the available button combinations and the corresponding constant you specify in the function. For example, if you want to display a dialog box with the Yes-No button combination, you specify

MsgBox strMessage, vbYesNo

If you incorporate more than one button in your dialog box, you need to know which buttons users are selecting so that you can take appropriate action. You can obtain this information by examining MsgBox's return value. You can assign the return value to a variable

retc = MsgBox(strMessage, vbYesNo)

or use it directly with code such as

If MsgBox(strMessage, vbYesNo) = _ vbNo Then
   WScript.Quit
End if

To use a function's return value, you need to enclose the function's arguments in parentheses. After you capture MsgBox's return value in retc, you can use a Select Case statement to compare that value against the values in Table 2 to determine the appropriate action to take. (See my September column for information about how to use the Select Case statement.)

You can use the buttons argument to specify other dialog box characteristics, such as the box's icon and default button. You can't assign any icon you want, but you can choose from the icons in Table 3. To add an icon, you append the Or operator and the icon's VBScript constant to the buttons argument. (For more information about the Or operator, see my August column.) For example, if you want to add the Question Mark icon to the dialog box containing the Yes-No button combination, you type

retc = MsgBox(strMessage, vbYesNo _ Or vbQuestion)

The default button is the button that activates when you press Enter or the spacebar. In a dialog box, the default button typically has a shadow to show its status. To specify which button is the default, you use one of four VBScript constants: vbDefaultButton1, vbDefaultButton2, vbDefaultButton3, or vbDefaultButton4. For example, to make the No button the default in the Yes-No button combination, you use the vbDefaultButton2 constant because No is the second button in that combination. To specify the default button, you append the Or operator and then the constant to the buttons argument:

retc = MsgBox(strMessage, vbYesNo _ Or vbQuestion Or vbDefaultButton2)

Title. The optional title argument specifies the caption that goes in the dialog box's title bar. No matter what caption you specify, the system appends that string to the text VBScript:. So, for example, if you specify "Important Message" as your caption, the dialog box's title will be VBScript: Important Message.

Helpfile-context. You use the optional helpfile-context argument to specify what kind of help users get when they click Help or press F1. This argument consists of two values: the helpfile value, which is a filename path that specifies which Help file to open, and the context value, which is a page ID that specifies what page within that Help file to open.

You can opt to specify the helpfile value and not the context value. However, you can't specify just the context value. When you specify the helpfile value, MsgBox automatically adds a Help button to the dialog box. Microsoft designed MsgBox so that in a dialog box with four buttons, Help must be the fourth button.

The Help button isn't a return button. In other words, when users click Help, the system opens the specified Help file but doesn't return control to the script until they click another button. For more information about Help, go to the "Designing Help Windows" section in the HTML Help Authoring Guide on the Microsoft Developer Network (MSDN) Web site at http://msdn.microsoft.com/workshop/ author/htmlhelp/hh_online_docs2/dswin.asp.

The InputBox Function
InputBox displays a dialog box with a fixed template. The function's syntax is

InputBox(prompt\[, title\] _
   \[, default\]\[, xpos\]\[, ypos\] _
   \[, helpfile, context\])

Prompt is the only mandatory argument. It specifies the message for the user. The title argument specifies the caption in the title bar. Once again, the system appends your caption to the text VBScript:. The default argument is the default response that appears in the edit box (i.e., the box in which users enter their input). For example, if you use the code

str=InputBox("Placethemessage" _
   & "for the user here", _
   "This is the title", _
   "This is the default value")

users see the edit box that the dialog box in Screen 1 shows. If you were to omit the default argument from this code, the edit box would be empty.

In the dialog box in Screen 1, the prompt message is one line. By default, the maximum length of the message is up to 1024 characters. The dialog's template reserves a fixed area for the message, so if you use a wider system font, fewer characters fit. If your message is longer, you can distribute the message in two (or more) lines, as the code in Listing 1 shows. You begin this code by splitting your message into two strings and assigning those strings to two variables. You then specify those variables as InputBox's prompt argument. You need to include the VBScript constant vbCrLf between the two variables to insert a line return. The concatenation (&) operator joins the strings and the constant in the correct order. The system automatically adjusts the overall height of the dialog box to fit the number of the rows needed to display your message.

You use the xpos and ypos arguments to position the dialog box. By default, the system centers the dialog box horizontally on the page and places it vertically about one-third of the way down the screen. You use xpos to change the horizontal position and ypos to change the vertical position. You express xpos and ypos in twips rather than pixels. (A twip is a unit of length that is equal to 1/1440 of an inch.)

The last argument is the helpfile-context pair. This argument operates the same way for InputBox as it operates for MsgBox.

InputBox returns the string the user enters in the edit box. If the user cancels the dialog box, the system returns an empty string. You can test whether the system returns a valid value (i.e., a nonempty string) or an invalid value (i.e., an empty string) with code such as

str=InputBox("Entertheinvoice" _ & "number")
If str = "" Then Wscript.Quit

The first line of this code creates a dialog box displaying the message Enter the invoice number and assigns the result to the str variable. In this case, the result is either the number the user enters or an empty string if the user selects cancel. The second line uses an If...Then...Else statement to test whether the str variable holds an empty string. If it does, the script quits. Otherwise, the script continues to execute.

Writing User-Defined Functions
MsgBox and InputBox are easy to use, but they might not be able to give you the functionality you need. Some of their limitations are minor. For example, neither function lets you remove the VBScript prefix from the caption on the title bar. Other limitations are more significant. For example, MsgBox doesn't let you specify a custom icon or custom button, and InputBox doesn't let you attach any code that validates or formats the data that users enter in the edit box.

If you need more functionality, you can create a user-defined function. You declare and define a function with the Function statement

Function funcName\[(arguments)\]
   \[statements\]
   \[funcName = return value\]
End Function

where funcName is the name of your function. When you name your function, you must not give it the same name as any VBScript keywords. After you declare your function's name and any arguments, you include any statements that you want the function to execute. If you want to use the function's return value, you need to assign the value to a pseudovariable that has the same name as the function.

For example, suppose you want a function that returns tomorrow's date. You can extend the capability of the VBScript Now function, which returns the current date, to provide that value. By increasing the Now function's return value (i.e., the current date) by 1, you get tomorrow's date. This user-defined function, called the GetTomorrow function, does just that:

Function GetTomorrow()
   GetTomorrow = Now + 1
End Function

For another example of how you can create a user-defined function that extends the capability of VBScript components, see the Web-exclusive sidebar "Building a Better InputBox Function" on the Win32 Scripting Journal Web site at http://www.winntmag.com/ newsletter/scripting. This sidebar describes how to create the InputBoxEx() function, which not only produces a dialog box but also validates the data users enter in it.

You can also download two COM components that extend MsgBox's and InputBox's capabilities even further. I created these components for my book Windows Script Host Programmer's Reference, but you can download them for free on the Wrox Press' Programmer to Programmer File Download and Samples Web page. Go to http://www.wrox.com/store/ download.asp. In the Show me files available for drop-down list, select Windows Script Host Programmer's Reference and click Download Source Code. From that point, just follow the instructions.

Next Month
Next month, my coverage of functions will continue. I'll show you how to use VBScript functions to manipulate strings.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish