pyvot: can I run Excel VBA macros from python script?

情到浓时终转凉″ 提交于 2019-12-01 09:54:01

问题


Say I have loaded Report WW26blueprint_with_chart_330.xlsm in the report object with the following code (the print.range is used here to test that the workbook is loaded):

import xl
report = xl.Workbook("Report WW26blueprint_with_chart_330.xlsm")
print report
print(report.range("A1:E50").get())

From the pyvot documentation I get that:

Pyvot is written on top of Excel’s COM API. You can always get the underlying COM object and make COM calls yourself

My Excel file has the following macros:

Macro1 
Масго2 
Macro7  

Can I run any of the above macros directly from the python script using python/pyvot?


回答1:


This did it for me:

report.xlWorkbook.Application.Run('Macro1')



回答2:


Didn't manage to do it with pyvot but can be done using pywin32 as following:

import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\florinescu_eduard\Downloads\\Report WW26blueprint_with_chart_330.xlsm",ReadOnly=1)
xl.Application.Run("Macro1")
xl.Workbooks(1).Close(SaveChanges=1)
xl.Application.Quit()
xl=0



回答3:


It's very important to make sure xl.Application.Quit() while you are debug. Other than you might get confused.



来源:https://stackoverflow.com/questions/17446807/pyvot-can-i-run-excel-vba-macros-from-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!