如何将空的可选参数从 Python 传递给 Excel VBA 宏

How to pass an empty optional argument from Python to Excel VBA macro

我正在使用 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中我得到“运行-time error '94': Invalid use of Null

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

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"))

returns:

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