VBScript操作Excel

Add Data to a Spreadsheet Cell

Demonstration script that adds the words “Test Value” to cell 1,1 in a new spreadsheet.

  1. Set objExcel = CreateObject("Excel.Application")
  2. objExcel.Visible = True
  3. objExcel.Workbooks.Add
  4. objExcel.Cells(1, 1).Value = "Test value"

Add Formatted Data to a Spreadsheet

Demonstration script that adds the words “test value” to a new spreadsheet, then formats the cell containing the value.

  1. Set objExcel = CreateObject("Excel.Application")
  2. objExcel.Visible = True
  3. objExcel.Workbooks.Add
  4. objExcel.Cells(1, 1).Value = "Test value"
  5. objExcel.Cells(1, 1).Font.Bold = TRUE
  6. objExcel.Cells(1, 1).Font.Size = 24
  7. objExcel.Cells(1, 1).Font.ColorIndex = 3

Create User Accounts Based on Information in a Spreadsheet

Demonstration script that creates new Active Directory user accounts based on information stored in an Excel spreadsheet.

  1. Set objExcel = CreateObject("Excel.Application")
  2. Set objWorkbook = objExcel.Workbooks.Open _
  3.     ("C:\Scripts\New_users.xls")
  4.  
  5. intRow = 2
  6.  
  7. Do Until objExcel.Cells(intRow,1).Value = ""
  8.     Set objOU = GetObject("ou=Finance, dc=fabrikam, dc=com")
  9.     Set objUser = objOU.Create _
  10.         ("User", "cn=" & objExcel.Cells(intRow, 1).Value)
  11.     objUser.sAMAccountName = objExcel.Cells(intRow, 2).Value
  12.     objUser.GivenName = objExcel.Cells(intRow, 3).Value
  13.     objUser.SN = objExcel.Cells(intRow, 4).Value
  14.     objUser.AccountDisabled = FALSE
  15.     objUser.SetInfo
  16.     intRow = intRow + 1
  17. Loop
  18.  
  19. objExcel.Quit

Format a Range of Cells

Demonstration script that adds data to four different cells in a spreadsheet, then uses the Range object to format multiple cells at the same time.

  1. Set objExcel = CreateObject("Excel.Application")
  2.  
  3. objExcel.Visible = True
  4. objExcel.Workbooks.Add
  5.  
  6. objExcel.Cells(1, 1).Value = "Name"
  7. objExcel.Cells(1, 1).Font.Bold = TRUE
  8. objExcel.Cells(1, 1).Interior.ColorIndex = 30
  9. objExcel.Cells(1, 1).Font.ColorIndex = 2
  10. objExcel.Cells(2, 1).Value = "Test value 1"
  11. objExcel.Cells(3, 1).Value = "Test value 2"
  12. objExcel.Cells(4, 1).Value = "Tets value 3"
  13. objExcel.Cells(5, 1).Value = "Test value 4"
  14.  
  15. Set objRange = objExcel.Range("A1","A5")
  16. objRange.Font.Size = 14
  17.  
  18. Set objRange = objExcel.Range("A2","A5")
  19. objRange.Interior.ColorIndex = 36
  20.  
  21. Set objRange = objExcel.ActiveCell.EntireColumn
  22. objRange.AutoFit()

List Active Directory Data in a Spreadsheet

