Home » excel » excel – Why do Labels get Type mismatch errors in VBA but ComboBoxes don't?

excel – Why do Labels get Type mismatch errors in VBA but ComboBoxes don't?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m running Excel 2003. I have the following VBA code, corresponding to a simple UserForm comprising a ComboBox control and a Label control. It works through the save of the ComboBox but generates a Type mismatch error when saving the Label.

Private whatComboBox As ComboBox
Private whatLabel As Label

Private Sub UserForm_Initialize()
    Call SaveComboBox(SomeComboBox)
    Call SaveLabel(SomeLabel)
End Sub

Private Sub SaveComboBox(aComboBox As ComboBox)
    Set whatComboBox = aComboBox
End Sub

Private Sub SaveLabel(aLabel As Label)
    Set whatLabel = aLabel
End Sub
[And I do appreciate that VBA is limited in comparison to most other languages. But I wouldn’t have thought this was the kind of thing it would get wrong.]

Thanks all!

How to&Answers:

Try this

Private whatComboBox As msforms.ComboBox
Private whatLabel As msforms.Label

Private Sub UserForm_Initialize()
    Call SaveComboBox(SomeComboBox)
    Call SaveLabel(SomeLabel)
End Sub

Private Sub SaveComboBox(aComboBox As msforms.ComboBox)
    Set whatComboBox = aComboBox
End Sub

Private Sub SaveLabel(aLabel As msforms.Label)
    Set whatLabel = aLabel
End Sub

Regarding your query

It works through the save of the ComboBox but generates a Type mismatch error when saving the Label.

You must qualify the Label object because Excel also has an object named Label

Alternative

Private whatComboBox As Control
Private whatLabel As Control

Private Sub UserForm_Initialize()
    Call SaveComboBox(SomeComboBox)
    Call SaveLabel(SomeLabel)
End Sub

Private Sub SaveComboBox(aComboBox As Control)
    Set whatComboBox = aComboBox
End Sub

Private Sub SaveLabel(aLabel As Control)
    Set whatLabel = aLabel
End Sub