dynamic引用ComboBox的更简洁的代码

我是VBA的新手。 这也是我在这里的第一篇文章。 我正在创build一个将用作表单的Excel电子表格。 大约有50个combobox是必需的。

代码的每个部分都可以工作,但是我想知道是否有更简洁的方法来执行以下操作:

  • 在不同的工作表上填充范围内的combobox(下面的第1节)
  • validation所选的选项。 如果select无效,那么只发一次错误消息。 它目前被抛出两次。 (下文第2节)
  • 一旦按下标签或input,移动到活动单元格。 (下文第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 

你改进了主要部分,但是还有一个优化我会包括:

在For循环之外只提取一次最后一次使用的行:


 Option Explicit Private Sub Worksheet_Activate() Dim rngList As Range, i As Long With Worksheets("Sheet6") Set rngList = .Range("AC10:AC" & .Range("AC" & .Rows.Count).End(xlUp).Row).Value End With For i = 1 To 9 Sheet3.Shapes("ComboBox" & i).OLEFormat.Object.Object.List = rngList Next i End Sub Private Sub ComboBox1_Change() If ComboBox1.ListIndex < 0 Then ComboBox1.ListIndex = -1 MsgBox "Entity Does Not Exist" End If End Sub Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) IIf KeyCode = 9, ActiveCell.Offset(0, 1).Activate, ActiveCell.Offset(1, 0).Activate End Sub '------------------------------------------------------------------------------------------