【问题标题】:How to pass an empty optional argument from Python to Excel VBA macro如何将空的可选参数从 Python 传递到 Excel VBA 宏
【发布时间】:2021-09-14 20:55:35
【问题描述】:

我正在使用 Python 测试 Excel VBA 宏。该宏有两个可选参数。只要只省略最后一个或两个参数就可以了。我只是传递了前面的参数。我不知道如何处理要省略第一个可选参数但包含第二个的情况。我不能使用 None,因为 Excel 将其解释为“Null”,这是另一种情况。我也不能省略参数,因为我在 Python 中遇到语法错误。

如何在使用 win32com 运行 Excel 宏时省略一个可选参数,它不是最后一个参数?

最小示例:

考虑这个宏:

Function getarg(Optional anArg, Optional anotherArg) As String
    Dim s As String
    
    If IsMissing(anArg) Then
        s = "No argument 1 passed! "
    Else
        s = "Argument 1 was: " + CStr(anArg) + ". "
    End If
    
    If IsMissing(anotherArg) Then
        s = s + "No argument 2 passed!"
    Else
        s = s + "Argument 2 was: " + CStr(anotherArg)
    End If
    getarg = s
End Function

这是我的 Python 代码:

import win32com.client as win32

from os.path import join

xl = win32.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(r"C:\Users\...\whatever.xlsm")

print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "reportbuilder", "getarg"), "A", "B"))
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "reportbuilder", "getarg"), "A"))
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "reportbuilder", "getarg")))
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "reportbuilder", "getarg"), None, "B"))

输出是:

Argument 1 was: A. Argument 2 was: B
Argument 1 was: A. No argument 2 passed!
No argument 1 passed! No argument 2 passed!

第四种情况没有输出,因为在 Excel 中我得到“运行时错误 '94': Invalid use of Null”

【问题讨论】:

    标签: python excel vba pywin32 win32com


    【解决方案1】:

    一个空列表就可以完成这项工作:

    import win32com.client as win32
    
    from os.path import join
    
    xl = win32.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(r"C:\a\b.xlsm")
    
    print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "Module1", "getarg"), "A", "B"))
    print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "Module1", "getarg"), "A"))
    print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "Module1", "getarg")))
    print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "Module1", "getarg"), [], "B"))
    

    返回:

    Argument 1 was: A. Argument 2 was: B
    Argument 1 was: A. No argument 2 passed!
    No argument 1 passed! No argument 2 passed!
    No argument 1 passed! Argument 2 was: B
    

    【讨论】:

    • @BigBen - 实际上认为它应该适用于任何空类,但只是尝试使用空字典,但它没有,所以我猜list() 是。或tuple()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多