This is the fourth tutorial in the VBScript Tutorials for Beginners. This VBScript beginner tutorial explains VBScript conditional statement, the Select Case statement. Please view the short VBScript tutorial 4 or read on... The VBScript Select Case statement evaluates an expression. The Select Case statement is followed by Case code blocks. Depending on the value of the expression, exactly one case block is run. If the expression value is not given in any Case above, the Case Else code block is run. The example of a VBScript Select Case statement is as follows:
' VBScript code
Option Explicit' VBScript code
Call Main
Sub Main
Dim stringA, stringB
'the first string would be the first argument of the VBScript run from command line
stringA = Wscript.Arguments.Item(0)
' the second string would be the second argument of the VBScript
stringB = Wscript.Arguments.Item(1)
' compare strings in VBScript
Select Case StrComp(stringA, stringB)
'StrComp function returns 0 is both the strings are equal
Case 0
'MsgBox has three arguments (the message, the icon and the title)
MsgBox "Both the strings are the same.", vbInformation, "Success"
'StrComp function returns 1 if the first string is greater
Case 1
MsgBox stringA &" is greater than " & stringB, vbQuestion, "Warning"
'StrComp function returns -1 if the first string is smaller
Case -1
MsgBox stringA & " is less than " & stringB, vbQuestion, "Warning"
Case Else
MsgBox "There is an error in string comparison.", vbCritical, "Error"
End Select
End Sub
Since this script needs two arguments to run, we cannot just double-click this VBscript. That would give a subscript out of range error. Instead, we can open the command window (cmd command). Then, change directory (cd command) to the folder that has our script. Give the commands as the script name followed by arguments like the examples below:
- StringCompare.vbs xyz xyz
- StringCompare.vbs abc a
- StringCompare.vbs d def
Want to understand the VBScript Select Case statement and string comparison in VBScript better? Please view my VBScript tutorial 4. Thank you.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.