Demonstration script that retrieves data from Active Directory and then displays that data in an Excel spreadsheet.

  1. Const ADS_SCOPE_SUBTREE = 2
  2.  
  3. Set objExcel = CreateObject("Excel.Application")
  4.  
  5. objExcel.Visible = True
  6. objExcel.Workbooks.Add
  7.  
  8. objExcel.Cells(1, 1).Value = "Last name"
  9. objExcel.Cells(1, 2).Value = "First name"
  10. objExcel.Cells(1, 3).Value = "Department"
  11. objExcel.Cells(1, 4).Value = "Phone number"
  12.  
  13. Set objConnection = CreateObject("ADODB.Connection")
  14. Set objCommand =   CreateObject("ADODB.Command")
  15. objConnection.Provider = "ADsDSOObject"
  16. objConnection.Open "Active Directory Provider"
  17.  
  18. Set objCommand.ActiveConnection = objConnection
  19. objCommand.Properties("Page Size") = 100
  20. objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
  21. objCommand.CommandText = _
  22.     "SELECT givenName, SN, department, telephoneNumber FROM " _
  23.         & "'LDAP://dc=fabrikam,dc=microsoft,dc=com' WHERE " _
  24.             & "objectCategory='user'" 
  25. Set objRecordSet = objCommand.Execute
  26. objRecordSet.MoveFirst
  27. x = 2
  28.  
  29. Do Until objRecordSet.EOF
  30.     objExcel.Cells(x, 1).Value = _
  31.         objRecordSet.Fields("SN").Value
  32.     objExcel.Cells(x, 2).Value = _
  33.         objRecordSet.Fields("givenName").Value
  34.     objExcel.Cells(x, 3).Value = _
  35.         objRecordSet.Fields("department").Value
  36.     objExcel.Cells(x, 4).Value = _
  37.         objRecordSet.Fields("telephoneNumber").Value
  38.     x = x + 1
  39.     objRecordSet.MoveNext
  40. Loop
  41.  
  42. Set objRange = objExcel.Range("A1")
  43. objRange.Activate
  44.  
  45. Set objRange = objExcel.ActiveCell.EntireColumn
  46. objRange.Autofit()
  47.  
  48. Set objRange = objExcel.Range("B1")
  49. objRange.Activate
  50. Set objRange = objExcel.ActiveCell.EntireColumn
  51. objRange.Autofit()
  52.  
  53. Set objRange = objExcel.Range("C1")
  54. objRange.Activate
  55.  
  56. Set objRange = objExcel.ActiveCell.EntireColumn
  57. objRange.Autofit()
  58.  
  59. Set objRange = objExcel.Range("D1")
  60. objRange.Activate
  61.  
  62. Set objRange = objExcel.ActiveCell.EntireColumn
  63. objRange.Autofit()
  64.  
  65. Set objRange = objExcel.Range("A1").SpecialCells(11)
  66. Set objRange2 = objExcel.Range("C1")
  67. Set objRange3 = objExcel.Range("A1")

List Excel Color Values

Demonstration script that displays the various colors — and their related color index — available when programmatically controlling Microsoft Excel.

  1. Set objExcel = CreateObject("Excel.Application")
  2.  
  3. objExcel.Visible = True
  4. objExcel.Workbooks.Add
  5.  
  6. For i = 1 to 56
  7.     objExcel.Cells(i, 1).Value = i
  8.     objExcel.Cells(i, 1).Interior.ColorIndex = i
  9. Next

List Service Data in a Spreadsheet

Demonstration script that retrieves information about each service running on a computer, and then displays that data in an Excel spreadsheet.

  1. Set objExcel = CreateObject("Excel.Application")
  2. objExcel.Visible = True
  3. objExcel.Workbooks.Add
  4.  
  5. x = 1
  6. strComputer = "."
  7. Set objWMIService = GetObject _
  8.     ("winmgmts:\\" & strComputer & "\root\cimv2")
  9. Set colServices = objWMIService.ExecQuery _
  10.     ("Select * From Win32_Service")
  11.  
  12. For Each objService in colServices
  13.     objExcel.Cells(x, 1) = objService.Name
  14.     objExcel.Cells(x, 2) = objService.State
  15.     x = x + 1
  16. Next

Open an Excel Spreadsheet

Demonstration script that opens an existing Excel spreadsheet named C:\Scripts\New_users.xls.

  1. Set objExcel = CreateObject("Excel.Application")
  2. Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\New_users.xls")

Read an Excel Spreadsheet

