Download presentation
Presentation is loading. Please wait.
Published byEthan Knight Modified over 8 years ago
1
BASIC OF VB SCRIPT Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh
2
CONTENTS OF VB SCRIPT INTRODUCTION DATA TYPE VARIABLE OPERATORS CONTROL STRUCTURE BUILT IN FUNCTION ADVANTAGES OF VB SCRIPT DISADVANTAGES OF VB SCRIPT
3
INTRODUCTION Visual Basic Script recently introduced by Microsoft represents a step further towards active web pages. It is a subset of the Visual Basic programming language that is fully compatible with Visual Basic and Visual Basic for Applications. VBScript was created to allow web page developers the ability to create dynamic web pages for their viewers who used Internet Explorer. With HTML, not a lot can be done to make a web page interactive, but VBScript unlocked many tools like: the ability to print the current date and time, access to the web servers file system, and allow advanced web programmers to develop web applications. To use Visual Basic Script within a HTML document, the code needs to be wrapped in...
4
vbscript script creation This first script will be very basic and will write "Hello World" to the browser window, just as if you had typed it in HTML. This may not seem very important, but it will give you a chance to see the VBScript Syntax without getting to complex.
5
VBScript Code: document.write("Hello World") VBScript only runs on Internet Explorer browsers. Output: Hello World
6
vbscript tag In the above example you saw the basic cookie cutter for inserting a script into a web page. The HTML script tag lets the browser know we are going to use a script and the attribute type specifies which scripting language we are using. VBScript's type is "text/vbscript". All the VBScript code that you write must be contained within script tags, otherwise they will not function properly.
7
vbscript syntax If you are an expert Visual Basic programmer then you will be pleasantly surprised to know that VBScript has nearly identical syntax to Visual Basic. However, if you are a programmer or only know the basics of HTML then VBScript code may look a little strange to you. This lesson will point out the most important things about VBScript syntax so you can avoid common potholes.
8
vbscript: no semicolons! If you have programmed before, you will be quite accustomed to placing a semicolon at the end of every statement. In VB this is unnecessary because a newline symbolizes the end of the statement. This example will print out 3 separate phrases to the browser. Note: There are 0 semicolons!
9
VBScript Code: document.write("No semicolons") document.write(" were injured in the making") document.write(" of this tutorial!") Output: No semicolons were injured in the making of this tutorial!
10
vbscript multiple line syntax The syntax is that placing a newline in your VBScript signifies the end of a statement, much like a semicolon would. However, what happens if your code is so long that absolutely must place your code on multiple lines? Well, Microsoft has included a special character for these multiple lines of code: the underscore "_". The following example contains an exceptionally longwrite statement that we will break up string concatenation and the multiple line special character.
11
VBScript Code: document.write("This is a very long write " &_ "statement that will need to be placed onto three " &_ "lines to be readable!") Output: This is a very long write statement that will need to be placed onto three lines to be readable!
12
vbscript syntax review VBScript is a client-side scripting language that is based off of Microsoft's Visual Basic programming language. No semicolons are used at the end of statements, only newlines are used to end a statement. If you want to access methods of an object then use a period "." and an underscore is used for statements that go multiple lines!
13
Data type of vbscript VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it's used. Because Variant is the only data type in VBScript, it's also the data type returned by all functions in VBScript.At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you're working with data that looks like numbers, VBScript assumes that it is numbers and does the thing that is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. Of course, you can always make numbers behave as strings by enclosing them in quotation marks (" ").
14
Variant Subtypes Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, you can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. Of course, you can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains
15
The following table shows the subtypes of data that a Variant can contain. SubtypeDescription EmptyVariant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables. NullVariant intentionally contains no valid data. BooleanContains either True or False.TrueFalse ByteContains integer in the range 0 to 255. IntegerContains integer in the range -32,768 to 32,767. Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807. LongContains integer in the range -2,147,483,648 to 2,147,483,647. SingleContains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. DoubleContains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Date (Time)Contains a number that represents a date between January 1, 100 to December 31, 9999. StringContains a variable-length string that can be up to approximately 2 billion characters in length. ObjectContains an object. ErrorContains an error number.
16
VARIABLE of vbscript A variable is a named location in computer memory that you can use for storage of data during the execution of your scripts. You can use variables to: Store input from the user gathered via your web page Save data returned from functions Hold results from calculations
17
Declaring Variables Creating variables in VBScript is most often referred to as "declaring" variables. You can declare VBScript variables with the Dim, Public or the Private statement. Like this: Dim x You declare multiple variables by separating each variable name with a comma. For example: Dim Top, Bottom, Left, Right You can also declare a variable implicitly by simply using its name in your script. That is not generally a good practice because you could misspell the variable name in one or more places, causing unexpected results when your script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in your script.Option Explicit
18
As mentioned, it's good practice to declare all variables before using them. Occasionally, if you're in a hurry, you might forget to do this. Then, one day, you might misspell the variable name and all sorts of problems could start occurring with your script. VBScript has a way of ensuring you declare all your variables. This is done with the Option Explicit statement: Option Explicit Dim firstName Dim age
19
Naming Restrictions Variable names follow the standard rules for naming anything in VBScript. A variable name: Must begin with an alphabetic character. Cannot contain an embedded period. Must not exceed 255 characters. Must be unique in the scope in which it is declared.
20
Assigning Values to Variables Values are assigned to variables creating an expression as follows: the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: B = 200 You represent date literals and time literals by enclosing them in number signs (#), as shown in the following example. CutoffDate = #06/18/2008# CutoffTime = #3:36:00 PM#
21
Example of Assign Values to your Variables Option Explicit Dim firstName Dim age firstName = "Borat“ age = 25
22
Display your Variables Option Explicit Dim firstName Dim age firstName = "Borat" age = 25 document.write("Firstname: " & firstName & " ") document.write("Age: " & age) Output: Firstname: Borat Age: 25
23
Lifetime of Variables When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different procedures, because each is recognized only by the procedure in which it is declared. If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
24
VBScript Array Variables An array variable is used to store multiple values in a single variable. In the following example, an array containing 3 elements is declared: Dim names(2) The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a fixed-size array. You assign data to each of the elements of the array like this: names(0)="Tove" names(1)="Jani" names(2)="Stale“ Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this: mother=names(0) You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns: Dim table(4,6)
25
Asign data to a two-dimensional array: Dim x(2,2) x(0,0)="Volvo" x(0,1)="BMW" x(0,2)="Ford" x(1,0)="Apple" x(1,1)="Orange" x(1,2)="Banana" x(2,0)="Coke" x(2,1)="Pepsi" x(2,2)="Sprite" for i=0 to 2 document.write(" ") for j=0 to 2 document.write(x(i,j) & " ") next document.write(" ") next
26
output
27
OPERATORS of vbscript Operators are used to "do operations" or manipulate variables and values. For example, addition is an example of a mathematical operator and concatenation is an example of a string operator. The plus sign "+" is the operator used in programming language to represent this mathematical addition operation.
28
VBScript's many operators can be separated into four semi-distinct categories: Math Operators Comparison Operators Logic Operators String Concatenation Operator
29
Math Operators When you want to perform addition, subtraction, multiplication, and other mathematical operations on numbers and variables use the operators listed below. OperatorEnglishExampleResult +Add8+715 -Subtract11-101 *Multiply7*856 /Divide8/24 ^Exponent2^416 ModModulus15 Mod 105
30
vbscript operators: comparison When you want to compare two numbers to see which is bigger, if they're equal, or some other type of relationship use the comparison operators listed below. Common uses of comparison operators are within conditional statements like an If Statement or the condition check in a While Loop. OperatorEnglishExampleResult =Equal To10 =1 4False >Greater Than10 > 14False <Less Than10 < 14True >= Greater Than Or Equal To 10 >= 14False <=Less Than Or Equal To10 <= 14True <>Not Equal To10 <> 145
31
vbscript operators: logic Logic operators are used to manipulate and create logical statements. For example if you wanted a variable shoeSize to be equal to 10 or 11 then you would do something like: VBScript Code: Dim shoeSize shoeSize = 10 If shoeSize = 10 Or shoeSize = 12 Then 'Some code EndIf
32
vbscript operators: logic A detailed explanation of Logic and Logic Operators are beyond the scope of this tutorial, but we do have a list of the various logic operators available to you in VBScript. OperatorEnglishExampleResult NotInverts Truth ValueNot FalseTrue OrEither Can Be TrueTrue Or FalseTrue AndBoth Must Be TrueTrue And FalseFalse
33
vbscript string concatenation operator When you have various strings that you would like to combine into one string use the concatenation operator. The concatenation operator acts as a glue between the two or more strings you wish to attach, effectively making them into one string. String concatenation is often used when using the document.writefunction. OperatorEnglishExampleResult &Connected To "Hello" & " there" "Hello there
34
Conditional statements Conditional Statements:Conditional statements are used to perform different actions for different decisions. In VBScript we have four conditional statements: If statement - executes a set of code when a condition is true If...Then...Else statement - select one of two sets of lines to execute If...Then...ElseIf statement - select one of many sets of lines to execute Select Case statement - select one of many sets of lines to execute
35
If Statement if Age = 100 Then MsgBox "Congratulations!“ An If statement first checks to see if the specified condition evaluates toTrue or False. If it evaluates to True, then it evaluates a set of statements. In the example above, the "Congratulations!" message box is only displayed ifAge = 100, i.e. if Age is equal to 100.
36
If...Then...Else statement If the condition in an if statement is true, then the code following the condition will be executed. But what if you wanted something to happen if it is false? What if you wanted one thing to happen if the condition is true, and something else to happen if the condition is false? This is where the else statement comes in. The else statement works together with the if statement and executes certain code if the condition in the if statement is false.
37
Example If Age = 100 Then MsgBox "Congratulations!“ Else MsgBox "You're still a young chicken!" End If Now we introduce the Else construct. If the condition evaluates to True, the first set of statements are executed. Otherwise, the set of statements after the Else statement are executed.
38
If...Then...ElseIf statement The if statement tests a single condition and performs an action if that condition is true and the else statement performs an action if the condition in the if statement is false, but what if there are more than two possibilities? Surely, any condition can be only true or false, but what if you needed to test a variable for more than one value? This is where the elseif statement comes in. The elseif statement is used in conjunction with the if statement. Unlike the else statement, it does not specifically perform a certain action if the condition in the if statement is false, but rather it performs an action if the condition in the if statement is another specific value specified in the elseif statement itself.
39
Example Dim X X = 7 if X = 5 then document.write("X is equal to 5") elseif X = 7 then document.write("X is equal to 7") end if Output: X is equal to 7
40
Select Case statement The Select statement is specifically designed for comparing one variable to a number of possible values. It can be thought of as a substitute for the if, elseif, else structure. elect Case is useful when there are many conditions to be checked. Syntax Select Case expression Case value1 Case value2... Case Else End Select With Select Case, expression is checked for equality against each ofvalue1, value2,... until a match is found. If no values match, then the Case Else statement is executed.
41
Example Dim X X = 7 select case X case 1 document.write("X is equal to 1") case 2 document.write("X is equal to 2") case 3 document.write("X is equal to 3") case 7 document.write("X is equal to 7") case else document.write("X is not equal to any of the values specified") end select Output: X is equal to 7
42
Looping or controlling Statements Looping statements are used to run the same block of code a specified number of times.In VBScript we have four looping statements: For...Next statement - runs code a specified number of times For Each...Next statement - runs code for each item in a collection or each element of an array The do while loop - loops while or until a condition is true While...Wend statement - Do not use it - use the Do...Loop statement instead
43
For...Next statement Use the For...Next statement to run a block of code a specified number of times. The For statement specifies the counter variable (i), and its start and end values. The Nextstatement increases the counter variable (i) by one.
44
Example For i = 0 To 5 document.write("The number is " & i & " ") Next
45
output The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
46
For Each...Next Loop A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.example: Dim cars(2) cars(0)="Volvo" cars(1)="Saab" cars(2)="BMW" For Each x In cars document.write(x & " ") Next Output: Volvo Saab BMW
47
The do while loop The Do … Loop statement is very useful (like, for … next and Select … case) to execute a block of code more than once. However, where it differs from the other two is that the Do … Loop statement executes the code as long as (while) a condition is true or until a condition becomes true. Typical uses of a Do … Loop are in cases where you may not know how many times you need to execute the code section because it could vary from situation to situation, like when reading in a file or taking in keyboard input.
48
Example: Dim num num = 0 do while num < 30 num = num + 5 document.write(num & " ") loop Output: 5 10 15 20 25 30 In the above example, a variable named num is given the value 0. The condition in the while loop is that while num is less than 30, 5 should be added to num. Once the value of num is greater than 30, the loop will stop executing. The loop prints the current value of numfollowed by a line break through each iteration.
49
BUILT IN FUNCTION There are many type of built in function in vbscript. Date/Time Functions Conversion Functions Format Functions Math Functions Array Functions String Functions Other Functions
50
Date/Time Functions FunctionDescription CDateConverts a valid date and time expression to the variant of subtype Date DateReturns the current system date DateAddReturns a date to which a specified time interval has been added DateDiffReturns the number of intervals between two dates DatePartReturns the specified part of a given date DateSerialReturns the date for a specified year, month, and day DateValueReturns a date DayReturns a number that represents the day of the month (between 1 and 31, inclusive) FormatDateTimeReturns an expression formatted as a date or time HourReturns a number that represents the hour of the day (between 0 and 23, inclusive) IsDateReturns a Boolean value that indicates if the evaluated expression can be converted to a date MinuteReturns a number that represents the minute of the hour (between 0 and 59, inclusive) MonthReturns a number that represents the month of the year (between 1 and 12, inclusive)
51
Date/Time Functions MonthNameReturns the name of a specified month NowReturns the current system date and time SecondReturns a number that represents the second of the minute (between 0 and 59, inclusive) TimeReturns the current system time TimerReturns the number of seconds since 12:00 AM TimeSerialReturns the time for a specific hour, minute, and second TimeValueReturns a time WeekdayReturns a number that represents the day of the week (between 1 and 7, inclusive) WeekdayNameReturns the weekday name of a specified day of the week YearReturns a number that represents the year
52
Conversion Functions FunctionDescription AscConverts the first letter in a string to ANSI code CBoolConverts an expression to a variant of subtype Boolean CByteConverts an expression to a variant of subtype Byte CCurConverts an expression to a variant of subtype Currency CDateConverts a valid date and time expression to the variant of subtype Date CDblConverts an expression to a variant of subtype Double ChrConverts the specified ANSI code to a character CIntConverts an expression to a variant of subtype Integer CLngConverts an expression to a variant of subtype Long CSngConverts an expression to a variant of subtype Single CStrConverts an expression to a variant of subtype String HexReturns the hexadecimal value of a specified number OctReturns the octal value of a specified number
53
Format Functions FunctionDescription FormatCurrencyReturns an expression formatted as a currency value FormatDateTimeReturns an expression formatted as a date or time FormatNumberReturns an expression formatted as a number FormatPercentReturns an expression formatted as a percentage
54
Math Functions FunctionDescription AbsReturns the absolute value of a specified number AtnReturns the arctangent of a specified number CosReturns the cosine of a specified number (angle) ExpReturns e raised to a power HexReturns the hexadecimal value of a specified number IntReturns the integer part of a specified number FixReturns the integer part of a specified number LogReturns the natural logarithm of a specified number OctReturns the octal value of a specified number RndReturns a random number less than 1 but greater or equal to 0 SgnReturns an integer that indicates the sign of a specified number SinReturns the sine of a specified number (angle) SqrReturns the square root of a specified number TanReturns the tangent of a specified number (angle)
55
Array Functions FunctionDescription ArrayReturns a variant containing an array FilterReturns a zero-based array that contains a subset of a string array based on a filter criteria IsArrayReturns a Boolean value that indicates whether a specified variable is an array JoinReturns a string that consists of a number of substrings in an array LBoundReturns the smallest subscript for the indicated dimension of an array SplitReturns a zero-based, one-dimensional array that contains a specified number of substrings UBoundReturns the largest subscript for the indicated dimension of an array
56
String Functions FunctionDescription InStrReturns the position of the first occurrence of one string within another. The search begins at the first character of the string InStrRevReturns the position of the first occurrence of one string within another. The search begins at the last character of the string LCaseConverts a specified string to lowercase LeftReturns a specified number of characters from the left side of a string LenReturns the number of characters in a string LTrimRemoves spaces on the left side of a string RTrimRemoves spaces on the right side of a string TrimRemoves spaces on both the left and the right side of a string MidReturns a specified number of characters from a string ReplaceReplaces a specified part of a string with another string a specified number of times RightReturns a specified number of characters from the right side of a string SpaceReturns a string that consists of a specified number of spaces StrCompCompares two strings and returns a value that represents the result of the comparison StringReturns a string that contains a repeating character of a specified length StrReverseReverses a string UCaseConverts a specified string to uppercase
57
Other Functions FunctionDescription CreateObjectCreates an object of a specified type EvalEvaluates an expression and returns the result GetLocaleReturns the current locale ID LoadPictureReturns a picture object. Available only on 32-bit platforms MsgBoxDisplays a message box, waits for the user to click a button, and returns a value that indicates which button the user clicked InputBoxDisplays a dialog box, where the user can write some input and/or click on a button, and returns the contents IsEmptyReturns a Boolean value that indicates whether a specified variable has been initialized or not IsNullReturns a Boolean value that indicates whether a specified expression contains no valid data (Null) RGBReturns a number that represents an RGB color value RoundRounds a number
58
ADVANTAGES OF VB SCRIPT You always have up-to-date pages with a correctly hyperlinked menu. The menu does not use Javascript and frames. You pages can be easily copied or transferred into any other folder or computer - and links do not become broken, because they are relative. Since each menu element has its own CSS class, it can have any look you wish. You receive pages which are already HTML- and CSS- validated. Only your own content must be validated additionally. Since the program script is simple enough, you can add features and optimize it.
59
DISADVANTAGES OF VB SCRIPT Some of the syntax is very different from C++ and will probably frustrate experienced programmers. – “=” is used for both assignment and comparison – the “()” characters are used less often then in C++ – "NOT" does both boolean and bitwise NOT (so NOT true is false, but NOT -1 is -2!) VBScript is not as widely used in web technology as JScript/Javascript, because it is only supported on Windows. XSI is able to support VBScript on the Linux platform, but few developers from a purely linux/unix background are familiar with VBScript. As a basic (sic) language the error handling is primitive (“on error resume next”, “option explicit”)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.