在 case 语句中使用 userform 作为参数时出错

Error with using userform as an argument in case statements

我有几个用户表单,其中包含我选择年份加载的组合框。根据用户表单,年份列表会发生变化。关于如何构建列表有很多逻辑。因此,我为其创建了一个单独的子过程,该子过程将在逻辑中使用用户窗体。我在用户窗体初始化事件的调用过程中有这个:

Set ufName = ufTest
Call Load_Year_Comboboxes(ufName)

在程序中,我有这个:

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

我的问题是 Select 案例出错。我收到 450 错误“参数数量错误或 属性 赋值无效”。我已经尝试使用定义为用户窗体和 MSForms.Userforn 的变量,但仍然没有成功。我在另一个 post 上读到它必须被分配为一个对象。我找不到关于此特定场景的任何 post。

这与您尝试传递用户表单的方式有关。我不确定您是否可以按照您尝试的方式通过它(也许其他人知道答案);但是,这对我有用。

在用户表单中,我将其添加到 UserForm_Initialize 事件

    Private Sub UserForm_Initialize()
        Load_Year_Comboboxes (Me.Name)
    End Sub

然后在标准代码模块中

Sub Load_Year_Comboboxes(ByVal ufName As String)

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

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

如您所知,您无法通过这种方式检查传递的对象。您可以使用以下 3 种方法来检查传递了哪个对象:

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