首页 > 解决方案 > 使用未知数量的参数从 python 调用 vba 宏

问题描述

目标是拥有一个可重用的 python 函数,该函数使用 win32.com 调用来自 VBA Excel 的宏,并使用**kwargs, 或其他可以传递未知数量参数的方法来执行此操作。

没有使用具体的问题**kwargs和明确的 win32.com,尽管发现了一些相似的问题,但没有人接受答案,即使不完全相似。
以下是一些相似但不相似的问题:

使用蟒蛇

def run_vba_macro(str_path, str_modulename, str_macroname, **kwargs):
    if os.path.exists(str_path):
        xl=win32com.client.DispatchEx("Excel.Application")
        wb=xl.Workbooks.Open(str_path, ReadOnly=0)
        xl.Visible = True
        if kwargs:
                xl.Application.Run(os.path.basename(str_path)+"!"+str_modulename+'.'+str_macroname,
                                          **kwargs)
        else:
              xl.Application.Run(os.path.basename(str_path)
                                          +"!"+str_modulename
                                          +'.'+str_macroname)
        wb.Close(SaveChanges=0)
        xl.Application.Quit()
        del xl

#example
kwargs={'str_file':r'blablab'}
run_vba_macro(r'D:\arch_v14.xlsm',
              str_modulename="Module1",
              str_macroname='macro1',
              **kwargs)
#other example
kwargs={'arg1':1,'arg2':2}
run_vba_macro(r'D:\arch_v14.xlsm',
              str_modulename="Module1",
              str_macroname='macro_other',
              **kwargs)

使用 VBA

Sub macro1(ParamArray args() as Variant)
    MsgBox("success the str_file argument was passed as =" & args(0))
End Sub

Sub macro_other(ParamArray args() as Variant)
    MsgBox("success the arguments have passed as =" & str(args(0)) & " and " & str(args(1)))
End Sub

预期结果是 VBA 中的 MessageBox:

标签: pythonexcelvba

解决方案


在 python 中,kwargs是 a dict,所以它不是可以通过 COM 传递的东西。kwargs.values作为*args数组传递,如下所示:

params_for_excel = list(kwargs.values())

xl.Application.Run(os.path.basename(str_path)+"!"+str_modulename+'.'+str_macroname,
                                      *params_for_excel)

在此处输入图像描述


推荐阅读