目前我试图用Python和win32com取消Excel的close事件。一个月前,我已经设法用IronPython处理了这个问题。但出于公司部门的进一步考虑,这应该也可以使用Python。接下来你会看到两个片段。第一个将包含正在工作的IronPython代码
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
clr.AddReference("System.Windows.Forms")
from Microsoft.Office.Interop import Excel
from System.Windows.Forms import Form, Application, MessageBox, MessageBoxButtons, MessageBoxIcon, DialogResult
class CloseEventTry(Form):
def __init__(self):
excel = Excel.ApplicationClass()
excel.Visible = True
excel.DisplayAlerts = False
self.workbooks = excel.Workbooks.Add()
self.Text = "Dummy GUI Window"
#link "BeforeCloseEvent" to the "beforeClose" method
self.workbooks.BeforeClose +=Excel.WorkbookEvents_BeforeCloseEventHandler(self.beforeClose)
def beforeClose(self, cancel):
print type(cancel) #Type: 'StrongBox[bool]
choice = MessageBox.Show("Close Excel", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
if choice == DialogResult.Yes:
cancel.Value = False #do't cancel the close action
self.Close()
elif choice == DialogResult.No:
cancel.Value = True #prevent excel from closing
Application.Run(CloseEventTry())
第二个版本将包含Python和win32com的版本。这篇文章基于我的IronPython代码片段和该链接的示例
https://win32com.goermezer.de/microsoft/office/events-in-microsoft-word-and-excel.html
^{pr2}$正如您将看到的,我可以连接到“OnBeforeClose”事件,但是不能取消close事件,就像我在IronPython版本中所做的那样。正如在上一个代码片段的注释中提到的,Python版本会引发AttributeError异常。此外,您还可以看到,事件处理程序所需的“cancel”变量的类型有两种不同的类型。在IronPython版本中,它是一个“StrongBox[bool]”。另一方面,Python版本的类型是一个常见的“class'bool'”类型(这解释了异常)。我就是这么想的
cancel = True #prevent excel from closing
但用这种方式,excel还是会关闭。 我也做了一些研究,但没有找到解决这个问题的办法。我的假设是需要某种包装?在
您可以通过返回所需的cancel值来实现与IronPython版本相同的行为,例如
以防您想中止关闭事件。
问候
相关问题 更多 >
编程相关推荐