Is there a way to call python with xlwings without reopening the Excel file?

白昼怎懂夜的黑 提交于 2019-12-18 22:33:22

问题


I am calling python from Excel using xlwings. I find that when running my macro, Excel closes and reopens in order to run the code. It functions correctly but it slows things down. In addition, if the Excel file is unsaved a dialog will mention that the file is already open and that I will lose unsaved changes.

Is there a way to call python without reopening the Excel file?

This is my python code (in loaddf.py):

from xlwings import Workbook, Range, Sheet

def my_macro():
    wb = Workbook.caller()
    Range('A1').value = Range('A1').value + 1

And the VBA code in my Excel file:

Sub loaddfsub()
    RunPython ("import loaddf; loaddf.my_macro()")
End Sub

Thanks for the help.


回答1:


It seems that under certain circumstances, Excel doesn't register an Excel Workbook properly in the RunningObjectTable, a precondition so it can be found via COM. So far I've only noticed this behaviour for Workbooks downloaded from the internet given it opens them in the Protected View mode first (depends on Settings). However, based on the feedback here, it seems that it can also happen under other circumstances, possibly caused by some add-ins or security settings.

I've implemented a fix for this which will be present in v0.3.1, but you can get it right now directly from GitHub. Let me know if you need help there.

Update (16-Jan-2015): xlwings v0.3.1 including this fix has just been released.

Update2 (13-Sept-2015): xlwings v0.4.0 should finally fix this bug in a reliable way.



来源:https://stackoverflow.com/questions/27802340/is-there-a-way-to-call-python-with-xlwings-without-reopening-the-excel-file

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