VBScript basic knowledge of language

Source: Internet
Author: User
Tags error handling execution expression functions object model variables split variable
VBScript

A VBScript language overview

We all hope that the Web pages made are exquisite, beautiful, lively and powerful, and can be achieved with VBScript language.

VBScript is a simplified version of Microsoft Visual Basic.

VBScript was designed specifically to work in a browser.

Programming methods are basically the same as Visual Basic.

VBScript has only one data type, that is, a variant type.

VBScript does not support the traditional I/O feature in Visual Basic, that is, you cannot read and write files on the client computer through open statements and functions, thus preventing possible harm to the client; VBScript cannot invoke API functions. This is because API function calls can compromise the security of the client, such as a virus that easily destroys a client through API function calls, and Visual basic supports system objects such as screen, Printer, App, Debug, err, and clipboard, However, VBScript only supports the Err object, which is used to provide run-time error handling for the application.

Two VBScript language Features

Easy to learn and easy to use

VBScript can write both server script and client script.

The advantage of the client programming language is that

(1) The browser has done all the work, which can reduce the burden on the server.

(2) The client program runs much faster than the server-side program.

In general, browsers that can interpret VBScript scripts are only Microsoft Internet Explorer.

Three editing and debugging of VBScript programs

You must use the <SCRIPT> tag to use the scripting language in the following format:

<SCRIPT>

VBScript code

</SCRIPT>

For example, we could write "Hello, learn VBScript interesting" to HTML pages with a VBScript statement.

<script language= "VBScript" >

<!--

Window.Document.Write ("Hello, it's fun to learn VBScript!") ")

-->

</SCRIPT>

Explains the use of the Document object in the previous example:

In the Document Object Model (DOM), the Window object is the highest-level object, and the document object is a child of the Window object, so you should use window.document when referencing the documents object, and write () Is the method of the Document object, you should use Window.Document.Write () when referencing the Write () method.

Another example:

<script language=vbscript>

<!--

Window.alert ("Hello")

-->

</SCRIPT>

<SCRIPT> Language properties of labels

The language type used to specify the script code contained in the <SCRIPT> label.

<script language= "VBScript" >

<script language= "JavaScript" >

<script language= "JScript" >

<SCRIPT> Runat properties of labels

The Runat property is used to specify whether the script code contained in the <SCRIPT> tag is run on the server or the client.

<script language= "VBScript" runat=server>

VBScript code

</SCRIPT>

Note: The file is to be saved as. asp, and the runat attribute can be omitted if the client is running.

Application of annotation Label

<script language= "VBScript" >

<!--

VBScript code

-->

</SCRIPT>

For browsers that do not support VBScript, the VBScript code will be displayed directly on the page as the text of the page, which will greatly damage the layout of the entire page, so we need to use the annotation tag to solve the problem.

Four Use VBScript to write content on the Web page.

The following example of VBScript code is the ability to write "This is a simple example of VBScript" on the page.

<HTML>

<HEAD>

<TITLE> a VBScript example </TITLE>

<script language= "VBScript" >

<!--

Window.Document.Write ("This is a simple example of VBScript")

-->

</SCRIPT>

</HEAD>

<BODY></BODY>

</HTML>

Example of a warning box that can appear when a button is pressed.

<HTML>

<HEAD>

<TITLE> a VBScript example </TITLE>

</HEAD>

<BODY>

<FORM>

<input type= "button" value= "ALERT" >

</FORM>

</BODY>

</HTML>

<script language= "VBScript" >

<!--

Sub Alerter ()

Window.alert ("This is a simple example of VBScript")

End Sub

-->

</SCRIPT> implementation

Five The location of VBScript code is different in order of execution

Run immediately on download and not included in the process VBScript code is embedded between the <HEAD> tags and </HEAD> tags, and this VBScript code is executed before the page is drawn. For example

Sometimes we don't want VBScript code to execute before the page is drawn, but rather to be able to process it in the page drawing, where the page is appropriate.

For example

Run immediately on download and not included in the process VBScript code is embedded between the <HEAD> tags and </HEAD> tags, and this VBScript code is executed before the page is drawn. For example

Sometimes we don't want VBScript code to execute before the page is drawn, but rather to be able to process it in the page drawing, where the page is appropriate. For example

Another way to solve this problem is to write a table label directly on the page and then use VBScript code to write a string in the table. For example.

Where to run VBScript code when called

In general, it's best to place VBScript code between <HEAD> tags and </HEAD> tags, which is not a mandatory requirement for scripting, but a good writing style. For example.

There is also an embedding method for embedding VBScript code (typically one line) in page element event handling.

<input type= "button" value= "ALERT"

onclick= "Window.alert (' This is a simple example of VBScript ')" > For example.

Six Client Script code example

