You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python合并含VBA与公式的xlsm文件并保留工作表结构

合并带宏、公式的XLSM文件(完整保留结构与内容)

实现方案

直接调用本地Excel实例进行操作,利用Excel原生功能复制工作表和VBA组件,确保所有元素完整保留。纯Python库(如openpyxl)对xlsm的宏支持有限,无法满足需求,win32com.client是最可靠的选择。

步骤

1. 安装依赖

先安装pywin32库:

pip install pywin32

2. 完整代码

import win32com.client as win32
import os

def merge_xlsm_files(input_folder, output_file):
    # 启动Excel后台进程
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    excel.DisplayAlerts = False

    try:
        # 创建空的合并工作簿,删除默认工作表
        merged_wb = excel.Workbooks.Add()
        for sheet in merged_wb.Sheets:
            sheet.Delete()

        # 遍历所有xlsm文件
        for filename in os.listdir(input_folder):
            if not filename.endswith('.xlsm') or filename == os.path.basename(output_file):
                continue
            
            source_path = os.path.join(input_folder, filename)
            source_wb = excel.Workbooks.Open(source_path)

            # 复制所有工作表到合并文件
            for sheet in source_wb.Sheets:
                sheet.Copy(After=merged_wb.Sheets(merged_wb.Sheets.Count))

            # 复制VBA模块(需开启VBA项目访问权限)
            for vb_comp in source_wb.VBProject.VBComponents:
                try:
                    merged_wb.VBProject.VBComponents.Import(vb_comp.Name)
                except Exception as e:
                    print(f"跳过VBA模块 {vb_comp.Name}: {str(e)}")

            source_wb.Close(SaveChanges=False)

        # 保存为xlsm格式(52是xlsm的文件格式代码)
        merged_wb.SaveAs(output_file, FileFormat=52)
        print(f"合并完成:{output_file}")

    except Exception as e:
        print(f"合并失败:{str(e)}")

    finally:
        merged_wb.Close(SaveChanges=False)
        excel.Quit()

# 替换为你的路径
if __name__ == "__main__":
    INPUT_DIR = r"C:\Path\To\Your\XLSMs"
    OUTPUT_FILE = r"C:\Path\To\Save\Merged.xlsm"
    merge_xlsm_files(INPUT_DIR, OUTPUT_FILE)

注意事项

  • 必须安装本地Excel客户端,且启用宏功能。
  • 需要在Excel设置中开启信任对VBA项目对象模型的访问(路径:Excel选项→信任中心→信任中心设置→宏设置),否则无法复制VBA代码。
  • 如果多个源文件有同名VBA模块,代码会跳过重复项,你可以修改异常处理逻辑来重命名模块或覆盖。
  • DisplayAlerts = False是为了避免Excel弹出提示框(比如覆盖文件确认),如果需要看到提示可以注释掉。

内容的提问来源于stack exchange,提问作者VonKTS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:45:30