首页 > 其他 > 详细

vbs中对excel的常用操作

时间:2014-02-26 00:13:53      阅读:596      评论:0      收藏:0      [点我收藏+]

使用QTP自动化测试中,用到对excel的读写操作,这里把一些常用对excel操作的方法进行了归纳,总结。(对excel格式设置的常用操作这里没有进行总结。)

bubuko.com,布布扣
bubuko.com,布布扣
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
bubuko.com,布布扣

补充:
excel文件另存为的操作:

1.工作表对象的SaveAs方法

exlBook.SaveAs(filepath & filename)

2.通过WScript对象实现:

Set shell = CreateObject("WScript.shell")

shell.SendKeys "^S"

shell.SendKeys filepath

shell.SendKeys "{enter}"

shell.SendKeys "%Y"

vbs中对excel的常用操作

原文:http://www.cnblogs.com/emilyzhang68/p/3566723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!