【问题标题】:VBA Classes. Calling Methods with multiple parameters and static functionsVBA 类。调用具有多个参数和静态函数的方法
【发布时间】: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


【解决方案1】:

Example2 应该是:

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

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 2014-10-28
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多