using Interfaces in vba for using same function for different kind of type


function "AddWeight" can add weight to every pet. I know that all of my animal (Inherit) have basicInfo type with same name ("data"), so i'm sure that "AddWeight"-function can proper handle with it. of course Vba will not let me to do that, i tried to declare in function title on object or variant.. nothing of them work for me.. someone have creative idea? i don't want to write this function for every animal and i also don't find it elegant to call function like that:

Call addWeight(

someone have other idea? thanks in advanced

   Type basicInfo
                name As string
                weight as integer
                height as integer
            End Type

            Type cat
                data As basicInfo
                mustacheType As String
            End Type

            Type dog
                data As basicInfo
                bark_volume as integer
            End Type

       Dim Max_Cat as cat
       Dim Buddy_Dog as dog
    .   some code
        Call addWeight(Max_Cat)
        Call addWeight(Buddy_Dog) 

        Public Function AddWeight(petName as object) 'not work also for petName as variant

        End Function

Show source
| excel-vba   | function   | vba   | excel   | types   2017-01-05 13:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 00:01

    As mentioned in the comments, this isn't "inheritance" in the strictest sense of the word. It's more like a composite structure. If you want to represent your data using Types, the obvious solution is to just pass the member that you want to work with, i.e. the basicInfo:

    Sub SomeSub()
        Dim Max_Cat As cat
        Dim Buddy_Dog As dog
        'Other stuff.
    End Sub
    Public Function AddWeight(animal As basicInfo)
        animal.weight = animal.weight + 50
    End Function

    If you really want to use interfaces, you'll need to build classes instead of types. That way you can have them implement a common interface, then use the interface as the parameter. This is probably going to give you much more robust and extensible code - I'd suggest reading Object-Oriented VBA in Documentation.

◀ Go back