我有一个动态选择的单元格,其中将填充一些我要放入的信息,当我在该单元格中输入信息并按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 键时必须运行 myMacro
。 OnKey
方法只需调用一次。您可以将其放入 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/