Private Sub ComboBox1_Click()循环

时间:2017-03-23 20:52:21

标签: vba excel-vba combobox excel

我有一个ComboBox的代码,其目的是在选择其值后写入ComboBox的值,然后重置ComboBox。代码如下:

Private Sub ComboBox1_Click()
  Dim valor As String
  Dim celda As Range
  Set celda = ActiveCell
  valor = ComboBox1.Value
  ComboBox1.ListIndex = "-1"
  celda = valor
  celda.Offset(1, 0).Select
End Sub

看起来语句ComboBox1.ListIndex =“ - 1”一遍又一遍地触发Sub ComboBox1_Click()。这种情况只发生过几次。任何想法如何解决它?

3 个答案:

答案 0 :(得分:2)

这个问题有很多可能的解决方案。我建议两个解决方案,一个可以轻松解决这个特定情况,另一个是“通用”,以避免在任何子程序中重新进入。

解决方案1。

此解决方案特定于您的具体情况。您可以在继续之前检查ListIndex属性,在子网的第一行:

    If ComboBox1.ListIndex = -1 Then Exit Sub

例程将输入两次,但在第二次出现时,它将立即退出,不起作用。

解决方案2。

这是避免重新进入任何常规的一般解决方案。你可以为例程定义一个状态变量,这是一个静态布尔变量,它指示例程是否已经在调用堆栈中,在这种情况下你不需要进入它。

Private Sub NoReEnter()
    Static isActive as Boolean ' <-- indicates that this routine is already in the call stack
    If isActive then Exit Sub
    isActive = True
    On Error Goto Cleanup

    '''''''''''''''''''''''''''''''''''''''''''''''''''' 
    '  .... ' Body of the routine
    ''''''''''''''''''''''''''''''''''''''''''''''''''''
Cleanup: ' make sure to reset the state variable before exiting
    isActive = False
End Sub

解决方案2可以应用于您想要进行非递归的任何例程。将此解决方案转换为您的代码,而不涉及其他潜在的(偏离主题)问题,提供以下内容:

Private Sub ComboBox1_Click()
    Static isActive As Boolean
    If isActive then Exit Sub
    isActive = True
    On Error Goto Cleanup

    ' You routine's code as is
    '''''''''''''''''''''''''''''''''''''''''''''''''''' 
    Dim valor As String
    Dim celda As Range
    Set celda = ActiveCell
    valor = ComboBox1.Value
    ComboBox1.ListIndex = -1
    celda = valor
    celda.Offset(1, 0).Select
    '''''''''''''''''''''''''''''''''''''''''''''''''''' 

Cleanup:
   isActive = False
End Sub

答案 1 :(得分:0)

试试这个

Private Sub ComboBox1_Click()
  Dim valor As String
  Dim celda As Range
  Set celda = ActiveCell
  valor = ComboBox1.Value
  ComboBox1.ListIndex = 0
  celda.value=valor
End Sub

答案 2 :(得分:0)

我相信你的代码可能会触发事件,尝试在代码运行时禁用事件:

Private Sub ComboBox1_Click()
  Dim valor As String
  Dim celda As Range

  Application.EnableEvents = False ' disable events

  Set celda = ActiveCell
  valor = ComboBox1.Value
  ComboBox1.ListIndex = "-1"
  celda = valor
  celda.Offset(1, 0).Select

  Application.EnableEvents = True ' re-enable events

End Sub