尝试通过 Python 来 运行 宏,宏 运行s 但在执行后崩溃并出现错误

Trying to run a macro via Python, macro runs but after execution crashes with an error

我正在尝试使用 Python 中的 win32com.client 模块执行一个宏,并且已经能够成功打开并执行我的宏(通过 Microsoft Excel).一旦宏完成执行并在 Excel 工作簿中生成所需的输出,Python 程序就会崩溃并给我一个错误,如:

>Traceback (most recent call last):
 File"my\path\to\python\program", line 19, in <modlule>
 xl.Application.Run('main')
 File"my\path\AppData\Local\Temp\gen_py.7[=12=]020813-0000-0000-C000-000000000046x0x1x9\_Application.py", line 376, in Run
, Arg26, Arg27, Arg28, Arg29, Arg30
File"my\path\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\__init__.py", line 467, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
 pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)

下面是我的代码:

import win32com.client
import win32com
import os, os.path

xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
xl.Workbooks.Open(Filename=r"my\path\Desktop\WorksWithPy.xlsm")
xl.Visible = True
xl.Workbooks(1).Worksheets(1).Cells(4, 7).Value = r"17639d0c-2007-4a68-a0fd0b615d6f8fed"
xl.Workbooks(1).Worksheets(1).Cells(7, 7).Value = r'\local\server\address'
xl.Application.Run(r'main')
xl.Workbooks(1).SaveAs(Filename=r'my\path\Desktop\sameFileButWithDesiredResults.xlsm', FileFormat=52)
xl.Workbooks(1).Close(0)
xl.Quit()

最后只是做了一个 'except' 并传递了错误,并在我完成宏后就杀死了 window。