Thursday 6 September 2018

VBA - Types - The Object Browser

I intend to post about Types and Type Libraries etc. and low-level COM interfaces that facilitate their discovery, just like reflection. Before I do I need to cover the basics of Types using the tools that a VBA developer has to hand. The first of these is the VBA IDE's Object Browser.

The two screenshots of the object browser above should be familiar and they show two separately libraries, the VBA library on the left and the Microsoft Scripting Runtime library on the right. I prefer to work with the Microsoft Scripting Runtime for the examples in this series of posts.

Showing Hidden Members

It is a little known feature of the VBA IDE Object Browser that it will reveal some hidden members. The following screenshot shows the menu option selected for the Scripting library and its hidden members revealed.

Some elements are more hidden than others

I will give a sneak preview of some of the Interface Definition Language (IDL) that is used to define the Scripting type library. Below there are two methods, one highlighted in blue and the other in red. The method in red HashVal was displayed after we selected Show Hidden Members' from the menu. However, the method in blue, _NewEnum, remains hidden, that is because it is marked with the restricted attribute.


    interface IDictionary : IDispatch {
        ...
        [id(0xfffffffc), restricted]
        HRESULT _NewEnum([out, retval] IUnknown** ppunk);
        [id(0x0000000a), propget, hidden]
        HRESULT HashVal(
                        [in] VARIANT* Key, 
                        [out, retval] VARIANT* HashVal);
    };

If you are wondering what _NewEnum does then I can tell you it is what drives VBA's For Each statement. So you can see that sometimes it is necessary to restrict some methods from VBA developers. Here is some sample code that relies on the restricted _NewEnum method.

Option Explicit

Sub Test()

    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary
    
    dic.Add "Red", "FF0000"
    dic.Add "Green", "00FF00"
    dic.Add "Blue", "0000FF"

    Dim v As Variant
    For Each v In dic
        Debug.Print v, dic(v)
    Next v

End Sub

What's Next?

So I do not intend to show the Object Browser again as I have demonstrated how it does not tell the full story. Instead I will work with and only show OLEVIEW.exe which I will introduce in the next post.

No comments:

Post a Comment