用python调用excel里的vba程序

def Excel(filename=r"macroTest.xlsm",visible=True):
    try: 
        import win32com.client,os,sys
        excelFile=r"%s\%s"%(sys.path[0],filename) #待测试 excel文件路径
        xlApp = win32com.client.Dispatch('Excel.Application')
        xlApp.visible=visible
        bFile=False
        for each in xlApp.Workbooks:
            if each.Fullname==excelFile:
                bFile=True
                xlWorkbook=each
                break
        if not bFile:
            xlWorkbook=xlApp.Workbooks.open(excelFile)
        strMacro=xlWorkbook.fullname+r"!test.test()"        
        xlApp.ExecuteExcel4Macro(strMacro)
    except Exception, e:
        print "Exception :",e
    finally:
        print "work finished"


if __name__ == '__main__':
    Excel()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容