When opened in a browser, a text box and a button are displayed. After you enter a number in the text box, click the Submit button and the browser finds and executes the procedure Button1_onclick. The Submit method that invokes the form is submitted to the server at execution time. If the input is not correct, if not a number or less than 1 or greater than 50, the MsgBox statement is invoked to generate a message box prompting for the correct number.

Seven VBScript data type

VBScript has only one data type, called a Variant.

A variant can further differentiate the specific meaning of numeric information. For example, use numeric information to represent a date or time.

See VBScript Data type Table

1. What is a constant

A constant is a name that has a meaning, used in place of a number or string, and its value never changes. VBScript defines a number of intrinsic constants.

2. Declaring constants

Use the Const statement to create a user-defined constant in VBScript. For example:

Const MyString = "This is a string. "

Const Myage = 49

Note that the string literal is contained between two quotes (""). The date text and time text are contained between two pound numbers (#). For example:

Const cutoffdate = #6 -1-03#

3. VBScript variables

A variable is a named memory location in the computer's memory that stores information that can be changed while the script is running.

In VBScript scripts, the use of variables does not require an understanding of the variable's address in the computer's memory, and can be viewed or changed by referring to a variable name.

4. declaring variables

Statement format: DIM myvar1, Myvar2, MYVAR3

In VBScript scripts, you do not need to specifically declare a variable before you use it.

Implicit declaration variables are called implicitly by using variable names directly in the script.

It is not a good habit to declare variables implicitly, and it is a good habit of programming to declare variables to be used first.

The Option Explicit statement is provided in VBScript to force an explicit declaration of a variable, so if you are writing a long and complex program, if you knock the wrong name of the variable, you will have an error that can help you debug the script. For example.

5. Variable naming rules

Variable naming must follow VBScript's standard naming conventions. Variable naming must follow:

(1) The first character must be a letter.

(2) cannot contain an embedded period.

(3) The length cannot exceed 255 characters.

(4) must be unique within the scope declared.

(5) You cannot use reserved words in VBScript as variable names.

Naming variables in VBScript is case-insensitive. When naming variables, it's best to be able to remember and use them for ease of memory and usage.

6. Comment VBScript Script

Rem Comment

' Comment

For example:

Dim MYSTR1,MYSTR2

MYSTR1 = "Hello": Rem statements and annotations are separated by colons.

MYSTR2 = "Goodbye" ' This is also a comment that does not require a colon.

Rem comments on lines without code does not have to be a colon.

REM I am a VBScript comment.

' I am also a VBScript comment.

7. Continuation line characters in VBScript scripts

When a line is written very long in a VBScript script, the readability of the program becomes very poor, and if the syntax is not able to wrap, and we want to change lines, we can use a continuation character, which is a space immediately following an underscore ("_"). Please note: Be sure not to forget the preceding spaces.

Please note: Be sure not to forget the preceding spaces.

Eight VBScript data type

1. Arithmetic operators in VBScript

The operator used to perform mathematical calculations.

In VBScript, 7 arithmetic operators are provided, with (+), minus (-), multiplying (*), excluding (/), and taking negative (-) several operators the same meaning as in mathematics.

\ (divisible operator)

In VBScript, Integer division first rounds the operands to make the operand an integer, then the division operation, and the integer division operation results in an integer, 1.5\2=1, and 1.4\2=0.

MoD (modulo operator)

Divides two operands and returns the remainder after division, for example, the result of the expression 5 mod 3 is 2. The results of the 38.57 mod 14.21 (rounded and fetched first) result in 11.

2. Connection operators

(1) + (plus operator)

The addition operator can also operate on the operands of the string type and then connect the two strings together as the result of the operation. For example, "How are" + "you! "The result of the operation is" how are you! "。

(2) & (Join operator)

A connection for a string that joins two string variables to generate a new string. The + operator can also concatenate strings, but only two strings are connected. The & operator can force a string concatenation of two expressions, regardless of type, and an error occurs when connecting to other types of data with the + operator.

3. comparison operator

The comparison operator compares the operands and returns a logical value indicating whether the result of the comparison operation is true, and the operands of the comparison operator can be numeric or string-type data. A total of 6 comparison operators. The difference is.

=, >, <, >=, <=, <>

In addition to numeric types, string types can be compared, and in the process of comparing strings, VBScript converts each letter in the string to the corresponding ASCII value, and then compares the corresponding characters in two strings from the first character to compare their ASCII values.

4. Comparison operator Example

For example, the return result of "Hello" = "Hello" is false, because the first character of the left-hand operand is H, and the ASCII value of the first character of the right operand is h,h with a value of 72 ASCII code of 104,H, which is not equal starting from the first character, So the value of the expression is false.

And if the expression is "came" >= "Come", first, comparing the first character of the two operands, which is C, does not directly determine the size of the two operands, then compares the second character of the two operands, the left operand is a, and the right-hand operand is o,a with an ASCII value of 97, The ASCII value of O is 111, of course 97<111, so for this expression, it returns a false result.

5. logical operators

and (with operator)

result = expression1 and expression2

If and only if all two expressions are true, result is true. If any of the expressions are false, result is false.

or (or operator)

result = expression1 Or expression2

If at least one of the two expressions is true, result is true.

Not (non-operator)

A non-operator has only one operand, and when the operand is true, the return result is false, and the result is true when the operand is false. For example, the expression not (2>3) logical operation result is true because the result of 2>3 is false, and the logical operation of expression not (2<3) evaluates to false because the result of 2<3 is true.

6. Operator Precedence

Operation, the operator in parentheses is always executed first, and then the operators outside the parentheses are executed.

The arithmetic operator is evaluated first, then the comparison operator is computed, and the logical operator is finally computed. All comparison operators have the same precedence, that is, the comparison operator is computed in left-to-right order.

Nine scalar variables and array variables

In most cases, you simply assign a value to the declared variable. A variable that contains only one value is called a scalar variable. Sometimes it is more convenient to assign multiple related values to a variable, so you can create a variable that contains a series of values (that is, a set of variables with different subscript values of the same name), called an array variable.

1. Declaring a fixed array

An array variable and a scalar variable are declared in the same way, except that the variable name is followed by parentheses () when the array variable is declared. Unlike the variables discussed earlier, an array must be declared before it is used.

For example: Dim A (10)

Note: The subscript of an array in VBScript starts at 0. The example above declares a one-dimensional array that contains 11 elements.

2. Declaring a dynamic array

Currently discussed are limited to fixed-size arrays. Once you have declared a fixed-size array, you will not be able to change the number of elements in the array. To change the size of a fixed array, you must delete it and recreate it. Another type of array in VBScript is called a dynamic array. A dynamic array is an array that can be resized at run time.

When declaring a dynamic array, you do not need to specify the size and dimension of the array, just add a pair of empty parentheses after the array name. However, before assigning a value to a dynamic array for the first time, you must specify its size and dimension with the ReDim statement. For example

Ten Process Control Statements

1. Conditional Control Statement

(1) Only one conditional statement form: Example

An If condition expression then

Statement block

End If

(2) The form of the statement to run separately when the condition is True and False: Example

An IF condition expression then

Statement Block 1

Else

Statement Block 2

End If

(3) If Judge structure nesting use: example

If condition expression 0 Then

If condition expression 1 Then

Statement Block 1

Else

Statement Block 2

End If

Else

Statement Block 3

End If

(4) ElseIf structure: Example

If condition expression 1 Then

Statement Block 1

ElseIf conditional Expression 2 Then

Statement Block 2

ElseIf conditional Expression 3 Then

Statement Block 3

......

ElseIf conditional expression N Then

Statement block N

Else

Statement Block n+1

End If

(5) Use Select case to judge: example

Select Case Test Expression

Case Expression List 1

[Statement Block 1]

[Case expression Column Expression 2

[Statement Block 2]]

......

[Case Else expression list n

[statement block N]]

End Select

2. Loop Control statement

(1) do ... Loop Loop Example 1

You can use do ... The Loop statement runs a block of statements multiple times (indeterminate). Repeats the statement block when the condition is true or the condition becomes true.

Do ... Loop Statement form:

The first form of grammar is to judge the cyclic condition first

Do [{while | Until} condition]

[Statements]

[Exit do]

[Statements]

Loop

Do ... Loop Loop Example 2 cases 3

The second form of syntax is to perform a loop first and then judge the cyclic condition

Todo

[Statements]

[Exit do]

[Statements]

Loop [{while | Until} condition]

(2) while ... Wend Cycle

While ... The Wend statement executes a series of statements when the specified condition is True. The grammatical form is:

While condition

[Statements]

Wend

(3) for ... Next Loop example

For ..... The next statement repeats a set of statements at a specified number of times.

The general form of the statement is:

For counter = start to end [step step]

[Statements]

[Exit for]

[Statements]

Next

For ..... Next Loop Nesting example

You can put a for ... Next loop is placed in another for ... Next loop, which makes up a nested loop. The counter in each loop will use a different variable name.

(4) for Each ... Next Loop example

For Each ... Next Loop with for ... Next loop is similar. For Each ... Next is not to run the statement the specified number of times, but to repeat a set of statements for each element in the array or for each item in the collection of objects. This is useful when you do not know the number of elements in the collection.

For Each ... The general form of the Next statement is as follows:

For each element in group

[Statements]

[Exit for]

[Statements]

Next [element]

(5) on Error statement

Syntax form: on Error Resume Next

When an error occurs, the statement executes the statement immediately following the error statement, or executes the statement immediately following the calling process.

Sub Cmdsubmit_onclick

On Error Resume Next

Myvar= "AAA" +30

' shows the description that caused the error

If Err <> 0 Then

Msgbox "An error occurred." & Err.Description

Err.Clear

End If

End Sub

Xi. Process and function according to

1. Sub-procedure Example 1 cases 2 cases 3

Declares the name of a Sub procedure, its parameters, and the code that constitutes its body.

Sub name [(arglist)]

[Statements]

[Exit Sub]

[Statements]

End Sub

Note: Sub procedures are public by default, that is, they are visible to all other procedures in the script. The value of a local variable in a Sub procedure is not retained during the call.

Note: You cannot define a Sub procedure in any other procedure (for example, a Function).

Call statement

Passes control to a sub or Function procedure. The general form of the statement is as follows:

[Call] name [ArgumentList]

An option keyword. If you specify this keyword, you must enclose the argumentlist in parentheses. For example:

Call MyProc (0)

You can call the same process any number of times.

2. Function process cases in 1 cases in 2 cases 3 cases 4

Declares the name of a Function procedure, its parameters, and the code that constitutes its body, in the form of a general statement:

Function name [(arglist)]

[Statements]

[NAME = expression]

[Exit Function]

[Statements]

[NAME = expression]

End Function

is essentially the same as a Sub procedure, unlike a Sub procedure: a function has a return value and the procedure does not. To return a value from a function, simply assign the value to the function name within the function. Any such assignment can occur anywhere in the function. If you do not assign a value to name, the procedure returns a default value: The numeric function returns 0, and the string function returns a 0-length string ("").

3. Input and output functions

The input and output functions mentioned below can only be used on the client side and cannot be used on the server.

(1) InputBox function

The grammatical forms are:

InputBox (Prompt[,title][,default][,xpos][,ypos][,helpfile,context])

Displays a prompt in the dialog box, waits for the user to enter text or clicks a button, and returns the contents of the text box. For example

Dim Input

input = InputBox ("Enter name")

MsgBox ("Entered name is:" & input)

(2) MsgBox Function Example 1

Displays a message in a dialog box, waits for the user to click the button, and returns a value indicating the button the user clicked.

MsgBox (Prompt[,buttons][,title][,helpfile,context])

Dim MyVar

MyVar = MsgBox ("Hello world!", "MsgBox Example")

' Returns 1 or 2 depending on the clicked button.

4. String functions

In VBScript, the system provides a number of string functions to handle things about strings.

(1) Left function

Grammar form: Left (string,length)

Returns the specified number of characters from the left of the containing string.

(2) Right function

Grammatical form: Right (string,length)

Returns a specified number of characters that are fetched from the right of the string.

(3) Mid function

Grammatical form: Mid (String,start[,length])

Returns a specified number of characters in a string.

(4) Space function

Grammatical form: space (number)

Returns a specific number of spaces.

(5) Ltrim, Rtrim, Trim function

Syntactic form: LTrim (String), RTrim (String), Trim (String)

Returns a copy containing the specified string without leading white space (LTrim), trailing white space (RTrim), or leading and trailing blanks (Trim).

(6) InStr function

Grammatical form:

INSTR ([Start,]string1,string2[,compare])

Returns the position of the first occurrence of a specified string in another string.

(7) LCase function

Syntactic form: LCase (String)

Returns a string that is converted to lowercase.

(8) UCase function

Syntactic form: UCase (String)

Returns a string that is converted to uppercase.

(9) Len function

Syntactic form: Len (string|varname)

Returns the number of characters in the containing string, or the number of bytes required to store a variable.

(Ten) Chr function

Grammatical form: Chr (charcode)

Returns the character of the ASCII code table corresponding to the charcode.

(one) ASC function

Syntax form: ASC (String)

Returns a character ASCII that represents the first letter in a string.

(a) Split function

Grammatical form:

Split (Expression[,delimiter[,count[,start]])

Returns a one-dimensional array of subscripts starting at 0 that contains the specified number of substrings.

Replace function

Returns a string in which a specified number of substrings are replaced with another substring.

Grammatical form:

Replace (Expression,find,replacewith[,compare[,count[,start]]])

(StrComp) function

Grammatical form:

StrComp (string1, string2[, compare])

Returns a value that indicates the result of a string comparison.

() string function

Grammatical form:

String (Number,character)

Returns a Variant (String) that contains a string that specifies the length of a repeating character.

() filter function

The filter function function is to filter a string array, returning a subset of composite groups that meet the criteria.

Grammatical form:

Filter (Inputstrings,value[,include[,compare]])

(strreverse) function

Grammatical form: strreverse (string1)

Returns a string in which the character order of a specified substring is reversed.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.