gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:02:05 27 4
gpt4 key购买 nike

我正在使用 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':无效使用 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"))
返回:
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

关于python - 如何将空的可选参数从 Python 传递到 Excel VBA 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69177745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com