vba 按下“ENTER”时调用子程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20780583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:05:18  来源:igfitidea点击:

Calling subroutine when "ENTER" is pressed

excel-vbavbaexcel

提问by Kentot

I am new to VBA. I have made a look-up function using vba and it works so fine. Here is what I wanted, I want to call my subroutine (that contains the look-up) when the Enterkey is pressed. How am I going to do this? How does an event like this in VBA work?

我是 VBA 的新手。我使用 vba 做了一个查找功能,它工作得很好。这是我想要的,我想在Enter按下键时调用我的子程序(包含查找)。我该怎么做?VBA 中这样的事件如何工作?

回答by Jerome Montino

Use Application.OnKeywith a Workbook_Openevent. This way, every time your workbook is loaded, you can call your macro on pressing Enter. See below:

使用Application.OnKey带有Workbook_Open事件。这样,每次加载工作簿时,您都可以按 调用宏Enter。见下文:

Private Sub Worksheet_Open(ByVal Target As Range)

    Application.OnKey "{RETURN}", "MyLookUp"

End Sub

Make sure you paste it in the ThisWorkbook's code. Let us know if this helps.

确保将其粘贴到ThisWorkbook's 代码中。如果这有帮助,请告诉我们。

回答by Patrick Lepelletier

workbook> in the Open (and window activate) Subroutine :

workbook> 在打开(和窗口激活)子程序中:

Application.OnKey "{RETURN}", "Sub_Enter"
Application.OnKey "{ENTER}", "Sub_Enter"

the is a difference between numpad Enter and the other Enter.

这是小键盘 Enter 和另一个 Enter 之间的区别。

and on workbook close (and change_window...) : (to deactivate it)

并在工作簿关闭(和change_window ...):(停用它)

Application.OnKey "~"
Application.OnKey "{ENTER}"

You will also need a custom bit of code to know if the content of a cell has changed + ENTER. (in that case your macro Enter will have to ignore and exit sub)...

您还需要一些自定义代码来了解单元格的内容是否已更改 + ENTER。(在这种情况下,您的宏 Enter 将不得不忽略并退出 sub)...