vba - 仅适用于一张工作表的 OnKey

标签 vba excel

我正在尝试添加代码,使“Enter”键的作用类似于一个( protected )工作表的“Tab”键,但在任何其他工作表中则不然。我在 ThisWorkbook 模块中有这段代码:

Private Sub Workbook_Open()
 Application.OnKey "~", "MoveThruForm"
 Application.OnKey "{enter}", "MoveThruForm"
End Sub

在一个单独的模块中我尝试过:

Private Sub MoveThruForm()
Select Case ActiveSheet.CodeName
    Case "Calculator"
    SendKeys "{tab}"
    Exit Sub

    Case "Lists"
    Application.OnKey "~" 'wanted this to set 'enter' key to be normal 'enter' key but it doesn't!
    'SendKeys "{down}" 'This works but is very much a workaround!

End Select
End Sub

这在“计算器”表中工作正常,但在“列表”表中则不然。

关于如何让“输入”键在“列表”表中“正常”发挥作用,有什么建议吗?

(我使用的是 Excel 2013 和 2010。)

最佳答案

为此,您不需要 OnKey :) Excel 允许您更改 Enter 键移动方向。

enter image description here

您也可以通过代码更改它。

在模块中,输入此内容

Public PreState As Long

将此代码放入工作簿代码区

Private Sub Workbook_Open()
    '~~> Store ENTER Key move behaviour
    PreState = Application.MoveAfterReturnDirection
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    '~~> Check here which sheet is active and then
    '~~> decide where the ENTER key should move
    If Sh.Name = "Calculator" Then
        Application.MoveAfterReturn = True
        Application.MoveAfterReturnDirection = xlToRight
    Else
        Application.MoveAfterReturnDirection = PreState
    End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    '~~> Reset ENTER Key behaviour
    Application.MoveAfterReturnDirection = PreState
End Sub

关于vba - 仅适用于一张工作表的 OnKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587134/

相关文章:

excel - 如何在不等于的单元格中计算 3*2*5+6

excel - VBA Excel 宏 - 显示与列相关的单元格值

excel - 选择直到不等范围

python - 如何通过python中的pandas导出到单个csv文件的多个excel表

vba - 宏来计算 hh :mm:ss 中的差异

vba - 将唯一 ID 添加到数字列表 - VBA

excel - 为什么我会从此代码中收到 VBA 运行时错误 '424' Object Required Error?

vba - 从 Excel VBA 发送格式化的 Lotus Notes 富文本电子邮件

php - 自动将 Excel 表格中的产品图像和描述包含在 MySQL 数据库中

excel - NetLogo:将表结果导出到 CSV