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.
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.