按“Enter”键激活按钮

时间:2014-06-23 12:41:14

标签: excel vba excel-vba

在单元格中输入内容后按Enter键是否可以激活按钮?

我有一个搜索功能,您可以在单元格中输入搜索字符串(C9),按下按钮时会激活该功能。但是如果你已经编辑了一个单元格,我想按Enter键激活它。

所以我正在思考伪代码:

If enterKey Is Activated Then
    If cursor Is in Range("C9") Then
        FindWords(parameter 1, parameter 2...)
    End If
End If

1 个答案:

答案 0 :(得分:0)

假设我们想要检测两个事物:

  1. 单元格 C9 变更
  2. Enter 键用于此更改
  3. 标准模块中输入:

    Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
    
    Public Function WhichKey() As String
    
        If (GetAsyncKeyState(vbKeyTab)) Then
                WhichKey = "Tab"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyTab)) Then
                WhichKey = "Tab"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyDown)) Then
                WhichKey = "Down Arrow"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyUp)) Then
                WhichKey = "Up Arrow"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyRight)) Then
                WhichKey = "Right Arrow"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyLeft)) Then
                WhichKey = "Left Arrow"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyReturn)) Then
                WhichKey = "Enter"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyRButton)) Then
                WhichKey = "Right Click"
                Exit Function
        End If
        If (GetAsyncKeyState(vbKeyLButton)) Then
                WhichKey = "Left Click"
                Exit Function
        End If
    End Function
    

    并在工作表代码区中输入:

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Intersect(Range("C9"), Target) Is Nothing Then Exit Sub
        If WhichKey() <> "Enter" Then Exit Sub
        Application.EnableEvents = False
            Call FindWords()
        Application.EnableEvents = True
    End Sub