简体   繁体   English

有没有一种方法可以使用xlwings调用python而无需重新打开Excel文件?

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

I am calling python from Excel using xlwings. 我正在使用xlwings从Excel调用python。 I find that when running my macro, Excel closes and reopens in order to run the code. 我发现在运行宏时,Excel将关闭并重新打开以运行代码。 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. 此外,如果未保存Excel文件,将出现一个对话框,提示该文件已打开,并且我将丢失未保存的更改。

Is there a way to call python without reopening the Excel file? 有没有一种方法可以在不重新打开Excel文件的情况下调用python?

This is my python code (in loaddf.py): 这是我的python代码(在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: 以及我的Excel文件中的VBA代码:

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. 在某些情况下,Excel似乎没有在RunningObjectTable正确注册Excel Workbook,这是前提条件,因此可以通过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). 到目前为止,我只注意到从Internet下载的工作簿的这种行为,因为它首先在“ Protected View模式下打开了它们(取决于“设置”)。 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 . 我已经为此实现了一个修复程序,该修复程序将在v0.3.1 ,但是您现在可以直接从GitHub获得 Let me know if you need help there. 让我知道您是否需要帮助。

Update (16-Jan-2015): xlwings v0.3.1 including this fix has just been released. 更新 (2015年1月16日):包括此修复程序的xlwings v0.3.1刚刚发布。

Update2 (13-Sept-2015): xlwings v0.4.0 should finally fix this bug in a reliable way. Update2 (2015年9月13日):xlwings v0.4.0最终应该以可靠的方式修复此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM