如何在VBA for Excel中为动态选择的单元格定义ENTER按键事件

Ber*_*eer 10 excel events vba excel-vba

我得到了一个动态选择的Cell,它将填充一些我将要放置的信息以及当我将信息和ENTERkeypressed放在那个Cell时;

1 - 它应该触发一个宏

'macro(value)
macro1 myinfo
Run Code Online (Sandbox Code Playgroud)

2 - 宏应该获取该单元格中的信息

myinfo = Cells( i, j )
Run Code Online (Sandbox Code Playgroud)

那我该如何实现呢?

Jea*_*ett 19

要捕获正在按下的特定键,您需要以下OnKey方法:

Application.OnKey "~", "myMacro" ' for the regular enter key
' or if you want Enter from the numeric keypad:
' Application.OnKey "{ENTER}", "myMacro"
' Below I'll just assume you want the latter.
Run Code Online (Sandbox Code Playgroud)

以上说,按下键myMacro时必须运行Enter.该OnKey方法只需要调用一次.你可以把它放在Workbook_Open事件中:

Private Sub Workbook_Open()
    Application.OnKey "{ENTER}", "myMacro"
End Sub
Run Code Online (Sandbox Code Playgroud)

要停止捕获Enter密钥,

Application.OnKey "{ENTER}"
Run Code Online (Sandbox Code Playgroud)

要检查是否Enter在单元格A1上按下了,可以执行以下操作:

Sub myMacro()
    If Not Intersect(Selection, Range("A1")) Is Nothing Then
    ' equivalent to but more flexible and robust than
    'If Selection.Address = "$A$1" Then
        MsgBox "You pressed Enter while on cell A1."
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

现在要检测是否Enter在特定单元格中按下了该单元格,我们必须有点聪明.假设您编辑一个单元格值并按Enter键.触发的第一件事是OnKey宏,然后Worksheet_Change触发事件.因此,您首先必须"保存结果" OnKey,然后Worksheet_Change根据这些结果处理事件.

OnKey像这样发起:Application.OnKey "{ENTER}", "recordEnterKeypress"

在您的代码模块中,您将拥有:

Public enterWasPressed As Boolean

Sub recordEnterKeypress()
    enterWasPressed = True
End Sub
Run Code Online (Sandbox Code Playgroud)

Worksheet_Change事件将捕获单元格编辑:

Private Sub Worksheet_Change(ByVal Target As Range)
    If enterWasPressed _
        And Not Intersect(Target, Range("A1")) Is Nothing Then
        MsgBox "You just modified cell A1 and pressed Enter."
    End If
    enterWasPressed = False 'reset it
End Sub
Run Code Online (Sandbox Code Playgroud)

现在,上面的代码完成了你在问题中提出的问题,但我想重申一下:你的问题听起来非常像XY问题.为什么要检测Enter按下的键?让我们知道,也许我们可以建议替代方案.


Sid*_*out 6

当在该单元格中输入股票代码并在excel中提供该股票的信息而导致生成错误时,Worksheet_Change或更改命令将仅导致它进入循环,因为当股票信息被解析到它将触发的单元格中时事件一次又一次.. - BerkerYüceer31分钟前

的Berker,

为此,您不需要捕获"ENTER"键.比方说,您键入股票代码,而不是按ENTER键,您单击另一个单元格.您是否也不希望在该场景中触发宏?如果是,请尝试下面的代码.我假设在单元格A1中输入股票代码时必须运行宏.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    '~~> This line ensure that the code will enter into the
    '~~> block only if the change happened in Cell A1
    If Not Intersect(Target, Range("A1")) Is Nothing Then
        Application.EnableEvents = False

        '
        ' ~~> Put your macro code here or run your macro here
        '
    End If

LetsContinue:
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub
Run Code Online (Sandbox Code Playgroud)

编辑:我看到你已经选择了你的答案:)