尝试通过Python运行Excel宏我收到以下错误:
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)
我尝试了other questions中建议的许多修补程序。
我尝试了'xlApp.Application.Run(wb.name + "!" + MACRO)'
。
这是一个命名约定问题吗?我通过Trust Center启用了所有内容,并将VBA sub更改为public。
作为旁注,我也无法从以编程方式打开的工作簿中运行宏(即,如果我手动尝试)。但是,如果我手动打开工作簿,一切都很好。
我在64位系统Windows 10上运行Python 3.6.5。
的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