我想分配一个热键和弦,例如 Ctrl + C , C 调用宏VBA excel。请帮我。我正在尝试使用Application.Onkey
,但不能。
答案 0 :(得分:1)
可怕而笨拙,但是您可以编写一个“临时”宏,该宏使用GetAsyncKeyState
检测键状态并检查 C 是否已释放,然后再次按下。
正如评论中正确提到的Mathieu Guindon一样,重新绑定 Ctrl + C (默认的“复制”快捷方式)是...“麻烦”的-因此,如果您没有在宏开始后的1秒钟内再次按 C ,则会执行正常的复制操作。
Option Explicit
Declare Function GetAsyncKeyState Lib "User32.dll" (ByVal vKey As Long) As Long
Const VK_C As Long = &H43
Public Sub CtrlCMacro()
Dim keyCReleased As Boolean, timeLimit As Single
keyCReleased = False
timeLimit = Timer + 1 'This gives you 1 second to release-and-press C
'On Windows, this is correct to Fractions of a Second.
'On Mac, it is whole seconds, so will not always behave properly, and can give you 0.1 seconds to act
While timeLimit > Timer
'This will check if you release and then re-press "C"
If GetAsyncKeyState(VK_C) = 0 Then
'You have to release the key before you can press it again!
keyCReleased = True
ElseIf keyCReleased Then
'Application.OnTime ensures that THIS sub finishes before the next macro starts
Application.OnTime Now(), "MyOtherMacro"
Exit Sub
End If
Wend
'Default action for Ctrl+C should be Copy
Selection.Copy
End Sub
Public Sub MyOtherMacro()
MsgBox "The Macro Ran!"
End Sub
'Debug Stuff
Private Sub SetCtrlC()
'Bind
Application.OnKey "^c", "CtrlCMacro"
End Sub
Private Sub ResetCtrlC()
'Reset to normal state
Application.OnKey "^c"
End Sub