excel宏和python,通过Python运行Excel宏?

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

xl.Application.Run("macrohere")

File ">", 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

# 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:

Code

import os

import win32com.client

if 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

Hope that helps

All the best SMNALLY

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值