VBA Classes / Objects

Despite being an experienced VBA programmer, this is my first time creating my own classes (objects). I'm surprised to see that all properties are "duplicated" in the Locales window. Small example (break in "End Sub"):

' Class module:
Private pName As String

Public Property Let Name(inValue As String)
    pName = inValue
End Property
Public Property Get Name() As String
    Name = pName
End Property

' Normal module:
Sub Test()
    Dim objTest As cTest
    Set objTest = New cTest
    objTest.Name = "John Doe"
End Sub

      

Why are both name and pName displayed in the locale window? Can I get rid of the pName somehow?

Regards Helge

+3


source to share


2 answers


As comments and answers, it has already been said that it is only useful to use VBE.

However, if you find it noisy to have private fields and public members listed in the locals toolwindow, there is a way to clean it up nicely - here I put the procedure Test

inside ThisWorkbook

and left the class named Class1

:

clean locals toolwindow

So what's going on here? What this

?

Here Class1

:



Option Explicit

Private Type TClass1
    Name As String
    '...other members...
End Type

Private this As TClass1

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

      

The class has only 1 private field, a user-defined value of a named type this

that contains all of the encapsulated data items.

As a result, the underlying fields are effectively hidden, or rather, they are all rearranged underneath this

, so you won't see the values ​​of the underlying field if you don't want to see them:

locals toolwindow, 'this' field expanded

And as an added benefit, you don't need any pseudo-Hungarian prefixes anymore, the implementations from properties are crystal clear, and the best of all properties have the exact same identifier name as their field stems.

+9


source


All inspection windows not only display the public interface of objects for you, but also their private members. AFAIK there is nothing you can do about it.

Consider this a nice feature to get even more information while debugging.



In my experience, this is less of a problem in real world objects as they have more fields and properties. Assuming consistent naming (as your example shows), fields and properties are well grouped together.

+6


source







All Articles