How to Run a Private Sub with a Shortcut Key

hrayani

Well-known Member
Joined
Jul 23, 2010
Messages
1,545
Office Version
  1. 2016
Platform
  1. Windows
Hello Friends,

I want to run the below VBA code with a shortcut key CTRL +q which I can if the sub is not Private

Can somebody please let me know how to make it run with a shortcut key if I set it to private (if possible) ?

VBA Code:
Private Sub unlockactivesheet()
If Sheets("INDEX").Range("A1") = "HUMAYUN-LAPTOP1N4CT93" Then
ActiveSheet.Unprotect Password:="merchant"
ActiveWindow.DisplayHeadings = True
End If
End Sub

Regards,

Humayun
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Use the OnKey Method of the application:

To activate the keys combo:
VBA Code:
Application.OnKey "^q", "unlockactivesheet"

To deactivate it:
VBA Code:
Application.OnKey "^q"

If the Private unlockactivesheet routine is located in a Class Module, say the ThisWorkbook Module, you can do this::
VBA Code:
Private Sub Workbook_Open()
    Application.OnKey "^q", Me.CodeName & ".unlockactivesheet"
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.OnKey "^q"
End Sub

EDIT:
Or better than the Open and BeforeClose events, use the Workbook_Activate and Workbook_Deactivate events respectively so it is only applied to the workbook where the code is located.
 
Upvote 0
Hi Jaafar,

Thanks for the reply
It is a normal module - not class module

I have placed the codes in the workbook open & close even but when I press CTRL + q it says below
 
Upvote 0
Hi Jaafar,

Thanks for the reply
The code is in the normal module - Not class module

After placing the lines you have provided in the workbook open & close event & after pressing the shortcut key CTRL + q it says

1735112633109.png
 
Upvote 0

Forum statistics

Threads
1,225,204
Messages
6,183,565
Members
453,169
Latest member
Marlon18

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top