1

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.

Pflugs
  • 772
  • 1
  • 10
  • 18

1 Answers1

1

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

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
  • 1
    _Save the file and import it in the VB editor (do not copy paste it use the import!)_: you first have to delete the class in the project - otherwise there will be a duplicate. Small hack: instead of importing you can also drag and drop the cls-file from the file explorer to the VBE project – Ike Jul 12 '22 at 07:05
  • @Ike Well yes, VBE will start numbering them if you do not delete the old one first as you cannot have 2 classes with the same name. – Pᴇʜ Jul 12 '22 at 07:12