I have been running into type errors when casting worksheets that implement an interface of my own design into objects of the same type as the interface. Whilst these are not 100% reliable (sometimes the cast works) I have not been able to identify any rhyme or reason behind the situations when it does or does not.
The issue persists in a simplified environment, and can be seen clearly by following the below steps (at least in Excel 2010):
Create a new workbook, add a class module, make it public-non-createable and call it ITest, create a standard module called Tools (although I believe this could have any name) and paste the following into the code modules for ITest, Tools, and Sheet1 respectively:
ITest:
Option Explicit
Public Function Test() As Boolean
End Function
Tools:
Option Explicit
Public Function IsRangeInSheetImplementingTest(rngIn As Excel.Range) As Boolean
Dim oWks As Object
Dim oITest As ITest
On Error Resume Next
Set oWks = rngIn.Worksheet
Set oITest = oWks
If Err.Number <> 0 Then
IsRangeInSheetImplementingTest = False
Else
IsRangeInSheetImplementingTest = True
End If
End Function
Sheet1:
Option Explicit
Implements ITest
Public Function ITest_Test() As Boolean
ITest_Test = True
End Function
You should find that calling IsRangeInSheetImplementingTest(Range("A1"))
returns False
. Commenting out On Error Resume Next
demonstrates that this is due to a Type Mismatch
on the line Set oITest = oWks
. Can anyone tell me (1) why is this happening and (2) what can I do to make the interface get recognised properly?
As a side note, sometimes placing the same call in a cell within the workbook gives the correct result - but only sometimes. Very confused as to what's going on here - any help very gratefully appreciated!
CTest
) paste in the Sheet1 code, and then in a subroutine recreate the following:Dim oCTest as New CTest : Dim oITest as ITest : Set oITest = oCTest
and run it. It'll execute with no errors. The problem is whether there are any specific rules for built in object types - and what they are!IsRangeInSheetImplementingTest(Range("A1"))
, so this is actuallyIsRangeInSheetImplementingTest(ActiveSheet.Range("A1"))
, does the activesheet implement the interface?IsRangeInSheetImplementingTest(Sheet1.Range("A1"))
worked fine for me=IsRangeInSheetImplementingTest(A1)
begins by returning false (changes to true if you access the object directly from the immediate window, e.g.debug.print Sheet1.Name
)