0

我知道有一种方法可以像这样在 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)?

4

1 回答 1

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
于 2013-01-23T00:46:42.533 回答