Python - run Excel macro

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.

Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.

Here's my code:

import win32com.client import os import xl  excel = win32com.client.Dispatch("Excel.Application")  macrowb = xl.Workbook('C:\MacroBook.xlsm') wb1 = xl.Workbook('C:\Database.csv') excel.Run("FilterLoans") 

I get an error, "pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)"

The error states that FilterLoans is not available in the Database.csv file...how can I import it?

回答1:

1) you can't have VBA on a *.csv file. You need the *.xlsm file to be the active workbook. I don't think you need to open the *.csv file at all if your macro know how to find it.

2) Enable VBA module access in your Office Excel:

File options Trust Center Trust Center Settings Macro Settings Enable VBA access 

3)I am using this function to run macros:

excel.Application.Run("FilterLoans") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!