【发布时间】:2014-09-20 18:52:08
【问题描述】:
以下是类模块中的示例类
Private mKey As String
Private mValue As String
'CREATE INSTANCE
Public Static Function CreateInstance(Key As String, Value As String) As ExampleClass
Dim obj As New ExampleClass
obj.InitialiseKey (Key)
obj.InitialiseValue (Value)
Set CreateInstance = obj
End Function
'INITIALISE
Public Sub InitialiseKey(Key As String)
mKey = Key
End Sub
Public Sub InitialiseValue(Value As String)
mValue = Value
End Sub
Public Sub InitialiseKVP(Key As String, Value As String)
mKey = Key
mValue = Value
End Sub
'GETTER
Public Property Get Value() As String
Value = mValue
End Property
Public Property Get Key() As String
Key = mKey
End Property
下面的代码在一个普通的模块中
Sub Example_1()
Dim A As New ExampleClass
A.InitialiseKey ("Key 1")
A.InitialiseValue ("Value 1")
Debug.Print A.Key
Debug.Print A.Value
End Sub
Sub Example_2()
Dim A As New ExampleClass
'A.InitialiseKVP ("Key 2", "Value 2") 'DOES NOT COMPILE, EXPECTS '=' FOR SOME REASON
Debug.Print A.Key
Debug.Print A.Value
End Sub
Sub Example_3()
Dim A As ExampleClass
Set A = ExampleClass.CreateInstance("Key 3", "Value 3") 'RUNTIME ERROR 424, no object
Debug.Print A.Key
Debug.Print A.Value
End Sub
'Example_1' 有效,'Example_3' 是我想写的。 'Example_2' 本来是中间的,但甚至不能编译。
stackoverflow 上有一个答案 (Class (Static) Methods in VBA) 基本上说明无法调用方法。这对我来说似乎很奇怪,因为“Example_1”调用了一个方法,而“Example_3”编译没有错误。
如何让“Example_2”编译? 如何让“Example_3”工作?
【问题讨论】:
-
在示例 2 中只需执行
A.InitialiseKVP "Key 2", "Value 2",在示例 3 中执行此操作Dim A As New ExampleClass,然后执行Set A = A.CreateInstance("Key 3", "Value 3")。您总是需要在 VBA 中初始化一个类的实例来调用任何成员。 VBA 中没有静态类这样的概念。 -
另外,您可能对THIS ANSWER感兴趣
标签: vba class methods static-methods