Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running an Excel macro via Python?

I'm trying to run a macro via python but I'm not sure how to get it working...

I've got the following code so far, but it's not working.

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 

I get the following traceback:

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) 

EDIT

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 
like image 730
Ryflex Avatar asked Oct 27 '13 08:10

Ryflex


People also ask

Can I write Excel macro in Python?

You can write an Excel macro in python to do whatever you would previously have used VBA for. Macros work in a very similar way to worksheet functions. To register a function as a macro you use the xl_macro decorator. Macros are useful as they can be called when GUI elements (buttons, checkboxes etc.)

Can I use Python instead of VBA in Excel?

Yes, absolutely! VBA is commonly used to automate Excel with macros, add new user defined worksheet functions (UDFs) and react to Excel events. Everything you would previously have done in Excel using VBA can be achieved with Python. Using Python as a VBA replacement has many benefits and is usually faster than VBA!

Can Python run Excel code?

In short, executing Python via Excel provides those with sufficient experience in the language with an avenue to efficiently communicate and visualize their data in a way that most people can see and understand.


2 Answers

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

    #Import the following library to make use of the DispatchEx to run the macro     import win32com.client as wincl      def runMacro():          if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):          # DispatchEx is required in the newest versions of Python.         excel_macro = wincl.DispatchEx("Excel.application")         excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")         workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)         excel_macro.Application.Run\             ("ThisWorkbook.Template2G")         #Save the results in case you have generated data         workbook.Save()         excel_macro.Application.Quit()           del excel_macro 
like image 39
abautista Avatar answered Sep 20 '22 13:09

abautista


I would expect the error is to do with the macro you're calling, try the following bit of code:

Code

import os, os.path import win32com.client  if os.path.exists("excelsheet.xlsm"):     xl=win32com.client.Dispatch("Excel.Application")     xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1)     xl.Application.Run("excelsheet.xlsm!modulename.macroname") ##    xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.     xl.Application.Quit() # Comment this out if your excel script closes     del xl 
like image 153
SMNALLY Avatar answered Sep 19 '22 13:09

SMNALLY