<p>I’m trying to run a macro via python but I’m not sure how to get it working…</p>
<p>I’ve got the following code so far, but it’s not working.</p>
<pre><code class="lang-auto">import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
</code></pre>
<p>I get the following traceback:</p>
<pre><code class="lang-auto">Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in ApplyTypes
result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
</code></pre>
<h2><a name="p-34947-edit-1" class="anchor" href="#p-34947-edit-1" aria-label="Heading link"></a>EDIT</h2>
<pre><code class="lang-auto">import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
It does run like this... but we get the following error:
Traceback (most recent call last):
File "C:\test.py", line 7, in <module>
xl.Workbooks(1).Close(SaveChanges=0)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in call
return self.get_good_object(self.oleobj.Invoke(*allArgs),self.olerepr.defaultDispatchName,None)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
Except isn't catching the above error... 🙁
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
</code></pre>