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

标签 events vba excel

我有一个动态选择的单元格,其中将填充一些我要放入的信息,当我在该单元格中输入信息并按ENTER时;

1 - 它应该触发宏

'macro(value)
macro1 myinfo

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

myinfo = Cells( i, j )

那么我怎样才能实现这一目标呢?

最佳答案

要捕获按下的特定键,您需要 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.

上面说,按下 Enter 键时必须运行 myMacroOnKey 方法只需调用一次。您可以将其放入 Workbook_Open 事件中:

Private Sub Workbook_Open()
    Application.OnKey "{ENTER}", "myMacro"
End Sub

要停止捕获 Enter 键,

Application.OnKey "{ENTER}"
<小时/>

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

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
<小时/>

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

像这样启动OnKey:Application.OnKey "{ENTER}", "recordEnterKeypress"

在您的代码模块中,您将拥有以下内容:

Public enterWasPressed As Boolean

Sub recordEnterKeypress()
    enterWasPressed = True
End Sub

单元格编辑将由 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
<小时/>

现在,上面的代码执行了您在问题中提出的问题,但我想重申:您的问题听起来非常像 XY problem 。为什么要检测 Enter 键被按下?让我们知道,也许我们可以提出替代方案。

关于events - 如何在 VBA for Excel 中为动态选择的单元格定义 ENTER 按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9377237/

相关文章:

xml - 将 csv/excel 转换为 xml 的工具

events - 如何在 Haskell 中模拟/欺骗按键事件?

Android MotionEvent.getActionIndex() 和多点触控

python - gevent 用事件控制 greenlets

vba - 按下 'red x'时如何使Excel VBA中的用户窗体记住密码

vba - 在excel中截断数据(删除前12个字符)

c# - Windows 中的重点应用程序更改事件

excel - 使用 VBA 在 Access 中创建多个链接表

vba - 使用 VBA 保存时显示 "Do you want to overwrite the file"对话框

java.lang.OutOfMemory错误: Java heap space while reading Excel file into java bean using XLSReader