2012-08-03 97 views
2

我想在Excel中使用ActiveX组合框。一切工作正常,从下拉按钮click_event填充点。但是,当它设置点击事件时,我发现它甚至从诸如箭头键之类的击键中被触发。这是正常的行为,如果是这样,我怎么能绕过这个?Excel ActiveX ComboBox onClick事件

我的工作在Excel 2007中VBA

这是我用来允许使用按键组合框中导航方法,我会等待,看看是否有更好的解决办法..:是的lastKey公共变量

Private Sub ComboBox1_KeyDown(ByVal KeyCode As _ 
MSForms.ReturnInteger, ByVal Shift As Integer) 
    If KeyCode = 38 Then 
     If ComboBox1.ListIndex <> 0 Then 
      lastkey = KeyCode 
      ComboBox1.ListIndex = ComboBox1.ListIndex - 1 
      KeyCode = 0 
     End If 
    ElseIf KeyCode = 40 Then 
     If ComboBox1.ListIndex <> ComboBox1.ListCount - 1 Then 
      lastkey = KeyCode 
      ComboBox1.ListIndex = ComboBox1.ListIndex + 1 
      KeyCode = 0 
     End If 
    End If 
End Sub 

Private Sub ComboBox1_Click() 
    If lastkey = 38 Or lastkey = 40 Then 
     Exit Sub 
    Else 
     MsgBox "click" 
    End If 
End Sub 
+0

你看到编辑我的帖子? – 2012-08-03 10:35:34

+0

对不起,我认为我错过了它,然后我更新了我的问题 – Deepak 2012-08-04 07:12:08

+0

没有probs :)那么这解决了你的问题? – 2012-08-04 07:28:59

回答

0

是的,这是正常的行为。使用箭头键导航组合中的项目,因此点击事件被触发。

绕过插入此代码。这将捕获所有4个箭头键,并在按下时不执行任何操作。这种方法的唯一缺点是您将无法再使用箭头键进行导航。

Private Sub ComboBox1_KeyDown(ByVal KeyCode As _ 
MSForms.ReturnInteger, ByVal Shift As Integer) 
    Select Case KeyCode 
    Case 37 To 40: KeyCode = 0 
    End Select 
End Sub 

随访

Dim ArKeysPressed As Boolean 

Private Sub ComboBox1_Click() 
    If ArKeysPressed = False Then 
     MsgBox "Arrow key was not pressed" 
     '~~> Rest of Code 
    Else 
     ArKeysPressed = False 
    End If 
End Sub 

Private Sub ComboBox1_KeyDown(ByVal KeyCode As _ 
MSForms.ReturnInteger, ByVal Shift As Integer) 
    Select Case KeyCode 
    Case 37 To 40: ArKeysPressed = True 
    End Select 
End Sub 
+0

感谢您的提示,我想要的这个主要原因是使用箭头键进行导航。我设法修改你的代码以使其适用于我。 – Deepak 2012-08-03 10:28:34

+0

在这种情况下,您可以使用布尔变量来确保按下箭头键时不会触发点击事件。请参阅上面的更新代码。 – 2012-08-03 10:30:28