将宏调用到不同的工作簿 python

Calling a macro to a different workbook python

所以我试图让 Python + Excel 自动化一些我需要为报告做的事情,让我的生活更轻松一些。我创建了一个专用于宏的 Excel 工作簿(启用宏)。例如,当我按下 ctrl+R 时,它会删除我不想用于报告的任何空格和括号。我的问题是如何打开宏工作簿,然后打开我需要的其他报告并使用宏。

这是我当前的代码:

import xlwings as xw
wb = xw.books.open(r'macrofile.xlsb', r'reportthatneedswork.csv')
macroname = wb.macro('MacroName')
macroname()

只打开宏工作簿,不打开其他工作簿,什么都不做。

如果您打算经常使用它,我会重写 python+xlwings 中的宏代码。这消除了 运行ning 其他工作簿的问题,并且只需添加循环逻辑就可以让你一次 运行 它在多个文件上:

macro.py

import os
import sys
import xlwings as xw
from os import listdir
from os.path import isfile, join

def python_macro(wb_path, app):
    #Optionally verify that files are all xls*, csv, or directory files

    wb = app.books.open(wb_path)
    sheet = wb.sheets.active
    
    #Rewrite macro in python+xlwings below
    print(sheet.range('A1').value)


with xw.App() as app:    
    for arg in sys.argv[1:]:
        path = join(os.getcwd(), arg)
            
        if os.path.isdir(path):
            #Optionally process further subdirectories
                
            files = [f for f in listdir(path) if isfile(join(path, f))]

            for file in files:
                python_macro(file, app)

        elif os.path.isfile(path):
            python_macro(path, app)


将文件保存在与报告文件相同的目录中,运行它将如下所示:

python macro.py reportthatneedswork.csv anotherreport.csv report-sub-dir


据我所知,确实没有办法用 xlwings 执行外部工作簿宏。我发现最接近的是使用 win32com 提取并移动 vb 脚本,然后您可以使用 xlwing 打开它并使用 运行 宏。 但是,这对您的场景来说特别过分。 python.

中的宏直接改写就好办多了

Read VBA from workbook and then 'inject' it into another sheet.