0

I am trying to read a macro in excel through python code but not able to do so as it is not able to find the macro. Also apart from the code if I try to view the macro just by opening Excel > Alt + F11 then I am supposed to enter the password. Is this the reason that the python code is not able to read the macro as I am trying to read a password protected macro using python. If so, please suggest what should be the workaround to read it. Thanks! Attaching the code snippet and error below :

    Code :
    import os
    import win32com.client

    os.chdir("C:\new folder\Input folder")    
    if os.path.exists("Input excel.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath("Input excel.xlsm"))
    xl.Application.Run("Input excel.xlsm!module1.mymethod")  #mymethod is of type sub
    xl.Application.Save()
    xl.Application.Quit() 
    del xl

    Error :
    result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
    pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'Input excel.xlsm!module1.mymethod'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)

I have tried all the below possible solutions but the issue is still there :

    1) Using the correct convention to call the macro : xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    2) Changing the excel settings :
       1.File > Options > Trust Center
       2.Click on Trust Center Settings... button
       3.Macro Settings > Check Enable all macros
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ans
  • 39
  • 1
  • 6
  • 1
    Possible duplicate of [Using Python to read VBA from an Excel spreadsheet](https://stackoverflow.com/questions/12287677/using-python-to-read-vba-from-an-excel-spreadsheet) – eirikdaude Jul 30 '18 at 11:01
  • 1
    The difference between Ans's question and that in @eirikdaude's suggestion is that for this question, the code is locked for viewing. I don't know about Python, but it's a real pain to do this even with VBA - which inherently has access to the `VBProject`. The only way to do it there is a messy send-key method once the Password input pop-up appears. I guess it might be possible to replicate that whole process in Python.. Good luck! – CLR Jul 30 '18 at 13:00

0 Answers0