Data types
The VBScript language uses a single data type - Variant, which allows you to store a number, string, date, Boolean value, object reference and other information in a variable. You can determine the content type of a variable using a set of functions: VarType , TypeName, IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, which will be discussed below. The type of information contained is also called a variant subtype. The complete list of subtypes is given in the following table:
Subtype | Description |
---|---|
Empty | The variable has not been assigned a value. When using an uninitialized variable in numeric expressions, 0 will be substituted, and in string expressions, an empty string will be substituted. |
Null | The variable contains no data. |
Boolean | A Boolean variable can take the values True or False. |
Byte | An integer ranging from 0 to 255. |
Integer | An integer in the range -32,768 to 32,767. |
Currency | A fixed-point number in the range -922,337,203,685,477.5808 to 922,337,203,685,477.5807. |
Long | An integer in the range -2,147,483,648 to 2,147,483,647. |
Single | Single precision floating point number. For negative values the acceptable range is from -3.402823E38 to -1.401298E-45. For positive ones – from 1.401298E-45 to 3.402823E38. |
Double | Double precision floating point number. For negative values, the acceptable range is from 79769313486232E308 to -4.94065645841247E-324. For positive ones - from 4.94065645841247E-324 to 1.79769313486232E308. |
Date (Time) | Contains a number representing a date in the range from January 1, 100, to December 31, 9999. |
String | Sequence of characters. The maximum length is around 2 billion characters. |
Object | An object. |
Error | Error number. |
Depending on the expression in which the variable is involved, its contents will be automatically cast to the desired type. Consider this example:
Option Explicit Sub TestVBScript Dim A, B A = 5 B = "12" Application.MessageBox A + B, "", vbOkOnly End Sub
Since the expression involves a numeric variable A, the interpreter converts the value of the variable B from string "12" into a number and sums them up:
Let's change the macro so that the variable A also contained the line:
Option Explicit Sub TestVBScript Dim A, B A = "5" B = "12" Application.MessageBox A + B, "", vbOkOnly End Sub
Let's run it. Now the result of the merger (concatenation) of two strings will appear on the screen, and not the sum of their numeric representations:
To avoid confusion with automatic type casting, it is recommended to use the conversion functions: CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr.
If the result of the expression should be a concatenation of strings, and not the sum of their numeric representations, then the & operator should be used instead of +.
Variables
A variable is a convenient symbolic representation of an area of memory where an application stores some data. During application execution, the value of a variable can change. Before use, a variable must be declared using the Dim statement.
Using one operator, you can declare several variables at once, if you list their names separated by commas:
Dim Left, Right, Top, Bottom
When declaring, there is no need to specify the data type, since all variables are of type Variant.
If Option Explicit is not specified in the first line of the script text, then variables can be used without declaration. But this path can lead to difficult-to-detect errors. It is enough to misspell a variable name in the program text once to get an unpredictable result. We recommend that you always specify Option Explicit and declare variables.
The variable name must meet the following requirements:
- Begin with a symbol of the Latin alphabet;
- Consist only of characters of the Latin alphabet or characters of the Latin alphabet and numbers;
- Do not exceed 255 characters in length;
- Be unique within its scope.
Scope and lifetime
The scope of a variable is determined by where it was declared. If inside the body of a procedure, then such a variable is called local and is available only within this procedure. If a variable is declared in the text of a script, then it will be visible to all procedures or functions defined in this script. Local variables can have the same names if they are declared in different procedures.
In the Explorer tree of the Script Object Editor window there is a special section - Constants and Variables - for declaring global variables visible to all script functions of the project.
The interpreter allocates memory for local variables at the time they are declared and releases them upon exit from the procedure. Global variables exist from the moment they are declared until the script finishes executing. In relation to Gedymin, this means that global variables exist throughout the entire execution of the program.
Assigning a value to a variable
The value of a declared variable is assigned using the = operator. The variable name is indicated to the left of the operator, the new value is indicated to the right. For example:
A = 200 B = "Name"
Scalar Variables and Arrays
A variable containing a single value is called a scalar. Sometimes, there is a need to store several values in one variable. In this case, you should declare an array. The syntax of the declaration is identical to the declaration of a scalar variable, with the exception that after the name in parentheses we specify the size of the array. The following declaration will create an array of 12 elements:
Dim Monthes(11)
In VBScript, the left bound of an array index is always 0. Thus, the size of the array is calculated as the number in parentheses plus one. When assigning a value to an array element, specify its index in parentheses:
Monthes(0) = "January" Monthes(1) = "February" Monthes(2) = "March" ... Monthes(10) = "November" Monthes(11) = "December"
Similarly, when accessing the value of an element, we use its index:
MonthName = Monthes(5)
The array does not have to be one-dimensional. VBScript allows us to specify up to 60 dimensions when declaring an array. For example, the following statement will create a two-dimensional array of 12 rows and two columns:
Dim MonthDays(11, 1)
When accessing elements of a multidimensional array, all indices must be specified:
MonthDays(0, 0) = "January" MonthDays(0, 1) = 31 MonthDays(1, 0) = "February" MonthDays(1, 1) = 28 ...
Above we declared arrays whose size does not change during program operation. If you don’t know in advance how many elements you will need, you can declare a dynamic array:
Before use, you should set the size of the dynamic array using the ReDim operator:
ReDim A(25)
During execution, you can call the ReDim operator multiple times, changing the size of the array each time. The Preserve option preserves the values of array elements when resizing. For example, the following code will increase the array declared above by five elements, leaving the existing ones untouched:
ReDim Preserve A(30)
Remember that when reducing the size of the array, the values of the deleted elements will be irretrievably lost. Using the Erase operator, you can clear the elements of a fixed array or free the memory occupied by a dynamic array.
Dim A ReDim A(25) ... Erase A
Constants
It is a good rule of thumb to declare constants for values that are used repeatedly in the program text. A correctly assigned constant name improves readability, and its use itself simplifies the process of making changes to the code. Unlike variables, the value of a constant cannot be changed during program execution. A constant is created using the Const operator:
Const CountryName = "Belarus" Const CountryCode = 375
Several constants can be declared within one statement, separated by commas. Like a variable, a constant has its own scope depending on where (in a procedure or outside it) and how (Public or Private) it was declared. Constants created by the Const operator without specifying Public or Private are public by default.
In the Explorer tree of the Script Object Editor window there is a special section - Constants and Variables - for declaring global constants visible to all script functions of the project.
The values of string constants are enclosed in double quotes.
Values of type Date should be surrounded by hash symbols (#) and use the American format: month/day/year. For example:
Const Public IndependenceDay = #03/25/1918#
To avoid confusion between constants and variables, it is recommended to use a single prefix for all constants, such as "con", or type the constant name in upper case.
To make the programmer's work easier, VBScript contains a set of predefined constants.
Operators
VBScript operators fall into five categories: arithmetic, comparison, merge, logical, and assignment.
Arithmetic operators
Operator | Usage example | Description |
---|---|---|
^ | number^exponent | Raises number to exponent. Number can only be less than zero if it is an integer power. If one of the operands is Null, the entire expression is Null. If several exponentiations are performed in a row, the result is calculated from left to right. |
* | number1 * number2 | Product of two numbers. If the operand has the value Empty, then it is assumed to be zero. If at least one of the operands is Null, the entire expression evaluates to Null. |
/ | number1 / number2 | Real division of two numbers. The rules for operands are similar to the multiplication operator. |
\ | number1\number2 | Integer division. Before evaluation, both operands are cast to Byte, Integer, or Long. Otherwise, the same rules apply as for the division operator. |
Mod | number1 Mod number2 | Remainder of integer division. Casting operands to an integer, as well as rules for handling Empty and Null, like integer division. |
+ | expression1 + expression2 | If both operands are numbers, the result is their arithmetic sum. If both operands are strings, it is a merger (concatenation) of two strings. If one operand is a number and the other is a string, then the string operand will be converted to a number and added to the numeric one. If at least one of the operands is Null, the entire expression evaluates to Null. If both operands are Empty, the result has the integer value 0. If only one operator is Empty, the value of the second operand is returned as the result. |
- | number1 – number2 or - number | In the first case, it returns the difference of two numbers. In the second, it inverts the sign of the number. Rules for operands with Null and Empty values, as for the multiplication operator. |
Comparison Operators
Format for using comparison operators:
Result = expression1 comparisonoperator expression2
where the following comparison operators are used:< (меньше), <= (меньше или равно), >(greater than), >= (greater than or equal to), = (equal to),<>(not equal).
Depending on the types and values of the operands, the comparison is carried out as follows:
If | That |
---|---|
Both operands are numbers. | A comparison is made between two numbers. |
Both operands are strings. | A comparison of two strings is performed. |
One of the operands is a number, and the second is a string. | The string operand is cast to a number and a comparison is made between the two numbers. |
One of the operands is Empty, and the second is a number. | The operand with the value Empty is assumed to be 0. |
One of the operands is Empty, and the second is a string. | The operand with the value Empty is assumed to be the empty string "". A comparison is made between two strings. |
Both operands are Empty. | The operands are considered equal. |
At least one of the operands is Null. | The result is Null. |
The special Is operator is used to compare two object variables and returns True if both variables refer to the same object instance.
Concatenation Operators
Result = expression1 & expression2
If the operand is not a string, it is cast to string type. If both operands are Null, then the result also takes the value Null, however, unlike the other operators, if only one operand is Null, then it is taken equal to the empty string. An operand set to Empty is also treated as the empty string "".
Logical operators
VBScript provides us with the following logical operators:
- Logical exception(Xor);
- Logical equivalent (Eqv);
- Logical implication (Imp).
The operands of logical operators can be Boolean expressions or numeric values. In the first case, the result will be a Boolean constant, in the second - a number. Depending on the operator, supplying one or two Null values as input can lead to a Null result. The Not operator is unary and returns the logical negation of an expression. The Not operator performs a bitwise inversion on a numeric operand. The remaining logical operators are binary. The table below shows the results of executing each of the operators depending on the value of the operands Exp1 and Exp2:
Exp1 | Exp2 | And | Or | Xor | Eqv | Imp |
---|---|---|---|---|---|---|
True | True | True | True | False | True | True |
True | False | False | True | True | False | False |
False | True | False | True | True | False | True |
False | False | False | False | False | True | True |
True | Null | Null | True | Null | Null | Null |
False | Null | False | Null | Null | Null | True |
Null | True | Null | True | Null | Null | True |
Null | False | False | Null | Null | Null | Null |
Null | Null | Null | Null | Null | Null | Null |
In life, the operators And and Or are most often used, and much less often - Xor. We have not encountered the use of the Eqv and Imp operators in practice. If you find it difficult to understand the table above, let’s summarize the action of these operators:
- And evaluates to True only if both operands are True. In any other case, it is either False or Null.
- Or evaluates to True if at least one of the operands is True.
- Xor evaluates to True if the values of the operands are different and False if they are the same.
When executed bitwise on numeric operands, the result of a logical operator is determined by the following table:
Exp1 | Exp2 | And | Or | Xor | Eqv | Imp |
---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 | 1 | 0 | 1 |
1 | 0 | 0 | 1 | 1 | 0 | 0 |
1 | 1 | 1 | 1 | 0 | 1 | 1 |
Assignment operator
The assignment operator (=) is described in detail in the Variables section.
The order of application of operators
If an expression contains multiple operators, they are applied in accordance with a specified order, called operator precedence. You can change the default order using parentheses. The expression inside the parentheses is always evaluated first.
In an expression containing operators of different categories, arithmetic operations are performed first, then comparison operators are performed, and logical operators are performed last. All comparison operators have the same precedence and are evaluated from left to right. Arithmetic and logical operators are evaluated in the following order:
- Exponentiation (^);
- Change the sign of a number, unary minus (-);
- Multiplication (*) and division (/);
- Integer division (\);
- Integer division remainder (Mod);
- Addition (+) and subtraction (-);
- String concatenation (&).
If multiplication and division occur in the same expression, then the operations are performed in left-to-right order. A similar rule applies in the case of the simultaneous presence of addition and subtraction operators.
The string concatenation operator (&) is not arithmetic and has precedence between arithmetic and comparison operators.
The order of priority for logical operators is as follows:
- Logical negation, inversion (Not);
- Logical multiplication, conjunction (And);
- Logical addition, disjunction (Or);
- Logical exception(Xor);
- Logical equivalent (Eqv);
- Logical implication (Imp).
Conditional Expressions
Conditional expressions are used to control the order of execution of program commands and allow you to organize transitions (branching) and repetition of commands. Typically, comparison operators are used in conjunction with conditional expressions.
If..Then..Else expression
The If conditional jump expression allows you to execute a particular group of commands depending on the result of a logical expression or the value of a Boolean variable.
To execute a single command when a given condition is met, use one-line expression syntax:
Dim S If DatePart("w", Now) = vbMonday Then S = "Monday" Application.MessageBox S, "", vbOkOnly
Note that the Else section is omitted in this case. To execute a group of statements, you must enclose them between the Then and End If keywords.
Dim S If DatePart("w", Now) = vbMonday Then S = "Today is Monday" Application.MessageBox S, "", vbOkOnly End If
If, when a condition is met, one code needs to be executed, and when a condition is not met, another code is required, then the expression syntax with an Else section is used:
Dim S If DatePart("w", Now) = vbMonday Then S = "Today is Monday" Else S = "Today is not Monday" End If Application.MessageBox S, "", vbOkOnly
If you need to choose from several alternatives, the syntax with the ElseIf construct is suitable:
Dim S, D D = DatePart("w", Now) If D = vbMonday Then S = "Monday" ElseIf D = vbTuesday Then S = "Tuesday" ElseIf D = vbWednesday Then S = "Wednesday" ... End If Application. MessageBox S, "", vbOkOnly
If statements can be nested:
Dim S, D D = DatePart("w", Now) If D = vbMonday Then S = "Monday" Else If D = vbTuesday Then S = "Tuesday" Else If D = vbWednesday Then S = "Wednesday" Else ... End If End If End If
Although there is no limit to the number of ElseIf clauses in a conditional expression, using them extensively can result in confusing, unreadable code. In case of selecting one alternative from many possible ones depending on the value of a selector, it is recommended to use the Select Case expression.
Select..Case expression
Let's rewrite the days of the week example using a selection expression:
Dim S Select Case DatePart("w", Now) Case vbMonday S = "Monday" Case vbTuesday S = "Tuesday" Case vbWednesday S = "Wednesday" ... Case Else Err.Raise 32000, "", "Unknown day of week " End Select
Since the selector expression is evaluated only once, using Select..Case results in more efficient code. It is recommended to always use the Case Else section to catch invalid or raw selector values.
Loop statements
Quite often a situation arises when the code needs to be re-run. To do this, write a loop statement that repeats certain commands over and over again. Loop statements are used in many situations: when calculating a total over a list of numbers, moving through the records of a data set, or to run a block of code on multiple objects. There are several cycles, described in the following sections. Some of them are executed while the condition is True, some are executed while the condition is False. And finally, there are those that are executed a specified number of times.
Do..Loop operator
This operator is designed to execute a group of commands until a given condition is True or until it becomes True. The condition can be checked as at the beginning of the loop:
Do [(While | Until) condition] Loop
and so at the end:
Do Loop [(While | Until) condition]
The Exit Do command can appear an unlimited number of times in the body of a loop. Typically used in conjunction with an If..Then conditional statement, it allows control to be transferred to the statement immediately following the loop. When using Exit Do inside a nested loop, control will pass to the outer loop.
The following code allows you to replace the dice:
Dim Resp, Num Do Num = Int(6 * Rnd + 1) Resp = Application.MessageBox(Num & "Another number?", "",_ vbYesNo or vbQuestion) Loop Until Resp = vbNo
While..Wend
It is a truncated version of the Do..Loop operator and allows you to execute a group of commands as long as the condition is True. Operator syntax:
While condition Wend
Note that Exit Do has no effect within this loop. While..Wend loops can be nested.
For..Next
This loop repeats a given set of commands a specified number of times. The operator syntax is:
For counter = start To end Next
Before the loop starts, the counter variable is assigned the value start. Next, the counter condition is checked.<= end, при step >= 0, or counter >= end, with a negative step. After executing a block of commands, the counter variable is increased by the value of step and everything is repeated from the beginning.
Changing the counter in the body of a loop is not prohibited, but it is strongly discouraged, as it makes it difficult to understand the program logic and debug it.
Exit For can appear in the body of a loop any number of times. Loops can be nested. For example, this loop initializes a three-dimensional array:
Dim A(9, 9, 9) Dim I, J, K For I = 0 To 9 For J = 0 To 9 For K = 0 To 9 A(I, J, K) = 1 Next Next Next
For Each..Next
The For Each..Next loop statement repeats a specified set of commands for each element of an array or collection and has the following syntax:
For Each element In group Next
The loop is executed if there is at least one element in the array or collection. Exit For can appear in the loop body an arbitrary number of times.
Let's illustrate the use of For Each..Next with the following code, which displays a list of files from the root directory of drive c:\
Dim fso, f, f1, fc, s Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder("c:\") Set fc = f.Files For Each f1 in fc s = s & f1 .name & vbNewLine Next Application.MessageBox s, "Files at c:\", vbOkOnly
Procedures
To save memory and structure the program, a piece of code that is called repeatedly in different places can be formatted as a procedure. There are two types of procedures in VBScript: subroutines (Sub) and functions (Function). A subroutine is a sequence of statements surrounded by the keywords Sub and End Sub. The subroutine can accept parameters as input, but does not return values. A function, a sequence of statements between a Function and an End Function, returns a result and can therefore be used in an expression. Each procedure must have a name that is unique within the module. The names of procedures declared in a global module must be unique within the entire project.
The definition of a subroutine and function has the following syntax:
| Private] Sub name [(arglist)] End Sub | Private] Function name [(arglist)] End Function
Public procedures are global and available in all program scripts. Private procedures are only available in the script where they were declared. Unless otherwise specified, the declared procedure is public. The Default keyword can only be used in the body of a class and serves to specify the default method of this class.
The parameter list has the following syntax:
Varname [, ...]
Parameters can be passed by value (ByVal) or by reference (ByRef). By default, all parameters are passed by value. Constants, the results of evaluating expressions, can be passed only by value. Changing the parameter passed by reference will change the value of the external variable. Let us explain the passing of parameters inside a procedure using the following example:
Sub DoCalculation(ByRef A, ByVal B, ByVal C) A = C * 2 B = C / 2 End Sub Sub TestVar Dim V1, V2 V1 = 1 V2 = 2 DoCalculation V1, V2, 10 " After performing the DoCalculation procedure " V1 = 20" V2 = 2 End Sub
Variables declared inside the body of a procedure are local and are destroyed upon completion of its execution. Local variable values are not saved.
The parameter list is specified in parentheses when calling a function or when calling a subroutine using the Call statement. So, we could write the call to the DoCalculation procedure in the example above as follows:
Call DoCalculation(V1, V2, 10)
Execute expression
VBScript Classes
VBScript allows you to create new classes, which we will henceforth call VB classes. Generally speaking, they are not full-fledged classes in the sense of object-oriented programming, since they do not support inheritance and, accordingly, polymorphism. So, of the three pillars on which the object-oriented paradigm is based, only encapsulation remains - the ability to combine data and methods within one entity.
A class is defined using the following construct:
Class name statements End Class
where name is the name of the class, and statements are one or more definitions of variables, properties, procedures or functions, also called members of the class. Please note that unlike Delphi, where the class definition code contains only declarations of procedures and functions, in a VB class the member code is written directly in the class text.
Members of a class can be declared Private or Public. The former are visible only inside the code of a given class, while the latter are available both to internal code and externally. If a variable or function (procedure) does not contain an explicit definition of Public or Private, then it is considered public. Procedures or functions declared as Public inside a class block become methods of that class.
Variables declared as public become class properties along with properties declared directly using the Property Get, Property Let, Property Set constructs.
Defining Class Properties
We already said above that the fields of a class, explicitly or implicitly declared as Public, become its properties. In addition, you can create a class property by defining special functions for reading the property value (Property Get), as well as for assigning it (Property Let or Property Set).
The syntax for defining such functions is as follows:
| Private] Property Get name [(arglist)] [ name = expression] [ name = expression] End Property Property Let name ( value) End Property Property Set name( reference) End Property
By defining only one function, read or assign, you can create a property that is read-only or write-only, respectively. The Property Let procedure is used to assign simple data types, and the Property Set procedure is used to pass a reference to an object. Please note that all three functions can take an arbitrary list of parameters as input. In this way, you can organize, for example, array properties by passing the element index as an argument.
Creating and destroying an instance of a VB class
Creating an instance of a VB class is done using the New operator.
Dim X Set X = New classname
The destruction of a previously created instance occurs automatically upon completion of the block of code where the corresponding variable was declared and provided that there are no external references to it. If you need to destroy the instance manually, you must assign the value Nothing to the variable.
‘ declaring a variable and creating an instance of the class Dim X Set X = New classname ... ‘ using an instance of the class... ‘ destroying an instance of the class Set X = Notning ...
Initialize and Terminate events
The Initialize event occurs when an instance of a class is created, and the Terminate event occurs when it is destroyed. The developer can define his own event data handlers. Below is an example of using object creation and deletion events:
Class TestClass " Definition of the Initialize event handler. Private Sub Class_Initialize MsgBox("TestClass started") End Sub " Definition of the Terminate event handler. Private Sub Class_Terminate MsgBox("TestClass terminated") End Sub End Class " Creating an instance of the TestClass class. " The message "TestClass started" will be displayed Set X = New TestClass " Destroying the instance. " The message "TestClass terminated" Set will be displayed X = Nothing
Continuation
Visual Basic Script
Why do we need VBS scripts?
VBS script is a powerful solution for automating user actions on Windows systems. This type of script is typically used for:
- creating complex scenarios;
- using objects from other applications and libraries;
- hiding windows during script execution;
- encryption of script logic.
VBS scripts are mainly used for data processing, system management, working with user and computer accounts, interacting with office applications, working with databases and other complex tasks.
Basic provisions
Depending on the script language, content and encryption, the following types of scripts are found:
- vbs - Visual Basic Script
- vbe - encrypted Visual Basic Script
- js - Java Script
- jse - encrypted Java Script
- wsh - script settings
- wsf - XML federated script
In this article I will look at vbs type scripts.
Scripts are usually edited in Windows Notepad, but I recommend using Notepad2, which highlights Visual Basic language keywords and helps format the body of the script. So, a vbs script is a regular text file named *.VBS, which can be easily edited in Notepad and executed by double-clicking or calling the name in the console.
As described above, scripts are not compiled, but rather interpreted. That is, to process a script, the system must have a VBS language interpreter, and there are even two such interpreters in Windows: window WScript and console CScript - both interpreters are Windows Script Host (WSH).
By default, all scripts are executed through WScript, that is, no settings are required, but to execute a script in the console window, you need to run it through CScript, or set CScript as the default interpreter. To do this, you need to run the following on the command line:
CScript //H:CScript
After which all scripts will be executed in console mode. Returning to windowed mode is carried out with the following command:
CScript //H:WScript
The following rules work in Visual Basic:
- line length is not limited;
- Character case is not sensitive;
- the number of spaces between parameters is not taken into account;
- the command line can be broken, and at the break place you need to insert the symbol "_";
- maximum variable name length is 255 characters;
- comments are indicated by the symbol " " ".
" === Script Information Header === " Script Name: " name of the script; " Date: " modification date; " Author: " author; " Description: " description; " === Initialization Block === Option Explicit " directive , which prohibits the automatic creation of " variables; Dim
Variables
By default, variables in scripts are declared automatically the first time they are used in the script body, unless prohibited by the Option Explicit directive. If you declare the Option Explicit directive at the beginning of the script, then all variables must be defined in advance using the following constructs:
Dim
Constants are declared at the beginning of the script using the following construct:
Const
The variable type is assigned automatically after the first value is entered into it. The following data types exist in Visual Basic:
- empty - uninitialized variable;
- null - empty variable;
- boolean - logical type, possible values: False, True or 0, 1;
- byte - 8-bit unsigned integer, possible values: 0 .. 255;
- integer - 32-bit integer, possible values: -32768 .. 32767;
- long - 64-bit integer, possible values: -2147483648 .. 2147483647;
- currency - monetary type, possible values: -922337203685477.5808 to 922337203685477.5807;
- single - floating point number, possible values: -3.402823e38 .. -1.401298e-45 for negative numbers and 1.401298e-45 .. 3.402823e38 for positive numbers;
- double - floating point number, possible values: 1.79769313486232e308 .. -4.94065645841247e-324 for negative numbers and 4.94065645841247e-324 .. 1.79769313486232e308 for positive numbers;
- date - date, possible values: 01/01/1900 and 01/31/9999;
- string - string variable, capacity up to 2 billion characters;
- object - pointer to an object;
- error - error code.
Data can be checked for type compliance, as well as converted from one type to another, if the values allow this. The following commands are used for operations on data types:
VarType(
As mentioned above, Visual Basic does not impose strict restrictions on variable names, but at the same time, there are guidelines for variable names so that the data type can be easily identified in script text. To do this, it is recommended to precede the variable name with conditional symbols that determine the type of the variable:
- iValueName - numeric types
- sValueName - string type
- bValueName - boolean type
- dValueName - date
- oValueName - object
- cValueName - constant
- aArrayName - array
In VBS scripts, it is possible to use arrays of variables that allow you to store lists, tables, and even more complex structures. One-dimensional arrays (lists) can be dynamic, that is, they allow their dimension to change as the script runs. All arrays are declared with the Dim command:
Dim
Example of using arrays
Dim aMyArray1(10,10) "creates a static array with dimensions 11x11; Dim aMyArray2() "creates a dynamic array; aMyArray1(0,0) = "Hello" " filling the array; aMyArray1(0,1) = "People" " filling the array; aMyArray1(1,0) = "World" " filling the array.
Before using a dynamic array, it needs to indicate the current dimension using the ReDim command, after which the array can be reformatted anywhere in the script, either clearing the entire array or saving the old cell values with the Preserve command:
ReDim aMyArray2(0) " forming an array from one element; aMyArray2(0) = "Hello" " filling the array; ReDim aMyArray2(1) " removing the old array and forming a new one from " other elements; aMyArray2(0) = "Hello" " filling the array; aMyArray2(1) = "World" " filling the array; ReDim Preserve aMyArray2(2) " forming an array of three elements, leaving " the old values of the elements in the cells where they were; aMyArray2(1) = "!" " filling an array; Erase aMyArray2 " deleting an array.
To find out the dimension of an array, they usually use the UBound function, which will be discussed below along with other functions for working with data.
Branching by condition
Not a single full-fledged scenario is complete without branches; branches help to choose the right path when some underlying condition is fulfilled or not. In other words, branches implement the logic of the script. VBS scripts implement several branching mechanisms. Let's look at them in order.
Construction for one action performed according to a condition:
If
A design for several actions performed based on a condition:
If
Fork design:
If
Construction "fork into several paths" (option cIf):
If
In all the above constructions, the following rule applies: “If the condition is satisfied
Construction "fork into several paths" (option withSelect):
Select Case
The following rule works in this construction: “If the value of a variable
Cycles
Loops are usually used to organize repeated actions or iterate through array elements. In VBS scripts, several types of loops are organized: a regular loop, a loop with an unknown number of iterations, a conditional loop.
A regular loop is organized by the For - Next structure, the arguments of which specify parameters such as the name of the counter (
For
If you need to stop iterating over values while the loop is running, you can do this using the Exit For command
For
A loop with an unknown number of iterations is typically used to iterate through all the values in a collection of an object when its dimension is unknown. This structure will iterate over all values (
For Each
For Each oCurrentFile In oFiles WScript.Echo oCurrentFile.Name Next
Conditional loops are used to process data when some condition is met. There are two types of such loops: with a check at the beginning of the cycle and with a check at the end.
Loop until the condition is met, checking at the beginning
Do While
Loop until the condition is met, checking at the beginning
Do Until
As mentioned above, conditions can be placed at the end of the loop. In this case, the body of the loop will be executed at least once. Just like in regular loops, a loop with a condition can be interrupted with the Exit Do command:
Do
Built-in functions
To work with data and build their procedures and functions, Visual Basic developers have already taken care of the basis of scripts - basic functions. VBS scripts functions for working with dates, strings and numbers, as well as basic input-output procedures and networking procedures. Let's take a quick look at the built-in functions.
Date processing functions:
Date " return the current date; Time " return the current time; Now " return the current date and time; DateDiff(
String processing functions:
Asc(
Math functions:
Randomize " initializes the random number engine (returns nothing); Rnd " returns a random non-integer value from 0 to 1; Atn(
And, of course, in addition to the functions mentioned, the scripts support all the simplest mathematical and logical operations:
- = - assignment operator;
- + - the sum of two numbers;
- - - subtraction of two numbers;
- * - multiplication of two numbers;
- / - division of two numbers;
- \ - integer division of two numbers;
- Mod - remainder of division of two numbers;
- ^ - exponentiation;
- & - concatenation of two strings;
- Is - comparison of two objects;
- Eqv - comparison of two expressions;
- Not - logical negation operation;
- And - logical conjunction operation;
- Or - logical operation of disjunction;
- Xor - logical exclusion operation;
- Imp is the logical operation of implication.
The order of operations is determined as in all programming languages: first the operations in parentheses are performed, then the functions are calculated, then the operations of multiplication and division, followed by addition and subtraction, and the logical operations complete the calculation.
Custom Functions
Scripts written in Visual Basic allow you to define custom procedures and functions and call them from the main program. There is practically no difference between a procedure and a function, the difference lies in the logical meaning of these routines: functions are usually used to calculate some value, and procedures are used to perform actions. However, both procedures and functions can perform operations and pass values to the main program. Despite this, we should not forget about the purpose of these subroutines: functions for calculations, procedures for actions.
A function is declared by the Function operator, followed by the name of the user-defined function, which must not coincide with any reserved word of the Visual Basic language, then the variables that will be passed to the subroutine as parameters are indicated - specifying variables in this construction means allocating memory cells for the subroutine variables (declaration variables for the function). In the body of the subprogram, the structure of the script is no different from a regular program (here you can declare additional variables, perform operations, use other functions and procedures); at the end of the body there must be an operator assigning a function to some value - this value will be returned to the main program. You can interrupt the execution of a function using the Exit Function statement, but in this case you must remember to assign some value to the function, otherwise the script will throw an error. The function ends with the End Function statement.
Function Definition
Function
Calling a function
A procedure is defined similarly to a function, but with a different -Sub operator. Since the procedure does not return any values to the main program, there is no assignment statement before exiting the procedure. You can interrupt the execution of the procedure using the Exit Sub command, and the entire construction ends with the End Sub operator. To call a procedure in the main program, you must use the keyword Call and the name of the function with the necessary arguments. (The Call keyword is optional, but I recommend using it to avoid incorrect procedure calls.)
Procedure Definition
Sub
Calling a procedure
By the way, procedures and functions should be located at the end of the script.
While the subroutine is running, the values of the variables in the main part of the script do not change, even if the subroutine contains variables of the same name. In order for the subroutine to be able to change the values of the main script variables, it is necessary to set the variable property as ByRef in the subroutine arguments. By default, all variables are defined with the ByVal property.
Sub
In this case the argument
Handling script execution errors
By default, all errors are processed by the script automatically, and if an error occurs, the script stops running. To disable automatic error handling, you need to use the special On Error Resume Next directive, which disables automatic error handling and continues the script even if there are errors. To manually handle errors, you need to access the built-in Err object, which stores the error status. The Err object has the following properties and methods:
Number " return the number of the last error; Description " return the description of the last error; Clear " clearing the object Err; Raise " calling a test error.
Example of manual error handling:
On Error Resume Next iTotalPoints = InputBox("Enter the total number of points") iNumberOfTests = InputBox("Enter the number of tests") iAvarage = iTotalPoints / iNumberOfTests Select Case Err.Number Case 0 " no errors; WScript.Echo "Average score = " & CStr(iAvarage) Case 11 " division by zero; WScript.Echo "The number of tests cannot be zero" Case 13 "type mismatch; WScript.Echo "You entered a non-numeric value "Case Else" no errors; WScript.Echo "Unknown error WScript.Quit" End Select
Objects, their methods and properties
VBS scripts, like their parent Visual Basic, is an object-oriented programming language, that is, the main concept is the concept of objects and classes
A class is a type that describes the structure of objects. An object means something that has a certain behavior and way of representation; an object is an instance of a class. A class can be compared to a blueprint according to which objects are created. Typically, classes are designed in such a way that their objects correspond to the objects of the domain.
So, to work with an object, you must first create it using classes from the required library:
Set
You can delete an object by assigning it the value Nothing:
Set
All objects that Windows Script Host works with have methods and properties. To access a method, you must specify an object, followed by a dot - a method with the necessary parameters.
The situation is similar with properties, but properties can be both assigned and read into variables and other properties, however, you should take into account the data type of the variables and properties, otherwise the script will throw a data type incompatibility error.
Example. Creating a file system object, calling the folder creation method, deleting the object. Set oFSO = CreateObject("Scripting.FileSystemObject") Call oFSO.CreateFolder("C:\Test") Set oFSO = Nothing Note that the term "object" refers to script logic, not filesystem logic. That is, when we say “deleting an object,” we mean a logical script object that does not in any way affect the removal of any parts of the file system. To find out what libraries exist in your operating system, the classes included in the libraries, their methods and properties, you can use the object explorer, for example from Microsoft Word: If a library is not reflected in the list, it can be connected through the Tools -> References menu. Scripts have methods that are not part of any class; they are available directly in the body of the script: MsgBox( An example of displaying a dialog box asking for text, and then displaying a window message with the entered text. MyValue = InputBox("Enter text", "First window", "Text must be entered here") MyResult = MsgBox(MyValue, 1, "Second window") Methods and properties of the WScript root class do not require the creation of an object - they are automatically available for use directly in the body of the script. CreateObject( We will discuss the use of these methods and properties in more detail in examples of other classes. To work with the operating system, a special Shell class is used, which allows you to perform such operations as launching programs, changing the registry, creating shortcuts, accessing system folders and system variables, and accessing the system log. So, the methods and properties of the Shell class: ExpandEnvironmentStrings( Example. Using methods and properties of the Shell class. " Creating an object of the Shell class Set oShell = Wscript.CreateObject("WScript.Shell") " Running the calculator oShell.Run("Calc.exe") " Delay WScript.Sleep(100) " Running the notepad oShell.Run("Notepad.exe ") " Delay WScript.Sleep(100) " Switch to the calculator window oShell.AppActivate "Calculator" " Delay WScript.Sleep(100) " Simulate keystrokes oShell.SendKeys("1(+)2(=)") " Receive path to the desktop sDesktopPath = oShell.SpecialFolders("Desktop") " Creating a shortcut object Set oLink = oShell.CreateShortcut(sDesktopPath & "\Test.lnk") " Setting up a shortcut oLink.TargetPath = WScript.ScriptFullName oLink.WindowStyle = 1 oLink .Hotkey = "CTRL+SHIFT+T" oLink.IconLocation = "notepad.exe,0" oLink.Description = "Test link" oLink.WorkingDirectory = sDesktopPath oLink.Save " Creating an environment object and getting system properties into it Set oSysEnv = oShell.Environment("SYSTEM") " Display a message about the number of processors on the screen MyResult = oShell.Popup("Number of processors: " & oSysEnv("NUMBER_OF_PROCESSORS"), _ 3, "Message", 0) " Get the folder path Windows and displaying a message on the screen MyResult = oShell.Popup("Windows directory: " & _ oShell.ExpandEnvironmentStrings("%WINDIR%"), 3, "Message", 0) " Reading a registry key and displaying its value on the WScript screen. Echo oShell.RegRead("HKLM\Software\Microsoft\Windows\CurrentVersion\ProductID") " Write a string value to the registry MyResult = oShell.RegWrite("HKCU\ScriptEngine\Value", "My Value") " Write a numeric value to the registry MyResult = oShell.RegWrite("HKCU\ScriptEngine\Key", 1, "REG_DWORD") " Deleting a registry key MyResult = oShell.RegDelete("HKCU\ScriptEngine\") " Writing an event to the system log MyResult = oShell.LogEvent(0 , "Test Script Completed") As we have already seen, VBS scripts can work with the Windows shell, but this is not their only ability. Using the Network class, you can access and manage network objects. Let's take a closer look at the Network class: ComputerName " return the computer name; UserDomain " return the domain name; UserName " return the user name; EnumNetworkDrives " return a list of mapped network drives; MapNetworkDrive( Example. Using methods and properties of the Network class. " Creating an object of the Network Set class oNetwork = WScript.CreateObject("WScript.Network") " Displaying a message about the computer name WScript.Echo "Computer Name = " & oNetwork.ComputerName " Displaying a message about the name of the current user WScript.Echo "User Name = " & oNetwork.UserDomain & "\" & oNetwork.UserName " Mapping a network drive oNetwork.MapNetworkDrive "Z:" "\\Server\Share" " Getting a collection of mapped network drives Set oDrives = oNetwork.EnumNetworkDrives " Displaying messages about mapped network drives For i=0 To oDrives.Count -1 step 2 WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1) Next " Removing a network drive oNetwork.RemoveNetworkDrive "Z:" " Connecting a network printer oNetwork.AddPrinterConnection "LPT1", "\\Server\Printer" " Setting the default printer oNetwork.SetDefaultPrinter "\\Server\Printer" " Getting a collection of connected printers Set oPrinters = oNetwork.EnumPrinterConnections Very often in scenarios there are such cases when it is necessary to create, delete, move or change something on a computer disk. This problem can be solved by the FileSystemObject class, designed to work with the file system. The following are the objects that this class can create: Methods and properties of the FileSystemObject class (main object): BuildPath( The Drives, Folders and Files objects of the FileSystemObject class store information about drives, folders and files and are mainly used to collect information about the file system. They have only two properties: Count " returns the number of items in the collection; Item( To make it more clear what a collection of objects is, consider an example of displaying a list of files on the root of drive C: " Creating an object of the class FileSystemObject Set oFSO = CreateObject("Scripting.FileSystemObject") " Creating a Folder Set object oFolder = oFSO.GetFolder("C:\") " Getting a collection of files Set oFilesCollection = oFolder.Files " Getting the number of elements in the collection sResult = sResult & oFilesCollection.Count & " files in C:\" & vbCrLf " Read the attributes of each file from the collection For Each oFile in oFilesCollection sResult = sResult & oFile.Name & vbTab sResult = sResult & oFile.Size & vbCrLf Next " Output the result to screen MsgBox(sResult) The Drive object provides access to the properties of a local or network drive: AvailableSpace " returns the amount of free disk space available to the user; DriveLetter " returns the drive letter; DriveType " returns the drive type; FileSystem " returns the drive's file system type; FreeSpace " returns the amount of free disk space; IsReady " returns the availability of the disk; Path " returns the path to the disk; RootFolder " creates a Folder object pointing to the root of the disk; SerialNumber " returns the serial number of the disk; ShareName " returns the network name of the disk; TotalSize " returns the disk capacity in bytes; VolumeName " returns or sets the disk label. The Folder object provides access to all the properties of a folder and also allows you to perform actions on it: Attributes " returns the folder's attributes; DateCreated " returns the folder's creation date; DateLastAccessed " returns the date the folder was last accessed; DateLastModified " returns the date the folder was modified; Drive " returns the drive letter of the folder; Files " returns the collection of files in the folder; IsRootFolder " returns True if the folder is the root of the disk; Name " returns the name of the folder; ParentFolder " creates a Folder object pointing to " the parent folder; Path " returns the folder path; ShortName " returns the folder name in 8.3 format; ShortPath " returns the path to the folder in 8.3 format; Size " returns the size of the folder; SubFolders " returns a collection of subfolders; Type " returns the type of folder; Copy( The File object is similar to the Folder object - it provides access to all the properties of the file, and also allows you to perform actions on it: Attributes " returns the file's attributes; DateCreated " returns the file's creation date; DateLastAccessed " returns the date the file was last accessed; DateLastModified " returns the date the file was modified; Drive " returns the drive letter of the file; Name " returns the file name; ParentFolder " creates a Folder object pointing to " the parent folder; Path " returns the path to the file; ShortName " returns the file name in 8.3 format; ShortPath " returns the path to the file in 8.3 format; Size " returns the file size; Type " returns the file type; Copy( The TextStream object is a tool for accessing the contents of a file. You can use it to read and modify a file: AtEndOfLine " shows whether the end of the line has been reached; AtEndOfStream " shows whether the end of the line has been reached; Column " returns the number of the column in which the reading cursor is located; Line " returns the number of the line in which the reading cursor is located; Close " closes the file - frees it for other processes; Read( We got acquainted with all the methods and properties of the FileSystemObject class, let's look at an example of using this class: " Setting constant codes for system folders Const WindowsFolder = 0 Const SystemFolder = 1 Const TemporaryFolder = 2 " Setting constant codes for access types to a text file Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 " Creating an object of the class FileSystemObject Set oFSO = CreateObject(" Scripting.FileSystemObject") " Retrieving a collection of drives Set DrivesCollection = oFSO.Drives " Processing each drive to obtain its label or network name For Each oDrive in DrivesCollection sResult = sResult & oDrive.DriveLetter & ": " If oDrive.DriveType = Remote Then sResult = sResult & oDrive.ShareName & vbCrLf ElseIf oDrive.IsReady Then sResult = sResult & oDrive.VolumeName & vbCrLf Else sResult = sResult & vbCrLf End If Next " Displaying the results Wscript.Echo(sResult) " Creating a drive object C: Set oDrive = oFSO.GetDrive("C") sResult = oDrive.DriveLetter & ": - " " Getting drive type C: Select Case oDrive.DriveType Case 0: sResult = sResult & "Unknown - " Case 1: sResult = sResult & "Removable - " Case 2: sResult = sResult & "Fixed - " Case 3: sResult = sResult & "Network - " Case 4: sResult = sResult & "CD-ROM - " Case 5: sResult = sResult & "RAM Disk - " End Select " Determine whether a disk is available and get its properties If oDrive.IsReady Then sResult = sResult & "Ready" & vbCrLf sResult = sResult & "FileSystem is " & oDrive.FileSystem & vbCrLf sResult = sResult & "Available Space: " & _ FormatNumber( oDrive.AvailableSpace/1024, 0) & " Kbytes" Else sResult = sResult & "Not ready" End If " Displaying results on the screen Wscript.Echo(sResult) " Creating a service folder object (Windows temporary files folder) Set oTempFolder = oFSO. GetSpecialFolder(TemporaryFolder) " Create a text file object (and create it in the root of the C: drive) Set oFile = oFSO.CreateTextFile("C:\TestFile.txt", True) " Write to a text file oFile.WriteLine("This is a test.") oFile.WriteLine(sResult) " Closes a text file and frees it for other processes oFile.Close " Checks for the presence of a file in the Windows temporary files folder, deletes the file If oFSO.FileExists(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) Then _ oFSO.DeleteFile(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) " Create a file object Set oFile = oFSO.GetFile("C:\TestFile.txt") " Move file to the Windows temporary files folder oFile.Move(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) " Changing the attribute of the file If oFile.Attributes and 32 Then oFile. Attributes = oFile.attributes - 32 Wscript.Echo("Archive bit is cleared") Else oFile.Attributes = oFile.attributes + 32 Wscript.Echo("Archive bit is set") End If sResult = oFile.Path & vbCrLf & oFile .DateLastModified & ":" & vbCrLf " Create a stream object by opening a file for reading Set oTestFile = oFSO.OpenTextFile(oFile.Path, ForReading, False) " Read a stream until its end is encountered Do While oTestFile.AtEndOfStream<>True sResult = sResult & oTestFile.ReadLine Loop " Closes a text file and frees it for other processes oTestFile.Close " Prints a message to the screen Wscript.Echo(sResult) This script is designed to clean the system of outdated files in Windows temporary directories and user profiles. In this example, you can see how almost all of the above constructs work: script structure, naming variables, working with arrays and collections, manual error handling, reading system variables, creating a text file to log the script, working with the file system, using procedures. " ==== Script Information Header ==== " script name: Purge Temp " version: 1.0 " date: 07/16/08 " author: Bochkarev Vitaly " description: The script deletes outdated temporary files from the computer " ==== Script Main Logic ==== " Enable manual error handling On Error Resume Next " Time interval constant when files are considered stale Const PurgeTime = 14 " days " Exceptions - user profiles that should not be processed Dim aExceptions(3) aExceptions(0) = " Default User" aExceptions(1) = "LocalService" aExceptions(2) = "NetworkService" aExceptions(3) = "All Users" " Creating shell and file system objects Set oShell = CreateObject("wscript.shell") Set oFSO = CreateObject ("Scripting.Filesystemobject") " Defining service folder paths sProgramFiles = oShell.ExpandEnvironmentStrings("%ProgramFiles%") sWinDir = oShell.ExpandEnvironmentStrings("%WinDir%") sWinTempFolder = sWinDir & "\Temp" sDocuments = "C:\ Documents and Settings" " Creating a script log file sLogFileName = sWinTempFolder & "\PurgeTemp_" & Date sLogFileName = Replace(sLogFileName, ".", "_") sLogFileName = Replace(sLogFileName, "/", "_") Set oLogFile = oFSO.CreateTextFile(sLogFileName & ".log",true) oLogFile.WriteLine "========== Start purging ==========" " Cleaning up the Windows temporary folder oLogFile.WriteLine vbCrLf & "========== Windows Temporary folder ==========" PurgeFolder(sWinTempFolder) " Cleaning the temporary folder of the user profile and Internet files oLogFile.WriteLine vbCrLf & _ "===== ===== Users Temporary folder and Users Temporary Internet Files ==========" Set oDocuments = oFSO.GetFolder(sDocuments) Set colProfiles = oDocuments.SubFolders For Each oProfile In colProfiles bFlag = false For Each sException in aExceptions if InStr(oProfile.Path,sException) > 0 then bFlag = true exit for end if Next If bFlag = False Then PurgeFolder(oProfile.Path & "\Local Settings\Temp") PurgeFolder(oProfile.Path & "\Local Settings\Temporary Internet Files") End If Next " Clearing NOD32 Quarantine oLogFile.WriteLine vbCrLf & "========== NOD32 Quarantine ==========" sQuarantine = sProgramFiles & "\Eset \Infected" PurgeFolder(sQuarantine) " Closing the log file oLogFile.WriteLine vbCrLf & "========== Stop purge ==========" oLogFile.Close " PurgeFolder procedure - deleting old files Sub PurgeFolder(sFolderPath) " Creating a Folder Set object oFolder = oFSO.GetFolder(sFolderPath) " Retrieving a collection of files Set colFiles = oFolder. Files " Process each file in the collection For each oFile in colFiles " Check if the file is out of date If (Date-oFile.DateLastModified) > PurgeTime and (Date-oFile.DateCreated) > _ PurgeTime Then " Write a message to the script log oLogFile.Writeline oFile.Path & vbTab & oFile.DateCreated " Deleting an obsolete file oFSO.DeleteFile oFile.Path, True " Checking for errors if err.Number<>0 then " Write an error message to the script log oLogFile.Writeline "-----> Error # " & CStr(Err.Number) _ & " " & Err.Description " Clear the error Err.Clear end if " Pause 20 milliseconds WScript.Sleep 20 End if Next " Receiving a collection of subfolders Set colSubFolders = oFolder.SubFolders " Processing each subfolder For Each oSubFolder In colSubFolders " Recursively calling the procedure for deleting old files - the subroutine calls " itself PurgeFolder(oSubFolder.Path) " Checking the folder size If oSubFolder.Size = 0 Then " Write a message to the script log oLogFile.Writeline oSubFolder.Path & vbTab & oSubFolder.DateCreated " Delete an empty folder oFSO.DeleteFolder oSubFolder.Path " Check for errors If err.Number<>0 then " Write an error message to the script log oLogFile.Writeline "-----> Error # " & CStr(Err.Number) _ & " " & Err.Description " Clear the error Err.Clear End if End if Next End Sub So far we've learned the basics of Visual Basic Script. Let's summarize and determine the advantages and disadvantages of such scenarios: Vitaly Bochkarev Section of external links, that is, links to other sites to which this resource has no relation. In addition, the site owner does not bear any responsibility for the availability of these resources and their content. Somehow I completely ran ahead and didn’t tell you about two Dialog box functions: MsgBox and InputBox. In this very short lesson I will tell you about all the gadgets for these two functions. There are also other ways to create dialog boxes, but this will require WSH objects, which will be discussed in the following lessons. The most common function for displaying a message. Of course it's more complicated than Echo a WScript object, but she doesn’t need the object either. Parameter Buttons can simultaneously take on several values. In order to indicate them, use the “+” sign or simply use the sum of the values. The values for this parameter are given below. It is worth noting that the parameter Buttons cannot accept multiple values from the same category. These values will simply add up. That is, you will not be able to install several sets of buttons or icons at the same time. "VBScript Lesson No. 16: "Function MsgBox and InputBox "file_1.vbs"********************************** ********************** MsgBox "Hello", 5+16, "Title" MsgBox "Hello", vbRetryCancel+16, "Title" MsgBox "Hello" , vbRetryCancel+524288, "Title" MsgBox "Hello", vbAbortRetryIgnore + vbInformation + vbDefaultButton2 + vbSystemModal + 524288, "Title" MsgBox "Hello", 528706, "Title" "********************************************************
"VBScript Lesson #16: "MsgBox and InputBox function "file_1.vbs "********************************************************
MsgBox "Hello" , 5 + 16 , "Title" MsgBox "Hello" , vbRetryCancel + 16 , "Title" MsgBox "Hello" , vbRetryCancel + 524288 , "Title" MsgBox "Hello" , vbAbortRetryIgnore + vbInformation + vbDefaultButton2 + vbSystemModal + 524288 , "Title" MsgBox "Hello" , 528706 , "Title" In addition, the MsgBox function can return the result of button clicks. It can be assigned to a variable and in this way determine the pressed button. "************************************************* ******* "VBScript Lesson No. 16: "MsgBox and InputBox Function "file_2.vbs"************************************* ***************************** Dim Knopka Knopka = MsgBox("Press any button",2,"Title") If Knopka = 3 Then MsgBox "You pressed the button - Abort" ElseIf Button = 4 Then MsgBox "You pressed the button - Repeat" Else MsgBox "You pressed the button - Skip" End If "************************************************* ******* "VBScript Lesson No. 16: "MsgBox and InputBox Function "file_4.vbs"************************************* ***************************** Dim Dict, AboutBomb Set Dict = CreateObject("Scripting.Dictionary") Dict.CompareMode = 1 Dict .Add "Yellow", "The bomb has exploded!" Dict.Add "Red", "You have defused the bomb!" Dict.Add "Blue", "The bomb has exploded!" Dict.Add "Green", "The bomb has exploded!" AboutBomb = InputBox("Bomb detected!!! Which wire should you cut: yellow, red, blue or green??","Bomb detected!!!","Enter wire color here...") If Dict.Exists(AboutBomb) then MsgBox Dict.Item(AboutBomb) else MsgBox "Your eyesight is bad! There is no such wire! The bomb exploded!!!" end if "********************************************************
Methods and Properties of the WScript Root Class
Methods and properties of the Shell class
Methods and properties of the Network class
Methods and properties of the FileSystemObject class
Scenario "Deleting old files"
External links
MsgBox function
Syntax: MsgBox (Prompt[, Buttons][, Title][, Helpfile, Context])Constants for dialog boxes (display buttons):
Constants for dialog boxes (displayed icons):
Constants for dialog boxes (default buttons):
Constants for dialog boxes (Window Mode):
Other:
Return result of pressed buttons (constants):