在vba中传递类变量

时间:2013-01-23 00:19:54

标签: class variables excel-vba global-variables vba

我知道有一种方法可以在vb.net中传递类变量:

模块模块1

Sub Main()

    ' Declare an instance of the class and assign a value to its field. 
    ***Dim c1 As Class1 = New Class1()***
    c1.Field = 5
    Console.WriteLine(c1.Field)
    ' Output: 5 

    ' ByVal does not prevent changing the value of a field or property.
    ChangeFieldValue(***c1***)
    Console.WriteLine(***c1.Field***)
    ' Output: 500 

    ' ByVal does prevent changing the value of c1 itself. 
    ChangeClassReference(c1)
    Console.WriteLine(c1.Field)
    ' Output: 500

    Console.ReadKey()
End Sub 

Public Sub ChangeFieldValue(***ByVal cls As Class1***)
    cls.Field = 500
End Sub 

Public Sub ChangeClassReference(***ByVal cls As Class1***)
    cls = New Class1()
    cls.Field = 1000
End Sub 

Public Class Class1
    Public Field As Integer 
End Class 

结束模块

但是,当我尝试在vba中模拟相同的过程时,它不起作用。 是否有可能在vba中做(对于Excel)?

1 个答案:

答案 0 :(得分:0)

请尝试以下操作。

Sub Main()

    Dim c1 As New Class1
    c1.Field = 5
    Debug.Print c1.Field

    changeFieldValue c1
    Debug.Print c1.Field

    changeClassReference c1
    Debug.Print c1.Field

End Sub

Public Sub changeClassReference(cls As Class1)

    Set cls = New Class1
    cls.Field = 1000

End Sub

Public Sub changeFieldValue(cls As Class1)

    cls.Field = 500

End Sub

您需要使用以下代码添加新的类模块:

Public Field As Long