Python:使用Python运行Excel宏 [英] Python : running Excel macro with python

查看:645
本文介绍了Python:使用Python运行Excel宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过python运行Excel宏,并且总是出现以下错误:

I need to run an Excel macro via python and I always get the following error :

result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)

在Excel中,它显示以下错误:

In Excel, it is giving the following error :

运行时错误1004: 无法运行宏.该宏可能在此工作簿中不可用,或者所有宏都可能被禁用.

Run-time error 1004: Cannot run the macro ". The macro may not be available in this workbook or all macros may be disabled.

我的代码如下:

xl=win32.Dispatch("Excel.Application")
wb=xl.Workbooks.Open(Filename="Path+MyExcelFile.xlsm", ReadOnly=1)
xl.Visible = True
time.sleep(1)
ws=wb.Worksheets("Sheet1")
ws.Cells(4,2).Value='Value1'
ws.Cells(5,2).Value='Value2'
ws.Cells(1,8).Value='Bool'
time.sleep(10)
xl.Application.Run("MyExcelFile.xlsm!macroname")
result = ws.Cells(3,10).Value
print result
xl.Application.Quit()
del xl

我通过宏"安全性启用了所有宏,并且未为特定工作表定义该宏.当然,如果我在Excel中手动运行该宏,则该宏会正常工作

I enabled all macros through Macros security, and the macro is not defined for a specific sheet. And of course the macro is working correctly if I run it manually in Excel

推荐答案

这对我来说很好.只需更改宏的路径和名称即可.

This worked fine for me. Just change the path and the name of the Macro.

from __future__ import print_function
import unittest
import os.path
import win32com.client

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser('C:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Macro1')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()

这篇关于Python:使用Python运行Excel宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