原创:转载请注明出处:--Jason Lee
放在DLL-VB(动态库工程)中的常用的excel操作的代码:
以下函数对于读取单个的单元格的值比较方便,如果要去很多单元格的值,经测试,此函数效率不高。
Function ReadExcelForCell(sFileName, nIndex, nRow, nColumn)
Dim oExcelApp 'as excel.application
Dim oExcelBook 'as excelbook object
Dim oExcelSheet 'as excelsheet object
Dim sStr1 'to stroe the return value(string)
Set oExcelApp = CreateObject("Excel.Application")
Set oExcelBook = oExcelApp.Workbooks.Open(sFileName)
Set oExcelSheet = oExcelBook.Worksheets.Item(nIndex)
sStr1 = oExcelSheet.Cells(nRow, nColumn)
ReadExcelForCell = sStr1
Set oExcelSheet = Nothing
oExcelBook.Close
oExcelApp.Quit '必须退出对象,要不会一直存在excel的进程。
Set oExcelBook = Nothing
Set oExcelApp = Nothing
End Function
下面的这个函数对于一次读取很多值很方便,不会频繁的调用函数锁在的堆栈,效率更高~
Function ReadExcelForArray(sFileName, nIndex)
Dim oExcelApp 'as excel.application
Dim oExcelBook 'as excelbook object
Dim oExcelSheet 'as excelsheet object
Dim sStr1 'to stroe the return value(string)
Set oExcelApp = CreateObject("Excel.Application")
Set oExcelBook = oExcelApp.Workbooks.Open(sFileName)
Set oExcelSheet = oExcelBook.Worksheets.Item(nIndex)
sStr1 = oExcelSheet.UsedRange.Cells
ReadExcelForArray = sStr1
Set oExcelSheet = Nothing
oExcelBook.Close
oExcelApp.Quit '必须退出对象,要不会一直存在excel的进程。
Set oExcelBook = Nothing
Set oExcelApp = Nothing
End Function
这个函数的核心就是让excel中的值传给数组。
QTP对于excel的应用主要是读取其中的值,写的操作一般用的不多。