Demonstration script that reads the values stored in a spreadsheet named C:\Scripts\New_users.xls.

  1. Set objExcel = CreateObject("Excel.Application")
  2. Set objWorkbook = objExcel.Workbooks.Open _
  3.     ("C:\Scripts\New_users.xls")
  4.  
  5. intRow = 2
  6.  
  7. Do Until objExcel.Cells(intRow,1).Value = ""
  8.     Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).Value
  9.     Wscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value
  10.     Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).Value
  11.     Wscript.Echo "LastName: " & objExcel.Cells(intRow, 4).Value
  12.     intRow = intRow + 1
  13. Loop
  14.  
  15. objExcel.Quit

VBScript字符操作函数

1、 字符串连接函数
Join(list[,delimiter])
说明:返回一个字符串,此字符串由包含在数组中的许多子字符串连接创建。
参数
list 必选项。包含要连接的子字符串一维数组。
Delimiter 可选项。在返回字符串中用于分隔子字符串的字符。如果省略,将使用空字符 (“”)。如果 delimiter 是零长度字符串,则在同一列表中列出全部项,没有分界符。
示例

  1. dim myarray(3)
  2. myarray(0)="垃圾邮件占用大量网络资源,"
  3. myarray(1)="并常常成为网络病毒传播的工具, "
  4. myarray(2)="威胁互联网信息安全,"
  5. myarray(3)="侵害了电子邮件用户的合法权益。"
  6. response.write JOIN(myarray)
  7. response.write ""
  8. response.write JOIN(myarray,"/")

注意:myarray必须是一个一维数组(一个列表)

2、字符串去空格函数
Trim(string) 将字符串前面和后面的空格去掉。
RTrim(string),将字符串右边的空格去掉。
LTrim(string), 将字符串左边的空格去掉。
示例

  1. dim a,b
  2. a="    Vbscript "
  3. b="    你好    "
  4. response.write b&"+"&a
  5. response.write ""
  6. response.write Trim(b)&"+"&Trim(a)'显示时,去掉字符串两边的空格。
  7. response.write ""
  8. response.write RTrim(b)&"+"&RTrim(a)'显示时,去掉字符串右边的空格。
  9. response.write ""
  10. response.write LTrim(b)&"+"&LTrim(a)'显示时,去掉字符串左边的空格。

3、字符串长度获取函数
(1) len(string)返回字符串内字符的数目。
(2) Left(string, length) 返回从字符串的左边算起的字符。
(3) Right(string, length)返回从字符串的右边算起的字符。
(4) Mid(string,start,length)返回字符串中指定数目的字符。
参数:
string给定字符串
start指定开始位置,如果 start 超过了 string 中字符的数目,Mid 将返回零长度字符串 (“”)。
length指定返回的数目,如果省略或 length 超过文本的字符数(包括 start 处的字符),将返回字符串中从 start 到字符串结束的所有字符。
示例

  1. dim a
  2. a="Vbscript,Javascript"
  3. '字符串中一共有多少字符
  4. response.write len(a) '显示19
  5. '从左边算起指定一个位置,返回从开始到该位置的字符
  6. response.write Left(a,8)'显示Vbscript
  7. response.write right(a,10) '显示Javascript
  8. '我想返回中间的"script,Java"
  9. response.write Mid(a,3,11)

4、字符串分割函数
Split(expression[, delimiter[, count[, start]]])
说明:返回基于 0 的一维数组,其中包含指定数目的子字符串。也就是说它把一个字符串分割成多个部分。分割操作的结果被放在一个数组中。
参数
expression
必选项。字符串表达式,包含子字符串和分隔符。如果 expression 为零长度字符串,Split 返回空数组,即不包含元素和数据的数组。
delimiter
可选项。用于标识子字符串界限的字符。如果省略,使用空格 (“”) 作为分隔符。如果 delimiter 为零长度字符串,则返回包含整个expression 字符串的单元素数组。
count
可选项。被返回的子字符串数目,-1 指示返回所有子字符串。
示例

  1. dim mystring, myarray
  2. mystring= "VBScriptXisXfun!"
  3. myarray=Split(mystring,"X" )'以“X”为分界符分割字符串
  4. response.write myarray(0)&""
  5. response.write myarray(1)&""
  6. response.write myarray(2)&""
  7. response.write JOIN(myarray)

