Python - run Excel macro

╄→尐↘猪︶ㄣ 提交于 2019-12-29 01:05:12

问题


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")



回答2:


Try savin the macro to your "Normal" Project and call.

excel.Application.Run("Normal.ModuleName.SubName")

You can even add the Module to the Normal profile programmatically, but Office doesn't let you do it if you have insufficient access rights.



来源:https://stackoverflow.com/questions/11023990/python-run-excel-macro

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