Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

vba - How to get property values of classes that implement an interface in the Locals window?

This is really bothering me and hindering my development/debugging. Whenever I declare a variable type of the interface I'm implementing, the Locals Window doesn't show it's property values. Instead it just reads

Object doesn't support this property or method

Which is silly, because it absolutely does. In fact it has to in order to fulfill its contract with the Interface.

If I declare the variable as the concrete implementation of the interface, the window works as expected. However, that completely defeats the purpose of coding to the abstraction to begin with.

How can I get the locals window to properly display the class' property values?

Minimal, Complete, and Verifiable Example:

Create an IClass class to use as an interface.

Option Explicit

Public Property Get Name() As String
End Property

Create a Class1 that implements the interface.

Option Explicit

Implements IClass

Public Property Get Name() As String
    Name = "Class1"
End Property

Private Property Get IClass_Name() As String
    IClass_Name = Name
End Property

And lastly, some test code in a regular .bas module to illustrate the issue.

Option Explicit

Public Sub test()
    Dim x As Class1
    Dim y As IClass

    Set x = New Class1
    Debug.Print x.Name

    Set y = New Class1
    Debug.Print y.Name

    Stop
End Sub

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I could be wrong, but I think this may be something to do with the way classes are instantiated in VBA.

For example:

Dim oClass1 as Class1
Set oClass1 = new Class1

Is different than

Dim oClass1 as New Class1

In the second case I believe the constructor doesn't get called until the property is accessed.

If you try this, it is sees the property in the Watch window. Notice the New for the IClass - just for Demonstration - I know its not the way to do that :)

Public Sub test1()

    Dim x As Class1
    Dim y As IClass

    Set y = New IClass
    Set x = New Class1
    Debug.Print x.Name
    Debug.Print y.Name
    Stop

End Sub

I suspect its something to do with that and the watch window requires this ... maybe...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...