vba Python - 运行 Excel 宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11023990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - run Excel macro
提问by user1137778
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
我想使用 Python 在 Data.csv 的工作表上运行 MacroBook.xlsm 中包含的宏。
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.
通常在 excel 中,我打开两个文件并将焦点转移到 Data.csv 文件并从 MacroBook 运行宏。python 脚本每天下载 Data.csv 文件,所以我不能把宏放在那个文件中。
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)
pywintypes.com_error: (-2147352567, '发生异常。', (0, u'Microsoft Excel', u"无法运行宏 'FilterLoans'。宏在此工作簿中可能不可用,或者所有宏都可能被禁用。" , u'xlmain11.chm', 0, -2146827284), 无)
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
错误指出,FilterLoans 在 Database.csv 文件中不可用...我该如何导入它?
回答by Ran S
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.
1) 你不能在 *.csv 文件上使用 VBA。您需要将 *.xlsm 文件作为活动工作簿。如果您的宏知道如何找到它,我认为您根本不需要打开 *.csv 文件。
2) Enable VBA module access in your Office Excel:
2) 在您的 Office Excel 中启用 VBA 模块访问:
File
options
Trust Center
Trust Center Settings
Macro Settings
Enable VBA access
3)I am using this function to run macros:
3)我使用这个函数来运行宏:
excel.Application.Run("FilterLoans")
回答by tst
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.
您甚至可以以编程方式将模块添加到 Normal 配置文件,但如果您没有足够的访问权限,Office 不允许您这样做。