【发布时间】:2015-10-27 13:55:04
【问题描述】:
我是 VBA 的新手。这也是我在这里的第一篇文章。我正在创建一个将用作表单的 Excel 电子表格。大约需要 50 个组合框。
代码的每个部分都有效,但我想知道是否有更简洁的方法来执行以下操作:
- 从不同工作表上的范围填充组合框(下面的第 1 节)
- 验证选择的选项。如果选择无效,则仅抛出一次错误消息。它目前被抛出两次。 (下文第 2 节)
-
一旦按下制表符或回车键,移动到活动单元格。 (下文第 3 节)
Private Sub Worksheet_Activate() With Worksheets("Sheet6") ComboBox1.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox2.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox3.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox4.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox5.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox6.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox7.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox8.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value ComboBox9.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value End With End Sub Private Sub ComboBox1_Change() If ComboBox1.ListIndex < 0 Then MsgBox "Entity Does Not Exist" Range(ComboBox1.LinkedCell).Select Application.EnableEvents = False ActiveCell.FormulaR1C1 = "" Application.EnableEvents = True End If End Sub Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) Select Case KeyCode Case 9 ActiveCell.Offset(0, 1).Activate Case 13 ActiveCell.Offset(1, 0).Activate Case Else End Select End Sub更新* - 我已经找到了第 2 部分。新代码很简单:
Private Sub ComboBox1_Change() If ComboBox1.ListIndex < 0 Then ComboBox1.ListIndex = -1 MsgBox "Entity Does Not Exist" End If End Sub
更新** - 这对于第 2 部分来说要好一些:
Private Sub WorkSheet_Activate()
With Worksheets("Sheet6")
Dim cb As ComboBox
Dim i As Long
For i = 1 To 9
Set cb = Sheet3.Shapes("ComboBox" & i).OLEFormat.Object.Object
cb.List = .Range("AC10:AC" & .Range("AC" & .Rows.count).End(xlUp).Row).Value
Next i
End With
End Sub
【问题讨论】:
-
看起来您正在以几乎相同的方式处理所有 ComboBox,因此创建了一个 VBA 类,您可以将其附加到每个 ComboBox 以进行初始化、验证和使用。看看我在this post 中为 CheckBoxes 创建的解释,看看它是否有意义。
标签: vba excel dynamic combobox