2
votes

I am attempting to create a class module that builds on top of a checkbox control. Within the Class Module I want to point at the checkbox in the userform. Although, when I try to fill the CheckBox object with one of the checkboxes in the userform I get a type-mismatch since calling on the checkbox gives back it's state instead of the entire object. Is there a way to get the entire object?

I have tried

set myCheckBox = makeMyCheckBox(Me.CheckBox1)

and

set myCheckBox = makeMyCheckBox(Me.CheckBox1.Object)

where makeMyCheckBox is a function that takes in a CheckBox object and creates a new MyCheckBox object.

'Within my userform's code

Dim myCheckBoxes(1 to 2) As MyCheckBox 'MyCheckBox is my class module

Private Sub UserForm_Initialize()
set myCheckBoxes(1) = makeMyCheckBox(me.CheckBox1)'<--Error Type Mismatch
End Sub

Private Function makeMyCheckBox(c As CheckBox) As MyCheckBox 
Dim myChck As MyCheckBox 
Set myChck = New MyCheckBox 
myChck.init c 'takes in a CheckBox and fills its internal CheckBox object
Set makeMyCheckBox= myChck 
End Function

I expect Me.CheckBox1 to be a CheckBox object. Me.CheckBox1 outputs the checkbox's state when I look in debug (true/false)

I get-- Run-time error '13': Type Mismatch

1
Qualify the types with the library they're from. Private Function makeMyCheckBox(ByVal c As MSForms.CheckBox) As MyCheckBox -- otherwise As CheckBox is As Excel.CheckBox, which is indeed a different and incompatible type.Mathieu Guindon

1 Answers

1
votes

I get a type-mismatch since calling on the checkbox gives back it's state instead of the entire object. Is there a way to get the entire object?

Wrong assumption, you're getting the "entire object", but the object you're getting isn't implementing the interface you're expecting, hence the type mismatch.

You need to qualify your MSForms types explicitly with the MSForms library, like this:

Private Function makeMyCheckBox(ByVal c As MSForms.CheckBox) As MyCheckBox 

Otherwise the unqualified CheckBox identifier / type name is referring to Excel.CheckBox, because the host application's object model (the Excel library) always has a higher priority than the referenced MSForms library, in the project references dialog:

Microsoft Excel 16.0 object library showing before Microsoft Forms 2.0 object library

This is excruciatingly hard to discover in a vanilla VBE. With Rubberduck you just place the caret on CheckBox and it tells you where it's coming from:

Excel checkbox

MSForms checkbox

Without any add-ins, you kind of have to guess what the actual type is, because Shift+F2 (which normally takes you to the definition in the Object Browser) is useless for this - all you get is a message saying "the identifier under the cursor is not recognized".

Disclaimer: I manage the Rubberduck open-source project.