我正在构建一个用户表单,其中文本框应该从工作表中选择值(每月12张)。
例如 -
textbox 500到526应该选择jan-dec表格单元格e5到e31中的值。
textbox 527到553应该选择jan-dec表格单元格e38到e64中的值。
textbox 554到580应该选择jan-dec表格单元格e71到e97中的值。
有人可以帮我创建一个循环来生成上述信息吗?
感谢
Private Sub monthlist_Change()
Dim myarray As Variant
Dim X As Long
myarray = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
For X = LBound(myarray) To UBound(myarray)
If Me.monthlist.Text = myarray(X) And Me.Teamlist.Text = "SDM" Then
Me.TextBox500.Value = Worksheets("Functions - " & myarray(X)).Range("e5").Value
ElseIf Me.monthlist.Text = myarray(X) And Me.Teamlist.Text = "Client accounts" Then
Me.TextBox527.Value = Worksheets("Functions - " & myarray(X)).Range("e38").Value
ElseIf Me.monthlist.Text = myarray(X) And Me.Teamlist.Text = "Class action" Then
Me.TextBox554.Value = Worksheets("Functions - " & myarray(X)).Range("e71").Value
End If
End Sub
答案 0 :(得分:0)
编辑
你会用
Me.Controls("TextBox" & i).Value = ...
在相应地设置了iMin和iMax后,你将i = iMin迭代到iMax
但是我还建议您对代码进行以下重构
Option Explicit
Private Sub monthlist_Change()
Dim myMnTBarray As Variant, myMxTBarray As Variant
Dim i As Integer
Dim mnTB As Integer, mxTB As Integer
Dim rngAddress As String
myMnTBarray = Array(500, 527, 554) '<== here you place the lower bounds of textbox names "numeric" part, corresponding to the 3 "teamlist" possible values
myMxTBarray = Array(526, 553, 580) '<== here you place the upper bounds of textbox names "numeric" part, corresponding to the 3 "teamlist" possible values
With Me
i = .teamlist.ListIndex
mnTB = myMnTBarray(i)
mxTB = myMxTBarray(i)
Select Case .teamlist.Text
Case "SDM"
rngAddress = "e5"
Case "Client accounts"
rngAddress = "e38"
Case "Class action"
rngAddress = "e71"
End Select
End With
If rngAddress <> "" Then
With Worksheets("Functions - " & Me.monthlist.Text).Range(rngAddress)
For i = mnTB To mxTB
Me.Controls("TextBox" & i).Value = .Offset(i - mnTB).Value
Next i
End With
End If
End Sub
唯一的假设是monthlist
列表框按顺序填充所有月份名称的数组。
以下只是填充用户表单monthlist
和teamlist
列表框的可能代码
Sub main()
With UserForm1
.monthlist.List = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
.teamlist.List = Array("SDM", "Client accounts", "Class action")
.Show
End With
Unload UserForm1
End Sub