我正在使用Python來測驗一個Excel VBA宏。該宏有兩個可選引數。只要只有最后一個或兩個引數應該被省略,我就沒有問題。我只是傳遞前面的引數。我不知道如何處理第一個可選引數被省略,但第二個引數被包含的情況。我不能使用 None,因為它被 Excel 解釋為 "Null",這是一種不同的情況。我也不能省略這個引數,因為我在 Python 中得到了一個語法錯誤。
在使用 win32com 運行 Excel 宏時,我如何省略一個可選的引數,而不是最后一個?
最小化的例子:
考慮這個宏:Function getarg(Optional anArg, Optional anotherArg) As String
Dim sAs String
If IsMissing(anArg) Then
s = "沒有通過引數1! "
Else
s = "引數1是。" CStr(anArg) " 。"/span>
End If
If IsMissing(otherArg) Then
s = s "沒有傳遞引數2!"。
Else
s = s "引數2是。" CStr(otherArg)
End If
getarg = s
結束 功能
這是我的Python代碼:
import win32com.client as win32
from os.path import join
xl = win32.Dispatch("Excel.Application"/span>)
wb = xl.Workbooks.Open(r "C:Users...whatever.xlsm")
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name)), "'{}'! Name), "reportbuilder", "getarg"), "A"/span>, "B"/span>)
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "A")。 Path,wb.Name), "reportbuilder", "getarg"), "A" )
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "getarg") Path,wb.Name), "reportbuilder", "getarg"))
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name)), "'{}'! Name), "reportbuilder", "getarg"), None, "B")
輸出結果是:
Argument 1 was: A. 論據2是: B。
論點1是: A。 No argument 2 passed!
No argument 1 passed! No argument 2 passed!
第四種情況沒有輸出,因為在Excel中我得到 "運行時錯誤'94'。無效使用 Null"
uj5u.com熱心網友回復:
一個空的串列可以完成這個作業:
import win32com.client as win32
from os.path import join
xl = win32.Dispatch("Excel.Application"/span>)
wb = xl.Workbooks.Open(r "C:a.xlsm")
print(xl.Run("'{}'! {}.{}".format(join(wb.Path,wb. Name), "Module1", "getarg"), "A"/span>, "B"/span>)
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "A")。 Path,wb.Name), "Module1", "getarg"), "A")
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name), "getarg") Path,wb.Name), "Module1", "getarg"))
print(xl.Run("'{}'!{}.{}".format(join(wb.Path,wb.Name)), . Path,wb.Name), "Module1", "getarg"), [] , "B")
回傳:
Argument 1 was: A. 論據2是: B。
論點1是: A。 No argument 2 passed!
No argument 1 passed! No argument 2 passed!
No argument 1 passed! Argument 2 was: B
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307761.html
標籤:
