vbs中對excel的經常使用操做

使用QTP自動化測試中,用到對excel的讀寫操做,這裏把一些經常使用對excel操做的方法進行了概括,總結。(對excel格式設置的經常使用操做這裏沒有進行總結。)shell

Function DataToExcel(byval filepath,byval filename)

    Dim objExcel,exlSheet,exlBook,fso,exApp,rows,cols

    '關閉全部excel
    'SystemUtil.CloseProcessByName("excel.exe")

    Set objExcel = createobject("Excel.Application")
    Set fso = createobject("scripting.filesystemobject")
                  Set exApp = getObject(,"excel.application")

    '關閉全部打開的excel文件
    If  TypeName(exApp) = "Application" Then
        For each objBook in exApp.workbooks
            msgbox objBook.FullName
            objBook.close

        Next
    End If    

    Set exApp = nothing
    
    If fso.FileExists(filepath & filename) Then
        Set exlBook =objExcel.Workbooks.Open(filepath & filename)
    else
        Set exlBook = objExcel.Workbooks.Add
    End If
    
    objExcel.DisplayAlerts = false
    'set exlBook = objExcel.Workbooks.Add        '建立excel
    '獲取指定工做表
    Set exlSheet = exlBook.Worksheets("sheet1")
    '或Set exlSheet = exlBook.worksheets(1).activate    

    exlSheet.cells(1,1).value = "aa"
    
    '獲取excel可用的範圍
    rows = exlSheet.usedrange.rows.count
    cols = exlSheet.usedrange.columns.count

    '設置單元格的列度
    exlSheet.Columns("A").ColumnWidth = 20
    '設置單元格的行高
    exlSheet.Range("A1").RowHeight = 15

    exlBook.SaveAs(filepath & filename)   'excel另存爲
    'objExcel.SaveWorkspace       '保存excel文件
    'exlBook.close                       '關閉sheet頁面
    objExcel.Quit


    Set exlSheet = nothing
    Set exlBook = nothing
    Set objExcel = nothing
    Set fso = nothing

End Function


Call DataToExcel ("D:\Documents\Desktop\","hello.xls")
View Code

補充:
excel文件另存爲的操做:app

1.工做表對象的SaveAs方法ide

exlBook.SaveAs(filepath & filename)測試

2.經過WScript對象實現:ui

Set shell = CreateObject("WScript.shell")spa

shell.SendKeys "^S"excel

shell.SendKeys filepathcode

shell.SendKeys "{enter}"對象

shell.SendKeys "%Y"blog

相關文章
相關標籤/搜索