python-3.x - 无法使用 Python 执行 Excel 宏
问题描述
为什么我不能使用下面的脚本通过 Python 运行宏?任何建议,将不胜感激。
import xlwings as xw
wb= xw.Book('C:\\myfolder\\path\\myFileName.xlsm')
a = wb.macro("z_ColumnClear.Column_Clear")
解决方案
这个想法来自这个链接。 https://www.excelcise.org/running-excel-vba-from-python/
当脚本不起作用时,此链接提供了用户的几种方案。 无法运行宏...此工作簿中可能没有该宏
import os
import win32com.client as win32
def run_excel_macro (file_path_no_extention, VBA_macro_name, VBA_procedure_name):
"""
Execute an Excel macro
:param file_path: path to the Excel file holding the macro
:param VBA_module_name: VBA name
:param VBA_procedure_name: name in the sub routine
:param separator_char: the character used by the operating system to separate pathname components
:return: None
"""
xl = win32.Dispatch('Excel.Application')
xl.Application.visible = False
# os.sep is \
try:
wb = xl.Workbooks.Open(os.path.abspath(file_path_no_extention))
xl.Application.run("'" + file_path_no_extention.split(sep=os.sep)[-1] + "'" + "!" + VBA_macro_name + "." + VBA_procedure_name)
wb.Save()
wb.Close()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print(message)
xl.Application.Quit()
del xl
print("Completed: " + str(file_path_no_extention.split(sep=os.sep)[-1]))
推荐阅读
- openedge - 如何逃避更新消息?
- node.js - 防止在 MongoDB 查询中提供 _id 字段
- excel - VLookup 耗时太长 - 需要替代方案
- php - 尊重\验证与 slim4
- android - Android中的DialogFragment和AppCompatDialogFragment有什么区别?
- linux - Windows 主机下的 Docker 与 cifs 版本 1.0 和 2.0 的问题
- apache-kafka - RDBMS 数据上的 Kafka 事件生产者并在多个主题的情况下以与生产者相同的顺序在消费者处读取它
- magento2 - Windows 10 上的 Magento 2 安装问题
- r - R语言中从十六进制转换为Unicode
- google-apps-script - 激活用于编辑 Google 脚本的单元格