(Solved) – Interface implementing multiple interfaces in VBA

(solved)-–-interface-implementing-multiple-interfaces-in-vba

I would like to create an Interface that implements multiple interfaces, and then make a class that implements that interface. For example:

IFlyable module:

Public Sub Fly()
End Sub

Public Function GetAltitude() As Long
End Function

ISwimmable module:

Public Sub Swim()
End Sub

Public Function GetDepth() As Long
End Function

IFlySwim module:

Implements IFlyable
Implements ISwimmable

Public Sub IFlyable_Fly()
End Sub

Public Function IFlyable_GetAltitude() As Long
End Function    

Public Sub ISwimmable_Swim()
End Sub

Public Function ISwimmable_GetDepth() As Long
End Function

This all compiles just fine. But if I declare an Object of type IFlySwim, the predictive text in VBA gives me:

IFlyable_Fly, IFlyable_GetAltitude, ISwimmable_Swim

And trying to create a Class that implements IFlySwimmable just doesn’t work.

Class Duck:

Implements IFlySwim

Public Sub IFlySwim_IFlyable_Fly()
    Debug.Print "Flying with wings!"
End Sub

Public Function IFlySwim_IFlyable_GetAltitude() As Long
    IFlySwim_IFlyable_GetAltitude = 30
End Function

Public Sub IFlySwim_ISwimmable_Swim()
    Debug.Print "Swimming with feet!"
End Sub

Public Function IFlySwim_ISwimmable_GetDepth() As Long
    IFlySwim_ISwimmable_GetDepth = 20
End Function

Pressing the compile button gives me the error:
“Compile error: Object module needs to implement ‘IFlyable_Fly’ for interface ‘IFlySwim’.

So this leads me to believe that Implementing an interface within another interface Doesn’t Work. Or at least, it doesn’t make sense from VBA’s point of view. Which is understandable, because I’m not actually providing an implementation for IFlyable and ISwimmable in IFlySwim. What I really want to do is defer implementation for IFlyable and ISwimmable to a class that implements both of them.

So now, if my Duck class is:

Implements IFlyable
Implements ISwimmable

Public Sub IFlyable_Fly()
    Debug.Print "Flying with wings!"
End Sub

Public Function IFlyable_GetAltitude() As Long
    IFlySwim_IFlyable_GetAltitude = 30
End Function

Public Sub ISwimmable_Swim()
    Debug.Print "Swimming with feet!"
End Sub

Public Function ISwimmable_GetDepth() As Long
    IFlySwim_ISwimmable_GetDepth = 20
End Function

Then when I go to use it, the predictive dropdown gives me:

Duck usage

I could cast Duck to either the IFlyable or ISwimmable to use as such:

Duck usage 2

But what if I wanted to create a Function or Sub that accepts a Flyable/Swimmable? Do I have to create a completely separate interface called IFlySwim that contains all of the Sub/Functions from IFlyable and ISwimmable, and then modify my Duck class to only implement from the IFlySwim ?

Leave a Reply

Your email address will not be published. Required fields are marked *