缺省情况下,函数SPLIT()通过在空格处截断来分割一个字符串。然而,你可以为该函数提供第二个参数,根据其他的字符来分割字符串。缺省情况下,该函数能把一个字符串分割成多少部分,就分割成多少部分。但是你可以提供第三个参数来限制该函数返回的子字符串的数目。下面的这个例子使用了这两个附加参数:

  1. yarray=SPLIT(“Once upon a time,there were three bears.”,”,”,2)

在这个例子中,字符串被分割成两个。逗号左边的子字符串被保存在数组的第一个元素中;逗号右边的子字符串被保存在数组的第二个元素中

5、字符串过滤函数
Filter(InputStrings, Value[, Include[, Compare]])
说明:返回下标从零开始的数组,其中包含以特定过滤条件为基础的字符串数组的子集。
参数:
InputStrings
必选项。一维数组,要在其中搜索字符串。
Value
必选项。要搜索的字符串。
Include
可选项。Boolean 值,指定返回的子字符串是否包含 Value。如果 Include 为 True,Filter 将返回包含子字符串 Value 的数组子集。如果 Include 为 False,Filter 将返回不包含子字符串 Value 的数组子集。
Compare
可选项。数字值指出使用的比较字符串类型。

函数FILTER()可以过滤一个数组。假定你想从一个句子中过滤掉不包含字母t的每一个词。用函数FILTER(),请看下面的示例:

  1. dim mystr,myarray
  2. mystr="Once upon a time,there were three bears."
  3. myarray=SPLIT(mystr)'把字符串分割为数组,默认情况下以空格为分割符
  4. myarray=FILTER(myarray,"t")
  5. '函数FILTER()过滤掉所有不匹配字符串”t”的数组元素。
  6. response.write JOIN(myarray)&"
  7. "'把过滤后的字符串连接起来

如果你想从一个句子中过滤掉包含字母t的每一个词,那么就在函数Filter()中加入参数false。如下所示:

  1. dim mystr,myarray         
  2. mystr="Once upon a time,there were three bears."         
  3. myarray=SPLIT(mystr)'把字符串分割为数组,默认情况下以空格为分割符         
  4. myarray=FILTER(myarray,"t",false)'函数FILTER()过滤掉匹配特定字符串"t"的所有数组元素         
  5. response.write JOIN(myarray)'把过滤后的字符串连接起来

6、字符串替换函数
Replace(expression, find, replacewith)
返回字符串,其中指定数目的某子字符串find被替换为另一个子字符串replacewith;

  1. '用Java替换Vb         response.write replace("Vbscript","Vb","Java")

7、返回字符位置
InStr(string1,string2)
返回string2字符串在string1字符串中第一次出现的位置;

  1. dim a,b,c
  2. a="@Vbscript"
  3. b="Vbscr@ip@t"
  4. c="Vbscript"
  5. '返回@第一次出现的位置,如果返回0表示不存在
  6. response.write InStr(a,"@")&""
  7. response.write InStr(b,"@")&""
  8. response.write InStr(c,"@")

8、字符串比较函数
StrComp(string1,string2)对string1和string2进行二进制比较,
如果string1 小于 string2 返回 -1
如果string1 等于 string2 返回 0
如果string1 大于 string2 返回 1
如果string1 或 string2 为 Null 返回 Null

  1. dim a,b,c
  2. a="Vbscript"
  3. b="Vbscript"
  4. c="Javascript"
  5. '如果a与b相等,则返回0
  6. response.write StrComp(a,b)
  7. '如果a大于c则返回1,反之返回-1
  8. response.write StrComp(a,c)
  9. response.write StrComp(c,a)
  1. dim a,b
  2. '给定密码
  3. a="123456"
  4. '再次输入密码b
  5. b="234567"
  6. if StrComp(a,b)<>0 then
  7. response.write "你输入的密码不正确"
  8. end if

