'========================================
'名 称:QTP_ReadExcel
'作 用:从Excel读数据
'参 数:sFileName:EXCEL文件名 sSheetName:Sheet表名
'返回值:把EXCEL变为2维数组返回
'========================================
Function QTP_ReadExcel(sFileName,sSheetName)
Dim oExcel
Dim oSheet
Dim oRange
Dim arrRange
On Error Resume Next
' 创建Excel应用程序对象
Set oExcel = CreateObject("Excel.Application")
If err.Number <> 0 Then
MsgBox "未能初始化Excel" & vbCrLf & "请确保Excel已安装", vbCritical
Exit Function
End If
On Error GoTo 0
On Error Resume Next
' 打开Excel文件
oExcel.Workbooks.Open(sFileName)
If err.Number <> 0 Then
MsgBox "未能加载Excel文件" & vbCrLf & "请确保Excel文件路径正确或格式正确", vbCritical
Exit Function
End If
On Error GoTo 0
' 获取表格的使用范围
Set oSheet = oExcel.Worksheets(sSheetName).UsedRange
' 获取从A列到Z列,从第1行到第1000行的范围i中的所有值
Set oRange = oSheet.Range("A1:Z1000")
'把Excel数据转换到数组
arrRange = oRange.Value
' 关闭工作簿
oExcel.WorkBooks.Item(1).Close
' 退出Excel
oExcel.Quit
Set oExcel = Nothing
' 返回包含Excel数据的数组
QTP_ReadExcel = arrRange
End Function
Dim arrExcel
arrExcel = QTP_ReadExcel("D:\test.xls","sheet1")
Dim randcs
randcs=RandomNumber(0,1000)
Dim user
Dim pwd
user=arrExcel(randcs,1)
pwd=arrExcel(randcs,2)