Customize the Value displayed in the VBA Watch Window for Custom Classes

Viewed 21

I'm working in VBA (specifically, Microsoft Access VBA). I've written several custom VBA classes, and I'm using the VBE's Watch Window to see values during debugging. I'd like to create a function similar to ToString() in .NET languages that will print a custom string for the class to the Watch Window so I don't have to expand each child object. See the image below where I'd like to custom string to appear. enter image description here

I've tried adding a GET property called Value, and I've also tried a ToString function. Neither worked. Does anyone know whether this is possible? Note: I'm NOT trying to do this.

1 Answers

Create the following example class MyClass

Option Explicit

Property Get MyProperty() As String
    MyProperty = "Some String"
End Property

Export it as MyClass.cls and open it in notepad. It looks like:

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "MyClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Property Get MyProperty() As String
    MyProperty = "Some String"
End Property

Add the line Attribute Value.VB_UserMemId = 0 to MyProperty() to make this property the default property.

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "MyClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Property Get MyProperty() As String
    Attribute Value.VB_UserMemId = 0
    MyProperty = "Some String"
End Property

Save the file and import it in the VB editor (do not copy paste it use the import!).

The line Attribute Value.VB_UserMemId = 0 will not be visible in your VBE. But if you now create a new instance of the class you can call the class itself to access the default property:

Option Explicit

Public Sub Example()
    Dim cl As MyClass
    Set cl = New MyClass
    
    Debug.Print cl  ' this returns the default property now
    Stop
End Sub

And it will also show in the Watch Window (but it will sadly not show the value in the Local Window.

enter image description here

Related