Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running VBA code from Python: macros may be disabled

Trying to run an Excel macro via Python I get the following error:

    Traceback (most recent call last):
    File ".\test.py", line 17, in <module>
        xlApp.Application.Run(MACRO)
    File "<COMObject <unknown>>", line 14, in Run
    File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
        result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
    pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)

I tried many of the fixes suggested in other questions.

I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.

Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.

As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.

I am running Python 3.6.5 on a 64 bit system, Windows 10.

Python:

    import win32com.client
    import os
    import traceback

    DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
    FILE = 'test.xlsb'
    MACRO = 'test'   
    path = os.path.join(DIRECTORY, FILE)

    if os.path.exists(path):
        try:
            xlApp = win32com.client.Dispatch('Excel.Application')
            xlApp.DisplayAlerts = False
            xlApp.Visible = True
            wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
            xlApp.Application.Run(MACRO)
            wb.Close(SaveChanges=1)
            xlApp.Application.Quit()
            print('Code ran successfully.')

        except:
            print('An error was encountered; see traceback.')
            print(traceback.format_exc())
            xlApp.Quit()

VBA:

Public Sub test()
MsgBox "Hello World!"
End Sub
like image 422
Talin Wauchope Avatar asked Jan 24 '26 21:01

Talin Wauchope


1 Answers

xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.

like image 151
godGivesMeLanguages Avatar answered Jan 26 '26 13:01

godGivesMeLanguages