结合作者提出的解决方案,我发现有时当你在个人宏工作簿中有宏时,打开工作簿的计数器会发生变化。这就是为什么我添加了一个简单的函数来处理这种情况。在
在我的例子中,有时我会打开多个excel文件,这样可以很方便地删除受宏影响但又不想关闭的工作簿。在def quit_excel(wb):
"""wb: workbook object from xlwings"""
print(wb.app.books) # for debugging and visualization of opened workbooks
# look if PERSONAL.XLSB is in the list of books associated with the Excel App
if "PERSONAL.XLSB" in [b.name for b in wb.app.books]:
if len(wb.app.books) == 2:
print("personal, 2, quitting")
wb.app.quit()
else:
print("personal, closing")
wb.close()
else:
if len(wb.app.books) == 1:
print("no personal, 1, quitting")
wb.app.quit()
else:
print("no personal, closing")
wb.close()