python - 使用未知数量的参数从 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:
- 成功 str_file 参数被传递为 = blablab
- 成功参数已通过 = 1 和 2
解决方案
推荐阅读
- javascript - 如何在反应中映射函数返回数组
- python - AttributeError:“顺序”对象没有属性“输出名称”。不是toco问题
- openvpn - Openvpn 客户端无法访问 openvpn 服务器可访问的子网
- jquery - 如何在循环期间设置超时?
- java - 使用 oauth2 的“PUT”请求
- prism - 在 Prism 7.2 中设置 SetDefaultViewModelFactory 的位置
- c++ - C++ 静态多态性——从基类指针引用派生类中重载的专用模板方法
- c++ - 为什么 valueType 的 std::any & operator= 不是有条件的 noexcept?
- android - 将 RecyclerView 显示到片段中
- c# - 是否有在 XAML 中指定多个相关命名空间的快捷方式?