Search code examples
excelvbauserform

Error with using userform as an argument in case statements


I have a few userforms that have comboboxes that I load with a selection of years. Depending on the userform, the list of years changes. There is a good amount of logic on how the list is constructed. I have therefore create a separate subprocedure for it that would utilize the userform in the logic. I have this in the calling procedure in the userform Initialize event:

Set ufName = ufTest
Call Load_Year_Comboboxes(ufName)

And in the procedure, I have this:

Sub Load_Year_Comboboxes(ufName As Object)

    Dim rFirstYear As Range
    Dim yCount As Integer, X As Integer, iThisYear As Integer, iYearCount as integer

    Select Case ufName
        Case(ufTest)
            yCount = 0
            Set rFirstYear = wsUserInput.Range("F10")
            Do While yCount < iYearCount
                ufName.cboBeginYear.AddItem rFirstYear.Offset(yCount, 0)
                yCount = yCount + 1
            Loop
        End Select
    'do other things
End sub

My problem is that I get an error with the Select Case. I get the 450 error "wrong number of arguments or invalid property assignment". I have tried with the variable defined as a userform and MSForms.Userforn, but still with no luck. I read on another post that it had to be assigned as an object. I cannot find any posts as to this specific scenario.


Solution

  • As you found out, you can't check the passed Object this way. Here are 3 ways you could use to check which Object was passed:

    Option Explicit
    
    Public Sub Load_Year_Comboboxes(ufName As Object)
        'check the name property
        Select Case ufName.Name
            Case "UserForm1"
               MsgBox "UserForm1 is being processed"
        End Select
        
        'check the type with Select
        Select Case True
            Case TypeOf ufName Is UserForm1
               MsgBox "UserForm1 is being processed"
        End Select
        
        'check the type with If
        If TypeOf ufName Is UserForm1 Then
            MsgBox "UserForm1 is being processed"
        End If
    End Sub