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

你可能感兴趣的:(用python调用excel里的vba程序)