Search code examples
pythonpython-3.xpywin32win32com

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


I'm trying to execute a macro using the win32com.client module in Python and have been able to successfully open and execute my macro (which runs without error when interacting with it through Microsoft Excel). Once the macro has finished executing and produces the desired output in the Excel workbook, the Python program crashes and gives me an error like:

>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)

Below is my code:

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()

Solution

  • Ended up just doing an 'except' and passing the error and just killing the window once I was done with the macro.