Saturday, 25 March 2017

"Interface marked as restricted" compile error prevents QueryInterface

In Com the method IUnknown.QueryInterface allows a client to hop between interfaces, this is callable via C++ but not VBA.  VBA has a different mechanism, one uses Dim itfFoo as IKung to declare the interface and then a call to Set itfFoo = objBar, where objBar is a Com object that implements the interface IKung.

However, this is also dependent of being able to write the Dim statement as such.  Not all interfaces play ball, they have types which cannot be represented in VBA and so the compiler chokes.  Following is an example.  When this happens you need to turn to C++.


Option Explicit
Option Private Module

Private Sub Test()


'**********************************************************************************
'* The following works and demonstrates a successful QueryInterface
'**********************************************************************************

    Dim obj As Object 'This is VBA way of asking of declaring IDispatch
    Set obj = VBA.CreateObject("Scripting.Dictionary")


    Dim itfUnk As stdole.IUnknown   'The canonical COM interface
    Set itfUnk = obj   '--- this does a QueryInterface , it asks for IUnknown

'**********************************************************************************
'* The following fails with compile errors, try uncommenting to see
'**********************************************************************************

    '* Compile error:
    '*
    '* Function or interface marked as restricted, or the function uses an
    '* Automation type not supported in Visual Basic


    'Dim itfDisp As stdole.IDispatch
    'Set itfDisp = obj

'******************************************************************************
    
    '* Compile error: User-defined type not defined
    '* Needs a Tools->Reference but where is IParseDisplayName defined?
    '* shame vba cannot declare interfaces by IID like C++
    
    'Dim itfUnk As IParseDisplayName
    'Set itfUnk = obj

'******************************************************************************

End Sub


No comments:

Post a Comment