本文介绍了通过Python运行Excel宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图通过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.clientxl=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我得到以下追溯: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) EDITEDITimport win32com.clientxl=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推荐答案除了您正在调用的宏的错误之外,请尝试以下代码:I would except the error is to do with the macro you're calling, try the following bit of code:import osimport win32com.clientif os.path.exists("excelsheet.xlsm"): xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\Full Location\To\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希望帮助 所有最好的SMNALLYHope that helpsAll the best SMNALLY 这篇关于通过Python运行Excel宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-01 14:55