Trace
Trace

Reputation: 18869

Cast to Interface type in VBA

How can we typecast to an interface type in VBA?

Public Function createArray(ParamArray args() As Variant) As IArray

    Dim arr As IArray
    Set arr = New cRwArray

    Select Case UBound(args)

        'No params
        Case -1
            'Create decorator for empty array (no action required)

        '1 params
        Case 0
            'Return array with range values
            If TypeName(args(0)) = "cRwRange" Then
                'Cast type
                Dim range As iRange
                range = ctype(args(0), iRange) 'IRange variable not defined
                Call arr.readFromRange(range)

    End Select
    Set createArray = arr
End Function

Edit: this is strange.

Sub test()

    Dim arr As IArray
    Dim range As iRange

    Set range = createRange("Sheet1", 20, 30)
    Set arr = createArray(range)

End Sub

Yet, the type is not correctly set.
I checked this in the factory:

Debug.Print TypeName(args(0)) 'cRwRange, not the interface type? 

Upvotes: 1

Views: 1774

Answers (1)

Rory
Rory

Reputation: 34045

You don't have to explicitly cast the object, as simple assignment will work:

Set range = args(0)

Additionally, TypeName returns the declared type of an object; if you want to know whether a given object implements a specific interface, you use TypeOf:

If TypeOf range Is iRange Then

for example. Also note that range is really not a good name for a variable in Excel... :)

Upvotes: 1

Related Questions