我有多个 Excel 文件,其中的宏分配了相同的快捷方式。当我同时打开这些文件并通过快捷方式运行宏时,通过在VBE中调试,我发现它总是运行第一个打开的文件中的宏而不是宏本身。怎么解决?
解决方法是对宏使用不同的快捷键。在一个 Excel 实例中,您只能将快捷方式分配给一个过程。快捷方式是按 Excel 实例而不是按文件分配的。
另一个解决方法是确保文件在不同的 Excel 实例中打开。不同实例的行为就像 2 个完全独立的 Excel 应用程序。
启动第二个 Excel 时按住键盘上的 Alt 按钮可以打开新实例。
另请参阅如何打开 Excel 的多个实例。
如果您有 2 个不同的实例,则每个 Excel 实例都有自己的应用程序设置,因此当您按下快捷方式时,快捷方式仅运行具有焦点的实例的宏。
我的建议是以编程方式分配快捷方式,并在工作簿变为活动/非活动状态时动态启用/禁用它们。通过这种方式,您可以确保一次仅在一个工作簿(即活动工作簿)中启用快捷方式。
这是我解决问题的方法:将其放入
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 Keys() As Variant
Dim pair As Variant
Keys() = Array(Array("+^W", "Function1_KB"), _
Array("+^D", "Function2_KB"), _
Array("+^F", "Function3_KB"), _
Array("+^G", "Function4_KB"), _
Array("+^L", "Function5_KB"), _
Array("+^P", "Function6_KB"), _
Array("+^T", "Function7_KB"))
For Each pair In Keys
If assign = True Then
' Enable the keyboard shortcut:
Application.OnKey pair(0), pair(1)
Else
' Disable the keyboard shortcut:
On Error Resume Next
Application.OnKey pair(0)
On Error GoTo 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