【问题标题】:Calling a macro to a different workbook python将宏调用到不同的工作簿python
【发布时间】:2021-12-04 21:23:41
【问题描述】:

所以我试图通过让 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 excel xlwings


【解决方案1】:

如果你打算经常使用这个,我会用 python+xlwings 重写宏代码。这消除了从其他工作簿运行事物的问题,并允许您通过添加循环逻辑一次在多个文件上运行它:

宏.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 然后'inject' it into another sheet。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2023-03-26
    • 1970-01-01
    • 2022-01-22
    • 2015-05-01
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多