![](/img/trans.png)
[英]generic function in python - calling a method with unknown number of arguments
[英]Calling vba macro from python with unknown number of arguments
The goal is to have a reusable python function which calls using win32.com a macro from VBA Excel, and do so using **kwargs
, or other method that can pass unknown number of arguments.
没有使用**kwargs
和显式 win32.com 的具体问题,尽管发现了一些类似的问题,但没有一个问题被接受,即使不完全相似。
以下是一些相似但不相似的问题:
使用 python
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:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.