excel - 使用相同快捷方式打开多个 Excel 文件的问题
问题描述
我有多个 Excel 文件,它们的宏分配了相同的快捷方式。当我同时打开这些文件并通过快捷方式运行宏时,通过在VBE中调试,我发现它总是会运行第一个打开的文件中的宏而不是宏本身。如何解决?
解决方案
我的建议是以编程方式分配快捷方式,并在工作簿变为活动/不活动时动态启用/禁用它们。通过这种方式,您可以确保一次仅在一个工作簿(即活动工作簿)中启用快捷方式。
这是我解决它的方法:
把它放在ThisWorkbook模块中:
Private Sub Workbook_Activate()
'Debug.Print "Workbook got activated"
Call KeyboardShortcuts(True)
End Sub
Private Sub Workbook_Deactivate()
'Debug.Print "Workbook got deactivated"
Call KeyboardShortcuts(False)
End Sub
这可以放在任意代码模块中:
Function KeyboardShortcuts(assign As Boolean)
' There is a problem when you assign keyboard shortcuts to macros through the macros menu:
' When there are multiple Excel workbooks open in the same instance of the Excel application,
' it is possible that when you enter a keyboard shortcut in workbook A, it gets captured from workbook B.
' This can lead to undesired results.
' So we do it like this:
' keyboard shortcuts are enabled when the workbook gets activated and
' they are disabled when the workbook gets deactivated.
Dim Keydef As String
Dim Keys() As String
Dim item As Variant
Dim pair() As String
Keydef = "+^W:Function1_KB" & _
"|" & "+^D:Function2_KB" & _
"|" & "+^F:Function3_KB" & _
"|" & "+^G:Function4_KB" & _
"|" & "+^L:Function5_KB" & _
"|" & "+^P:Function6_KB" & _
"|" & "+^T:Function7_KB" & _
""
Keys = Split(Keydef, "|")
For Each item In Keys
pair = Split(item, ":")
If assign = True Then
' Enable the keyboard shortcut:
Application.OnKey pair(0), pair(1)
Else
' Disable the keyboard shortcut:
Application.OnKey pair(0)
End If
Next
End Function
Function Function1_KB()
Debug.Print "You have pressed Shft+Ctrl+W"
End Function
...
Function Function7_KB()
Debug.Print "You have pressed Shft+Ctrl+T"
End Function
推荐阅读
- mysql - 按最新值sql分组
- .net - Azure 媒体服务:获取需要编码的视频的时长
- winapi - SetWindowLong 与 SetWindowLongPtr
- google-sheets - 通过过滤掉零值来创建帮助表
- android - 活动在第一次打开时花费了太多时间
- mysql - 将行中的日期显示为 MySQL 中的动态列
- java - 如何创建实现两个通用接口(不修改这些类)的许多类的实例的集合/列表?
- python - 按值将列拆分为新列的更好方法?
- swift - 使用动态键和自动增量 Swift 更新 Cloud Firestore 中的嵌套字段
- azure-devops - Azure YAML - 使用变量动态设置阶段/作业执行顺序