Overloading Properties
I tried to overload in VBA within a class module:
Dim a As Integer
Public Property Let SomeNumber(newNumber as Integer)
a = newNumber
End Property
Public Property Let SomeNumber(newNumber as String)
a = Val(newNumber)
End Property
Public Property Get SomeNumber() As Integer
SomeNumber = a
End Property
The compiler complains that an "ambiguous name was detected" where clearly there is a different signature. Is it possible to overload a property defined within a class in VBA or VB6? If so, what would be the syntax?
Moreover, if property overloading is not possible, what benefits do properties offer over get/set methods defined by public functions other than a more seamless way t开发者_JS百科o access the fields of an instantiated object?
Can you use a variant or object type and manually handle the type checking?
A mixture of Optional parameters may also be possible, but it's not exactly equivalent to overloading either.
No.
The workaround is to use Variants, which allows the client to pass anything. But you have to write code to do the type-checking at runtime:
Public Property Let SomeNumber(newNumber as Variant)
Select Case VarType(newNumber)
Case vbInteger '' Caller passed an integer
a = newNumber
Case vbString '' Caller passed a string
a = Val(newNumber)
Case Else
Err.Raise vbObjectError+513, , "Invalid type passed"
End Select
End Property
Public Property Get SomeNumber() As Variant
SomeNumber = a
End Property
For more details see Dan Appleman's excellent book Developing COM/ActiveX Components In Visual Basic 6.
From what I can see here:
http://vbcity.com/forums/t/76453.aspx
It seems you are out of luck until you convert to VB.NET.
There was a thread on this topic:
Function Overloading and UDF in Excel VBA
精彩评论