Inheritance for VBA code in MS Access

inheritance, vba

Solution

No. They are not derived from the `Control` class. They implement `Control`'s definition/ methods and properties signatures. The way `TypeOf` and `Is` operators work it's they check whether the instance of a class Implements one of 3 categories (listed below).

open a new workbook

Go to VBE and add

a class module and name it: `MyClass`

in the code view only add `Implements MyInterface`

a class module and name it: `MyInterface`

in the code view - do nothing/leave empty

a module and copy paste the below code and run it

Sub Main()

    Dim cls As MyClass
    Set cls = New MyClass

    Debug.Print TypeOf cls Is MyClass
    Debug.Print TypeOf cls Is MyInterface

End Sub

The result may be surprising

True
True

`cls` variable is of two types - `MyClass` and `MyInterface`

as you can see `cls` doesn't inherit nothing from `MyInterface` but definition. When using `TypeOf` and `Is` it actually shows true because `MyClass` implements `MyInterface`. Not because it's derived from the `MyInterface` class but because it implements it.

Now, suppose

result = TypeOf objectexpression Is typename

The `TypeOf` operator determines whether the run-time type of variable is compatible with typename. The compatibility depends on the type category of typename. There are three categories

Class objectexpression is of type typename or inherits from typename

Structure objectexpression is of type typename

Interface objectexpression implements typename or inherits from a class that implements typename

Specifically try to understand the 3rd category - Interface.

I think at this point you should really understand why `TypeOf varName Is varType` shows `True` for the `TextBox` and `ListBox`...

When you do VBA inheritance, you can only use Implements keyword to implements a class definition. That is, the class to be implemented is equivalent to C++/C#'s abstract class: only having property/method definition.

Generally, your example isn't a form of a class polymorphism. Class polymorphism occurs when you are actually deriving an instance of one to class to another. This isn't the case. Even though `TextBox` and `ListBox` are both of a `Control` type they aren't actually derived from `Control` class. Note: they may as well be members of another collection - they would be `TypeOf` the higher in the object hierarchy type ( forms, also Component and IComponent becuase Forms implements that).

Problem

I've started to learn VBA in Access. I have read that the language has no inheritance. And then I read an example code which seems like it actually has inheritance: ``` Dim ctrl As Control ... If TypeOf ctrl Is TextBox Then ... If TypeOf ctrl Is ListBox Then ... ``` It seems to me as the TextBox, ListBox were inherited from the Control. Could somebody explain this?

Original source