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



我有一些用户表单,它们有组合框,我可以用选择的年份加载。根据用户表单的不同,年份列表会发生变化。关于如何构建列表,有大量的逻辑。因此,我为它创建了一个单独的子流程,它将在逻辑中使用userform。我在userform Initialize事件的调用过程中有这个:

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 Case中遇到了一个错误。我得到450错误";参数数目错误或属性分配无效";。我尝试过将变量定义为userform和MSForms.Userforn,但仍然没有成功。我在另一篇帖子上读到,它必须被指定为对象。我找不到任何关于这个特定场景的帖子。

正如您所发现的,您不能用这种方式检查传递的Object。这里有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

这与您试图传递用户表单的方式有关。我不确定你是否能像你尝试的那样通过(也许其他人知道答案(;然而,这对我很有效。

在用户表单中,我将其添加到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

最新更新