【问题标题】:Couldn't execute Excel Macro using Python无法使用 Python 执行 Excel 宏
【发布时间】:2019-12-24 22:27:47
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.x


    【解决方案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]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-27
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      相关资源
      最近更新 更多