当前位置:文档之家› VBScript脚本语言讲义

VBScript脚本语言讲义

VBScript脚本语言讲义
VBScript脚本语言讲义

. TypeName及VarType函数介绍,示例程序如下:

可用VarType 函数来返回某个数据的Variant 子类型,如下面的代码:

Dim strInput,strVarType,strTypeName

strInput="hello world"

MsgBox strInput

strVarType=VarType(strInput)

MsgBox "VarType:"&strVarType

strTypeName=TypeName(strInput)

MsgBox "TypeName:"&strTypeName

问题:如下三段语句,结果分别是什么?

Dim VarTypeCheck

VarTypeCheck = VarType(300)

MsgBox VarTypeCheck

VarTypeCheck = VarType(#10/19/62#)

MsgBox VarTypeCheck

VarTypeCheck = TypeName("VBScript")

MsgBox VarTypeCheck

. Option Explicit 声明,如果变量没有定义就使用要报错:

Option Explicit

Dim MyDate

MyDate = "October 19, 1962"

If IsDate(MyDate) then

MyShortDate = CDate(MyDate)

End if

MsgBox MyShortDate

变量的作用域与存活期:

Dim strMain

Call ChangeValue

Sub ChangeValue()

Dim strSub

strMain="hello world!"

MsgBox "strMain InSub:"&strMain

strSub="hello liuxiaolin"

MsgBox "strSub InSub:"&strSub

End Sub

MsgBox "strMain in Main:"&strMain

MsgBox "strSub in Main:"&strSub

数组的定义:

Dim 数组名(n)实际上数据会有n+1个元素,下标从0到n

Dim MyArray(10),i

For i=0 To 10

MyArray(i)=i

MsgBox MyArray(i)

Next

MsgBox "min is "&LBound(MyArray) '返回数组的最小可用下标

MsgBox "max is "&UBound(MyArray) '返回数组的最大可用上标

利用Redim重新定义数据的大小,加上preserve关键字保存原来数组的内容:

Dim MyFamily()

ReDim MyFamily(1)

MyFamily(0)="0"

MyFamily(1)="1"

ReDim MyFamily(2)

.

'ReDim Preserve MyFamily(2)

MyFamily(2)="2"

Dim i

For i=0 To 2

MsgBox MyFamily(i)

Next

在字符串中回车换行的方法:chr(13)&chr(10) / vbCr&vbLf / vbCrLf / vbNewLine

Dim str,str1,str2,str3,str4

str="how are you fine,thank you!"

str1="how are you"&chr(13)&chr(10)&"fine,thank you!"

str2="how are you"&vbCr&vbLf&"fine,thank you!"

str3="how are you"&vbCrLf&"fine,thank you!"

str4="how are you"&vbNewLine&"fine,thank you!"

MsgBox str

MsgBox "str1:"&str1

MsgBox "str2:"&str2

MsgBox "str3:"&str3

MsgBox "str4:"&str4

Chr用法:

Dim str

str=chr(34) & "Hello" & chr(34)

MsgBox str

.

Const常量

Const a=1

a=2

IF…THEN…ELSEIF…ELSE…END IF语句:

Dim House,Car

House=Null

Car=null

If IsNull(House) Or IsNull(Car) Then

MsgBox "现在我们还不成熟,还是再等等吧!"

Else

MsgBox "OK,我嫁给你!"

End If

课堂练习:找出3个整数中的最大数并输出,三个整数存在三个变量intA,intB,intC中

.

Dim intA,intB,intC,max

intA=8

intB=5

intC=3

If intA>=ntB Then

max=intA

else

max= intB

End If

If max>=intC Then

MsgBox max

Else

MsgBox intC

End If

Dim intA,intB,intC,temp

intA=CInt(InputBox("请输入整数A:"))

intB=CInt(InputBox("请输入整数B:"))

intC=CInt(InputBox("请输入整数C:"))

If intA>=intB Then

temp =intA

else

temp =intB

End If

If temp >=intC Then

MsgBox temp

Else

MsgBox intC

End If

Select…case…case else…End Select语句:

Dim str

str=InputBox("请输入你要说的话!")

Select Case str

Case "hello"

MsgBox "hello"

Case "how are you"

MsgBox "fine,thank you "

Case Else

MsgBox "thanks"

End Select

.

Case后接的表达式可以是任意字符,如:case 1,也可以是多个表达式,如:case 5,6,7,但是vbs中不支持给出case后的范围的格式

课堂练习:输入一个字符,判断字符类型:大写、小写、数字、其他。给出相应的提示信息。

Option Explicit

Dim strValue

strValue = InputBox ("请输入一个字符:")

strValue = CInt(Asc(strValue))

MsgBox strValue

If strValue>=65 And strValue<=90 Then

strValue=1

ElseIf strValue>=97 And strValue<=122 Then

strValue=2

ElseIf strValue>=48 And strValue<=57 Then

strValue=3

End if

Select Case strValue

Case 1

MsgBox "您输入的是大写字母!"

Case 2

MsgBox "您输入的是小写字母!"

Case 3

MsgBox "您输入的是数字!"

Case Else

MsgBox "您输入的是特殊字符"

End Select

Do…Loop循环语句的使用:

推荐使用while循环

'即使不符合条件也会做一次

.

Dim intAge

intAge=0

Do

intAge=intAge+1

MsgBox CStr(intAge)

Loop While intAge<=5

'不符合条件时,则一次也不做

intAge=0

Do While intAge<=5

intAge=intAge+1

MsgBox CStr(intAge)

Loop

'达到条件时就不再进入循环了。而while语句在达到条件时也要再进入循环一次

Dim intAge

intAge=0

Do Until intAge=5

intAge=intAge+1

MsgBox intAge

Loop

intAge=0

Do

intAge=intAge+1

MsgBox intAge

Loop Until intAge=5

'Do循环支持Exit Do语句

Dim intAge

intAge=0

Do Until intAge=5

intAge=intAge+1

MsgBox intAge

If intAge=3 Then

Exit Do

End If

Loop

While…Wend循环语句的使用:

不建议使用,因为没有退出循环的语句

Dim intAge

intAge=0

.

While intAge<5

intAge=intAge+1

MsgBox intAge

Wend

For…Next循环语句的使用:

Dim i

For i=1 To 5

MsgBox i

Next

For i=1 To 5 Step 2

MsgBox i

Next

For i=5 To 1 Step -1

MsgBox i

Next

练习:接收用户输入的5个数字,然后倒序输出出来

Dim intMyArray(4),i

For i=0 To 4

intMyArray(i)=InputBox("请输入第"&CStr(i)&"个数字")

Next

For i=4 To 0 Step -1

MsgBox "您输入的第"&CStr(i)&"个数字是:"&CStr(intMyArray(i))

Next

. For each…Next循环语句的使用:

如果生命还有三天,你准备怎么安排呢?

Dim countDownDay

countDownDay=Array("看日出","骑自行车","聊天")

For Each element In countDownDay

MsgBox element

Next

With…End With语句的使用:

SystemUtil.Run "E:\WINDOWS\system32\calc.exe"

With Window("计算器")

.WinButton("1").Click

.WinButton("+").Click

.WinButton("2").Click

.WinButton("=").Click

.Close

End with

Sub与Function的用法:

Dim strCall

strCall=InputBox("请输入你想说的话:")

'Shout strCall

Call Shout(strCall)

Sub Shout(ByVal strEcho)

MsgBox strEcho&"!"

End Sub

Dim str

str=InputBox("请输入你想说的话:")

MsgBox Answer(str)

Function Answer(ByVal strAsk)

Select Case strAsk

Case "我爱你"

Answer="我也爱你"

Case "我恨你"

Answer="冤冤相报何时了"

Case Else

Answer="下次再聊"

End Select

End Function

函数的返回值:

格式为:函数名=返回值

Function add(x,y)

add=x+y

MsgBox add

End Function

a=add (1,2)

MsgBox a

注意与c和tcl中return的区别

参数的值传递ByVal与地址传递ByRef:

ByVal 与 ByRef(默认值)

这两个是子过程的参数传递时,指定参数按什么传递的

ByVal(按值传递)

ByRef(按地址传递)

具体这样来理解:

过程中的参数列表,我们称形参

调用过程时的参数列表,我们称实参

在调用时,我们要将实参的值传递给形参,这样过程才能拿这些数据参与计算并实现一些功能

那么在传递的过程中,就存在这两种传递方式

传值时(ByVal),是先给形参开辟一个临时地址,将实参的内容传入这个临时地址,这样,传递后,形参与实参是在两上不同的地址中,也就是说他们是相互独立的

传址时(ByRef),是直接将实参的地址传递给形参,这样,形参与实参就共用一个地址,所以,形参内容的改变,也直接改变了实参的内容

通过上面的分析,你只要记得:

按值传递时(ByVal),形参的改变不会影响到实参

按址传递时(ByRef),形参的改变,会影响到实参

Dim str

str="hello world!"

Call strEcho(str)

MsgBox str

Sub strEcho(ByVal str)

str=str&"!!!!!"

End Sub

Dim str

str="hello world!"

Call strEcho(str)

MsgBox str

Sub strEcho(ByRef str)

str=str&"!!!!!"

End Sub

Dim msg

msg = "喂,你好吗?"

MsgBox msg

Answer msg

MsgBox msg

'Sub Answer(ByVal sentense)

' sentense = "我很好!你呢?"

'End Sub

Sub Answer(ByRef sentense)

sentense = "我很好!你呢?"

End Sub

过程的调用

在调用过程时,不必使用Call关键字。使用Call语法调用内部函数或使用用户自定义函数,函数返回值都会被放弃。

变量命名规则:

1、匈牙利命名法:

变量的前面加类型前缀,约定俗成字母写1个或者3个。

例如:iCount strUserName blnCall

2、骆驼命名法:

变量以词组来组成,并且单词的首字母大写,其余小写。

例如:strLoginName strPassword

3、帕斯卡命名法:

类似骆驼命名法,区别在于首单词的首字母必须大写,而骆驼命名法则小写。

例如:StrLoginName StrPassword

综上,希望大家写程序命名好。例如:iRowsCount iColumnsCount psz_filename

VBScript编码规范:

参考其他开发语言编码规范:结构性规范,SQL语句规范…(参见自动化测试编码规范)

VBScript的常用函数:

Len 函数:返回字符串中的字符数也就是字符串长度,或者是存储变量所需的字节数

Left 函数:返回指定数目的从字符串的左边算起的字符

Mid 函数:从字符串中返回指定数目的字符,字符串的第一个起始位置是1

Right 函数:从字符串右边返回指定数目的字符

InStr 函数:返回某字符串在另一字符串中第一次出现的位置

LTrim、RTrim 和Trim 函数:返回不带前导空格(LTrim)、后续空格(RTrim) 或前导与后续空格(Trim) 的字符串副本

LCase 函数:返回字符串的小写形式

UCase 函数:返回字符串的大写形式

Replace 函数:返回字符串,其中指定数目的某子字符串被替换为另一个子字符串

Split 函数:返回基于0 的一维数组,其中包含指定数目的子字符串

Chr 函数:返回与指定的ASCII 字符代码相对应的字符

Cstr函数:VB中的函数,取出字符串(用Cstr)

CInt或CLng函数:VB中的函数,返回字符串内的数字(用CInt或CLng)

CBool 函数:返回表达式,此表达式已转换为Boolean 子类型的Vari ant

CByte 函数:返回表达式,此表达式已被转换为Byte子类型的Variant

CDate 函数:返回表达式,此表达式已被转换为Date子类型的Variant

CDbl 函数:返回表达式,此表达式已被转换为Double子类型的Variant

CInt 函数:返回表达式,此表达式已被转换为Integer子类型的Variant

CLng 函数:返回表达式,此表达式已被转换为Long子类型的Variant

CSng 函数:返回表达式,该表达式已被转换为Single子类型的Variant

CStr 函数:返回表达式,该表达式已被转换为String子类型的Variant

IsArray 函数:返回Boolean 值指明某变量是否为数组

IsDate 函数:返回Boolean 值指明某表达式是否可以转换为日期

IsEmpty 函数:返回Boolean 值指明变量是否已初始化

IsNumeric 函数:返回Boolean 值指明表达式的值是否为数字

IsNull 函数:返回Boolean 值,指明表达式是否不包含任何有效数据(Null)

IsObject 函数:返回Boolean 值指明表达式是否引用了有效的Automation 对象VarType 函数:返回指示变量子类型的值

TypeName 函数:返回一个字符串,提供有关变量的Variant子类型信息

Rnd 函数和Randomize 语句:

先利用Randomize初始化随机数生成器,Randomize作用是使产生的随机数不重复,然后再调用Rnd函数返回随机数:

要产生指定范围的随机整数,请使用以下公式:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

这里,upperbound 是此范围的上界,而lowerbound 是此范围内的下界。

显示出1-6整数中的随机数:

MsgBox Int(6*Rnd+1)

练习:用户输入5个词语,并用逗号隔开,读入这5个词语后进行随机显示5次。

Dim strInput,strArray

strInput=InputBox("please input 5 words!")

strArray=Split(strInput,",")

'Randomize ‘注意这里有这句话和没有这句话的区别

Dim i,j

For i=0 To 4

j=Int(5*Rnd)

MsgBox strArray(j)

Next

Err对象:

Err 对象是一个具有全局范围的内部对象:不必在您的代码中创建它的实例。Err的属性被一个错误的生成器设置:Visual Basic,自动对象,或VBScript 程序。

Err 对象的默认属性是number。Err.Number 含有一个整数,且可由Automation 对象使用以返回SCODE。

当发生运行时错误时,Err 的属性由标识错误的唯一信息以及可用于处理它的信息填充。要在代码中生成运行时错误,请用Raise 方法。

Err 对象属性被重新设置为零或零长度字符串("")。Clear 方法可被用于显式地重新设置Err。

下面的示例说明了Err 对象的用法:

On Error Resume Next

Err.Raise 6 '产生溢出错误。

MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description

Err.Clear '清除错误。

在错误处理后,使用Clear 显式地清除Err 对象。此操作是必须的,例如使用On Error Resume Next 延迟错误处理时。在任何时候执行下列语句,VBScript 自动调用Clear 方法:

练习:写一个计算余数函数,该函数在计算出现错误时,输出错误号和错误描述,计算正确时,输出计算结果

On Error Resume Next

Dim a,b,c

a=CInt(InputBox ("请输入被除数:"))

b=CInt(InputBox("请输入除数:"))

c=a Mod b

If Err then

MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description

Err.Clear '清除错误。

Else

MsgBox c

End if

On Error 语句

On Error Resume Next会使程序按照产生错误的语句之后的语句继续执行,或是按照最近一次所调用的过程(该过程含有On Error Resume Next语句)中的语句继续运行。这个语句可以不顾运行时错误,继续执行程序,之后您可以在过程内部建立错误处理例程。在调用另一个过程时,On Error Resume Next 语句变为非活动的。所以,如果希望在例程中进行内部错误处理,则应在每一个调用的例程中执行On Error Resume Next语句。如果您已启用On Error Resume Next 错误处理程序,则可使用On Error GoTo 0禁用错误处理程序。

练习:用VBS实现冒泡排序,输入10个数,按从小到大的顺序排好。

练习:用VBS实现用户名和密码的输入验证,先输入用户名再输入密码:用户名必须是4~10位的字符,否则提示用户名为空、少于4位或多于10位。密码必须是Mercury(不区分大小写),如果输入为空则提示用户输入密码,如果连续三次未输入正确密码则提示用户重新登录,然后退出。

写一个函数,实现将大写字符转换成小写字符,将小写字符转换成大写字符

Dim intArray(9),i,j,t

For i=0 To 9

intArray(i)= CInt(InputBox("请输入第"&CStr(i+1)&"个数:")) Next

For i=0 To 8

For j=0 To 8-i

If intArray(j)> intArray(j+1) Then

t=intArray(j)

intArray(j)=intArray(j+1)

intArray(j+1)=t

End If

Next

Next

Dim strResult

For i=0 To 9

strResult=strResult&" "&intArray(i)

Next

MsgBox strResult

Dim iCount,strUser,strPwd,iLen

iCount=0

Do

iCount=iCount+1

strUser=InputBox("请输入用户名","用户名")

iLen=Len(strUser)

Select Case iLen

Case 0

MsgBox "输入的用户名为空",48

Case 1,2,3

MsgBox "输入的用户名不足3位",48

Case 4,5,6,7,8,9,10

.

Exit Do

Case Else

MsgBox "用户名超过10位",48

End Select

Loop

iCount=0

Do

If iCount=3 Then

Msgbox "连续输入3次密码错误,请重新登录",48

Exit Do

End If

iCount=iCount+1

strPwd=InputBox("请输入密码","密码")

strPwd=UCase(Trim(strPwd))

If strPwd="MERCURY" Then

MsgBox "恭喜您,密码正确",64

Exit Do

Else

MsgBox "密码错误,请重新输入",48

End If

Loop

CreateObject函数:创建并返回对Automation 对象的引用

Automation 对象就是与其他应用程序交互的中介

Set myObj = CreateObject("WScript.Shell")

Set myObj = CreateObject("Excel.Application")

Set myObj = CreateObject("Scripting.FileSystemObject")

Set myObj = CreateObject("Scripting.Dictionary")

Set myObj = CreateObject("ADODB.Connection")

Set myObj = CreateObject("ADODB.Recordset")

Set myObj = CreateObject("https://www.doczj.com/doc/3b13232515.html,mand")

Set myObj = CreateObject("Microsoft.XMLDOM")

文本文件读写:

AtEndOfLine和AtEndOfStream的区别:前者遇到空行就返回true,后者到达文件的末尾才返回true。

Option Explicit

Const ForReading=1,ForWriting=2,ForAppending=8

Dim fso,fil,msg

' 创建一个文件系统对象(File System Object)

Set fso = CreateObject("Scripting.FileSystemObject")

.

' 创建一个文件对象,通过fso对象来打开指定的文件

Set fil = fso.OpenTextFile("C:\f.txt",ForReading)

' 读取文件内容

' MsgBox fil.ReadAll ' 一次性全部读取

' 判断是否到了文件的最后面

Do While Not fil.AtEndOfStream ‘注意和AtEndOfLine的区别

' 只要没到最后,就读取一行,同时把游标向下移动一行

msg = msg & vbNewLine & fil.ReadLine

Loop

MsgBox msg

' 关闭这个文件

fil.Close

' 释放这个文件对象

Set fil = Nothing

' 释放这个文件系统对象

Set fso = Nothing

课堂练习:写一个函数,实现向log.txt文件中插入记录的功能

Option Explicit

Const ForReading=1,ForWriting=2,ForAppending=8

Dim fso,fil,msg

' 创建一个文件系统对象(File System Object)

Set fso = CreateObject("Scripting.FileSystemObject")

' 创建一个文件对象,通过fso对象来打开指定的文件

Set fil = fso.OpenTextFile("C:\log.txt",ForAppending)

fil.WriteLine "hello"

fil.Close

' 释放这个文件对象

Set fil = Nothing

' 释放这个文件系统对象

Set fso = Nothing

课堂练习:将上面计算余数的函数结果和错误记录方式改为调用记录结果的函数

Option Explicit

On Error Resume Next

Dim a,b,c

a=InputBox ("请输入被除数:")

b=InputBox("请输入除数:")

c=a Mod b

If Err then

WriteLog "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear '清除错误。

Else

WriteLog a&"与"&"b的余数为:"&c

End If

Function WriteLog(Content)

Const ForReading=1,ForWriting=2,ForAppending=8

Dim fso,fil,msg

' 创建一个文件系统对象(File System Object)

Set fso = CreateObject("Scripting.FileSystemObject")

' 创建一个文件对象,通过fso对象来打开指定的文件

Set fil = fso.OpenTextFile("C:\log.txt",ForAppending)

fil.WriteLine Now & " " & Content

fil.Close

' 释放这个文件对象

Set fil = Nothing

' 释放这个文件系统对象

Set fso = Nothing

End function

Excel文件读写:

Excel对象模型:

Application对象

WorkBook对象

WorkSheet对象

UsedRange对象:Rows属性,Columns属性

Cells对象:Rows属性,Columns属性

练习:打开calc.xls文件,读取内容

Option Explicit

Dim excelApp,excelWorkBook,excelWorkSheet

Dim iRowsCount,iColumnsCount,iLoop,jLoop,msg

' 创建Excel应用程序对象

Set excelApp = CreateObject("Excel.Application")

' 默认的Excel应用程序是隐藏的,这里强行显示给用户看

excelApp.Visible = True

' 创建工作簿对象,并打开它

Set excelWorkBook = excelApp.Workbooks.Open("E:\WORK\课程PPT\01 QTP\发给学员\calc.xls")

' 创建工作表对象,并指定工作表

Set excelWorkSheet = excelWorkBook.Worksheets("calcsheet")

' 获取已用区域的行数

iRowsCount = https://www.doczj.com/doc/3b13232515.html,edRange.Rows.Count

' 获取已用区域的列数

iColumnsCount = https://www.doczj.com/doc/3b13232515.html,edRange.Columns.Count

' 循环读取该区域内的数据

For iLoop=1 To iRowsCount

For jLoop=1 To iColumnsCount

msg = msg & vbTab & excelWorkSheet.Cells(iLoop,jLoop)

Next

msg = msg & vbNewLine

Next

MsgBox msg

' 保存Excel工作簿

excelWorkBook.Save

' 关闭Excel工作簿

excelWorkBook.Close

' 退出Excel应用程序

excelApp.Quit

' 释放Excel所有对象

Set excelWorkSheet = Nothing

Set excelWorkBook = Nothing

Set excelApp = Nothing

XML文件读写:

ReadXML

Sub ReadXML()

Dim xmlDoc, xmlRoot, rootChildItem, msg

Set xmlDoc = CreateObject("Microsoft.XMLDOM")

xmlDoc.Load " E:\WORK\课程PPT\01 QTP\发给学员\calc.xml"

If xmlDoc.parseError.errorCode <> 0 Then

MsgBox "XML loaded failed. The reason is :" & xmlDoc.parseError.reason

Exit Sub

End If

Set xmlRoot = xmlDoc.documentElement

If Not xmlRoot.hasChildNodes Then

Exit Sub

End If

For Each rootChildItem In xmlRoot.childNodes

If rootChildItem.nodeName = "TestResult" Then

msg = msg & rootChildItem.firstchild.nodeValue & vbNewLine

End If

Next

MsgBox msg

End Sub

数据库读写:

新建一个文本文件(获取数据库连接参数),然后把后缀改成udl(use data link),双击启动该文件。

首先选择要连接的数据库类型:

Access数据库:

Oracle数据库:

SQL Server数据库:

相关主题
文本预览
相关文档 最新文档