VBA课程。使用多个参数和静态函数调用方法

时间:2014-07-29 11:52:34

标签: vba class methods static-methods

以下是类模块

中的示例类
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'起作用?

1 个答案:

答案 0 :(得分:2)

示例2应为:

Sub Example_2()
    Dim A As New ExampleClass
    Call A.InitialiseKVP("Key 2", "Value 2")
    Debug.Print A.Key
    Debug.Print A.Value
End Sub

使用Call关键字,或A.InitialiseKVP "Key 2", "Value 2"

正如@mehow指出的那样,你需要首先实现类,不能像对象或常规模块那样访问类:

Sub Example_3()
    Dim A As New ExampleClass
    Set A = A.CreateInstance("Key 3", "Value 3")
    Debug.Print A.Key
    Debug.Print A.Value
End Sub

但这没有多大意义,你应该使用常规函数进行实例化:

Sub Example_3()
    Dim A As ExampleClass
    Set A = CreateInstance("Key 3", "Value 3") 'RUNTIME ERROR 424, no object
    Debug.Print A.Key
    Debug.Print A.Value
End Sub


Public 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