我正在尝试找到让我的组合框选择(在我的用户表单中)为其所代表的实际数字的“别名”的最佳方式。例如,如果用户在组合框中选择“A”,则表示4.0。我试图找到一种迭代设置变量的方法,所以我不必重复相同的选择案例代码9次(对于我的9个组合框。我正在尝试做这样的事情:我想要GradeBox( GradeBox_0,GradeBox_1等等)
For i = 0 To GRADE_BOX_COUNT
Select Case GradeBox_0.ListIndex
Case 0
Grades(i) = 4
Case 1
Grades(i) = 3.7
Case 2
Grades(i) = 3.3
Case 3
Grades(i) = 3
Case 4
Grades(i) = 2.7
Case 5
Grades(i) = 2.3
Case 6
Grades(i) = 2
Case 7
Grades(i) = 1.7
Case 8
Grades(i) = 1.3
Case 9
Grades(i) = 1
Case 10
Grades(i) = 0.7
Case 11
Grades(i) = 0
End Select
Next i
答案 0 :(得分:1)
已修改以添加可能的较短成绩(参见下半部分)
在UserForm代码窗格中尝试此代码
Option Explicit
Dim GradeBox() As MSForms.ComboBox
Dim Grades() As Double
Dim nGradeBox As Long
Private Sub UserForm_Initialize()
Dim ctrl As MSForms.Control
With Me
ReDim GradeBox(0 To Me.Controls.Count - 1) As MSForms.ComboBox
ReDim Grades(0 To Me.Controls.Count - 1) As Double
For Each ctrl In .Controls
If TypeName(ctrl) = "ComboBox" And Left(ctrl.Name, 8) = "GradeBox" Then
Set GradeBox(nGradeBox) = ctrl
ctrl.RowSource = ActiveSheet.Range("A1:A11").Offset(, nGradeBox).Address '<== here I filled comboboxes with ranges vakues
nGradeBox = nGradeBox + 1
End If
Next ctrl
End With
ReDim Preserve GradeBox(0 To nGradeBox - 1) As MSForms.ComboBox
ReDim Preserve Grades(0 To nGradeBox - 1) As Double
End Sub
Private Sub CommandButton1_Click()
Dim i As Long
With Me
For i = 0 To nGradeBox - 1
Select Case GradeBox(i).ListIndex
Case 0
Grades(i) = 4
Case 1
Grades(i) = 3.7
Case 2
Grades(i) = 3.3
Case 3
Grades(i) = 3
Case 4
Grades(i) = 2.7
Case 5
Grades(i) = 2.3
Case 6
Grades(i) = 2
Case 7
Grades(i) = 1.7
Case 8
Grades(i) = 1.3
Case 9
Grades(i) = 1
Case 10
Grades(i) = 0.7
Case 11
Grades(i) = 0
End Select
Next i
End With
End Sub
我假设所有相关组合框的名称都以&#34开头; GradeBox&#34;
如您所见,无需预设&#34; GradeBox&#34;组合框,因为它在运行时通过UserForm_Initialize
sub。
您可能还需要考虑以下等级切换代码
Private Sub CommandButton1_Click()
Dim i As Long
Dim gradesArr As Variant
gradesArr = Array(4, 3.7, 3.3, 3, 2.7, 2.3, 2, 1.7, 1.3, 1, 0.7, 0) '<== list here the grades. they'll be associated with their index in the array
For i = 0 To nGradeBox - 1
If GradeBox(i).ListIndex > -1 And GradeBox(i).ListIndex <= UBound(gradesArr) Then Grades(i) = gradesArr(GradeBox(i).ListIndex)
Next i
End Sub
另一种可能的更短的方式是
Private Sub CommandButton1_Click()
Dim i As Long
For i = 0 To nGradeBox - 1
Grades(i) = Choose(GradeBox(i).ListIndex + 1, 4, 3.7, 3.3, 3, 2.7, 2.3, 2, 1.7, 1.3, 1, 0.7, 0)'<== list here the grades. they'll be associated with their position form 1 to n)
Next i
End Sub
但后者无法控制索引在实际列表范围内