无法使用Python执行Excel宏

时间:2019-12-20 20:03:58

标签: python-3.x

为什么我不能使用下面的脚本通过Python运行宏?任何建议,将不胜感激。

import xlwings as xw
wb= xw.Book('C:\\myfolder\\path\\myFileName.xlsm')
a = wb.macro("z_ColumnClear.Column_Clear")

enter image description here

1 个答案:

答案 0 :(得分:1)

这个想法来自这个链接。 https://www.excelcise.org/running-excel-vba-from-python/

,当脚本不起作用时,此链接为用户提供了几种方案。 Cannot run the macro... the macro may not be available in this workbook

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