我正在尝试使用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\3.7\00020813-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()
答案 0 :(得分:0)
最后,只做了一个'except'并传递了错误,并在我完成宏后杀死了窗口。