我是否有更有效的方法来编写此用户格式代码?
Private Sub Userform_Initialize()
'do stuff
With Item1_DropDown
.AddItem "Monday"
.AddItem "Tuesday"
.AddItem "Wednesday"
End With
With Item2_DropDown
.AddItem "Monday"
.AddItem "Tuesday"
.AddItem "Wednesday"
End With
With Item3_DropDown
.AddItem "Monday"
.AddItem "Tuesday"
.AddItem "Wednesday"
End With
'and so on, and so on. (I have about fifty of these 'With/End With' blocks)
End Sub
基本上,我希望能够停止编写这么多'With / End With'块。现在,我在四个类似构造的用户表单中有这种类型的代码。它占用了太多的文本空间,似乎是一种浪费。有更好的方法吗?
请知道我从未写过课程模块。所以,如果解决方案需要它,我将需要被其中的宝宝所吸引。
谢谢,
利亚
答案 0 :(得分:5)
使用子程序划分代码:)
假设您的下拉列表为ComboBox
表单控件:
Private Sub Userform_Initialize()
PopulateDropDown Item1_DropDown
PopulateDropDown Item2_DropDown
PopulateDropDown Item3_DropDown
End Sub
Sub PopulateDropDown(cb as MSForms.ComboBox)
With cb
.AddItem "Monday"
.AddItem "Tuesday"
.AddItem "Wednesday"
End With
End Sub
答案 1 :(得分:3)
此外,您可以使用List
填充项目:
Private Sub UserForm_Initialize()
Me.ComboBox1.List = Array("Monday", "Tuesday", "Wednesday")
End Sub
您可以定义此数组(Variant)一次:
Private days As Variant
Private Sub UserForm_Initialize()
days = Array("Monday", "Tuesday", "Wednesday")
Me.ComboBox1.List = days
End Sub
我还会利用Tag
属性(每个组合框)来区分那些需要填充这些值的属性:
Private days As Variant
Private Sub UserForm_Initialize()
Dim ctl As Control
days = Array("Monday", "Tuesday", "Wednesday")
For Each ctl In Me.Controls
If TypeOf ctl Is ComboBox And ctl.Tag = "days" Then
ctl.List = days
End If
Next ctl
End Sub
答案 2 :(得分:1)