Pat*_*ick 28 excel vba excel-vba user-defined-functions
我正在使用Excel VBA来编写UDF.我想用几个不同的版本重载我自己的UDF,以便不同的参数将调用不同的函数.
由于VBA似乎不支持这一点,任何人都可以建议一种实现同一目标的良好,非凌乱的方式吗?我应该使用可选参数还是有更好的方法?
Joe*_*sky 51
将您的参数声明为Optional Variants,然后您可以测试它们是否缺少使用IsMissing()或检查其类型TypeName(),如以下示例所示:
Public Function Foo(Optional v As Variant) As Variant
If IsMissing(v) Then
Foo = "Missing argument"
ElseIf TypeName(v) = "String" Then
Foo = v & " plus one"
Else
Foo = v + 1
End If
End Function
Run Code Online (Sandbox Code Playgroud)
这可以从工作表中调用为= FOO(),= FOO(数字)或= FOO(" 字符串 ").
如果你可以通过参数计数来区分,那么像这样的东西可以工作:
Public Function Morph(ParamArray Args())
Select Case UBound(Args)
Case -1 '' nothing supplied
Morph = Morph_NoParams()
Case 0
Morph = Morph_One_Param(Args(0))
Case 1
Morph = Two_Param_Morph(Args(0), Args(1))
Case Else
Morph = CVErr(xlErrRef)
End Select
End Function
Private Function Morph_NoParams()
Morph_NoParams = "I'm parameterless"
End Function
Private Function Morph_One_Param(arg)
Morph_One_Param = "I has a parameter, it's " & arg
End Function
Private Function Two_Param_Morph(arg0, arg1)
Two_Param_Morph = "I is in 2-params and they is " & arg0 & "," & arg1
End Function
Run Code Online (Sandbox Code Playgroud)
如果区分函数的唯一方法是按类型划分,那么你实际上必须要做C++和其他被覆盖函数的语言,即通过签名调用.我建议打电话看起来像这样:
Public Function MorphBySig(ParamArray args())
Dim sig As String
Dim idx As Long
Dim MorphInstance As MorphClass
For idx = LBound(args) To UBound(args)
sig = sig & TypeName(args(idx))
Next
Set MorphInstance = New MorphClass
MorphBySig = CallByName(MorphInstance, "Morph_" & sig, VbMethod, args)
End Function
Run Code Online (Sandbox Code Playgroud)
并创建一个具有许多方法的类,这些方法与您期望的签名相匹配.您可能需要进行一些错误处理,并警告可识别的类型是有限的:例如,日期是TypeName Double.