用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()

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容