示例解读
函数StrComp进行二进制比较,是一种严格比较,例如:比较a与a则相等,而a与A检查结果会不相等。

QTP中Window ID属性有什么用?何时会变?

相信很多人都有这个疑问。

Window Id对应Windows应用程序的控件ID(Control ID),是指Windows指定给每个控件的数值型标识符,用来标识一种控件类型。不同类型的控件id就会不一样,同样类型的控件id是一样的。例如windows资源管理器的control id和打开文件对话框中的资源管理器属于同样的控件,它们的control id都是1

如果应用程序调用系统控件,那么系统控件的windows id 一般都是0。比如window内置的 open(打开), save as(另存为) 等等窗口得id都为0。

Window Id在运行前后一般都不会有什么变化。如果变了,应该不是id变,而是控件变了

如何遍历WebTable中的单元格

QTP中的WebTable测试对象提供了RowCount和ColumnCount,可用于遍历WebTable中的所有单元格。

  1. Set wtObj = Browser(XXX).Page(XXX).WebTable(XXX)
  2. For i = 1 To wtObj.RowCount
  3. For j =1 To wtObj.ColumnCount(i)
  4. 'Set cellLink = wtObj.ChildItem(i,j,"Link",0) '取每个单元格中的链接对象
  5. msgbox wtOjb,GetCellData(i,j) '取每个单元格的内容
  6. Next
  7. Next

其中用到了两个方法
object.ChildItem (Row, Column, MicClass, Index)
object.GetCellData(Row, Column)
Row – 行号
Column – 列号
MicClass – 对象的类型
Index – 对象的索引序号,比如如果取第一个符合条件的对象,则index=0

解决ExecuteFile调用外部的VBS文件时提示”无效字符”的问题

出现这个问题的原因:
从QTP新建的Function Library文件是以Unicode编码被保存下来的,而正常执行的文件一定要是ANSI编码,所以导致出现”无效字符”的提示

解决办法:
1. 用记事本打开该vbs文件,然后点击”另存为”,编码选择”ANSI”,覆盖掉原来的文件即可
2. 对于要用ExecuteFile引用的vbs文件,最好用记事本或其他编辑工具保存为ANSI编码的,QTP只能保存成Unicode的所以不要用QTP(这也算是QTP的一个bug)

QTP同时注释多行的技巧

第一种,用菜单的方式
注释:选中要注释掉的那几行代码,点击右键,选择”Comment Block”
取消注释:选中要注释掉的那几行代码,点击右键,选择”Uncomment Block”

第二种,用快捷键
注释:选中要注释掉的那几行代码,按Ctrl + M
取消注释:选中要注释掉的那几行代码,按Ctrl + Shift + M

QTP链接SqlServer数据库

  1. Dim rs,conn,sqlstr,strcon
  2. strcon = "Provider=SQLOLEDB.1;User ID=sa;Password=srt123321;"&_
  3. "Data source=192.168.4.112;DATABASE=default_meg_db"
  4. Set conn = createobject("adodb.connection")
  5. conn.open strcon
  6. sqlstr="SELECT * FROM TEST"
  7. Set rs=createobject("adodb.recordset")
  8. rs.open sqlstr,conn,1,1
  9. msgbox rs("TS_NAME")
  10. rs.Close
  11. Set rs = nothing
  12. conn.Close
  13. Set conn = nothing

QTP中如何获取错误信息

在执行QTP脚本的时候,如果出现错误,例如对象不识别等,如何捕捉到错误信息呢?

Vbscript提供了Err对象
Err.Number 返回VBScript 错误编号或 SCODE 错误值的整数
Err.Source 返回生成错误的应用程序
Err.Description 返回包含错误说明的字符串表达式

可以运行以下代码,查看运行结果中三个属性的返回值是什么

  1. On Error Resume Next
  2. Err.Raise 6   ' 引发溢出错误。
  3. MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description & Err.Source)
  4. Err.Clear   ' 清除该错误