python写excel宏_Python - 运行Excel宏

1586010002-jmsa.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值