区分 class 成员和 VBA 中同名的参数?

Distinguish between class members and arguments with same name in VBA?

有没有办法区分 class 成员和 VBA 中同名的 property/sub/function 参数?例如:

第 1 类:

Private Name As String

Property Let LastName(Name As String)
   this.Name = Name
End Property

Property Get LastName() As String
    Dim Name As String
    Name = "Mr. "
    LastName = Name & this.Name
End Property

在其他语言中,您可以使用关键字 this 来引用 class/instance(?) 成员。但是在VBA中是怎么解决的呢?我知道你可以使用不同的名字。但这不是我想要的。

感谢您的帮助!

在 VBA 中,代替 this. 使用的关键字是 Me. 但是,如果 class 中引用的变量是私有的(我是不知道为什么)。一种可能的解决方法是将其更改为 public.

''''  Class1
Private PrName As String
Public PbName As String

Property Let LastName(Name As String)
   Me.PrName = Name ' throws a compile error
   Me.PbName = Name ' OK
End Property

更新: 您还可以创建额外的包装函数/属性层 - set_namegetNameName 变量不需要重命名或更改范围。原始属性的输入参数也保持不变。

Private Name As String

Property Let LastName(Name As String)
   Call set_name(Name) ' throws a compile error
End Property

Private Sub set_name(new_name As String)
    ' wrapper
    Name = new_name
End Sub

Property Get getName() As String
    ' wrapper
    getName = Name
End Property

Property Get LastName() As String
    Dim Name As String
    Name = "Mr. "
    LastName = Name & Me.getName
End Property

您可以使用 Mathieu 在 private-this-as-tsomething

中教我们的类型创建 This

只需使用 vars 创建一个 Type 并将其分配给 This。

Private Type TPerson
  Name As String
End Type

Private This As TPerson
Property Let LastName(Name As String)
   This.Name = Name
End Property

Property Get LastName() As String
    Dim Name As String
    Name = "Mr. "
    LastName = Name & This.Name
End Property

不要忘记阅读 RubberDuckVBA 上的其他文章,因为它们提供了许多关于 VBA-OOP 的深刻见解。