我有一个userform,它有三个概念文本框组。我正在尝试为每个组创建一个集合,然后当用户单击一个按钮来调用与其中一个组相关联的子/函数时,我希望能够调用一个循环通过相关文本框集合的函数使用该组并检查它们是否为空,包含无效字符等。
我在模块级别做了以下声明。
Dim typSectFields, laneFields, matFields As Collection
然后,当用户表单初始化时,我将文本框添加到集合中:
Set typSectFields = New Collection
With frmAddTypSect
typSectFields.Add txtTypSectName
typSectFields.Add txtStartSta
typSectFields.Add txtEndSta
End With
然后当用户单击使用“typSectFields”集合中输入的按钮时:
Dim tb As Control, res As VbMsgBoxResult
For Each tb In typSectFields
If tb.Text = vbNullString And t.Tag <> vbNullString Then
res = MsgBox("You've not completed the " + tb.Tag + " field. Would you like to complete it now?", vbYesNo + vbQuestion)
If res = vbYes Then Exit Sub
End If
Next
执行命中For循环时出现“Object Required”错误 VBE显示tb = nothing且typSectFields = Empty。
我做错了什么?
答案 0 :(得分:0)
确保所有代码(特别是模块级声明)都在表单模块后面的代码中。以下运行对我没有错误:
Dim typSectFields As Collection, laneFields As Collection, matFields As Collection
Private Sub CommandButton1_Click()
Dim tb As Control, res As VbMsgBoxResult
For Each tb In typSectFields
If tb.Text = vbNullString And tb.Tag <> vbNullString Then
res = MsgBox("You've not completed the " + tb.Tag + " field. Would you like to complete it now?", vbYesNo + vbQuestion)
If res = vbYes Then Exit Sub
End If
Next
End Sub
Private Sub UserForm_Initialize()
Set typSectFields = New Collection
With frmAddTypSect
typSectFields.Add txtTypSectName
typSectFields.Add txtStartSta
typSectFields.Add txtEndSta
End With
End Sub