VBA迭代地设置variables

我试图find最好的方法,让我的comboboxselect(在我的用户表单中)是他们所代表的实际数字的“别名”。 例如,如果用户在combobox中select“A”,则表示4.0。 我试图find一种方法来迭代地设置我的variables,所以我不必重复相同的select案例代码9次(对于我的9个combobox,我想要做这样的事情:我想要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 

编辑添加一个可能的较短的成绩select(见底部)

在您的用户窗体代码窗格中尝试此代码

 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 

我认为所有相关的combobox名称都以“GradeBox”开头

如您所见,不需要预设“GradeBox”combobox的数量,因为它在运行时通过UserForm_Initialize子节点检测到。

您可能还需要考虑以下等级切换代码

 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 

但后者无法控制指数在实际清单范围内