NoOne
NoOne

Reputation: 33

F1 key to run macro

How can I assign F1 key to macro in excel instead of 'excel help'? I see many answers to this question, but they do not work in excel 2013/2016.

I need solutions like this, but for new Excel: https://www.extendoffice.com/documents/excel/1798-excel-disable-f1-key.html https://excel.tips.net/T002089_Disabling_the_F1_Key.html

Thanks in advance for help.

Upvotes: 2

Views: 3231

Answers (2)

Vityata
Vityata

Reputation: 43585

Public Sub TestMe()
    Application.OnKey "{F1}", "RunMe"
End Sub

Public Sub UnTestMe()
    Application.OnKey "{F1}"
End Sub

Public Sub RunMe()
    Debug.Print Now
End Sub

If you run TestMe, it would assign F1 to RunMe. To unassign it, run UnTestMe. In general, you may consider using F1 with Ctrl, Shift or Alt like this:

Application.OnKey "^{F1}", "F1_CtrlMacro"
Application.OnKey "%{F1}", "F1_AltMacro"
Application.OnKey "+{F1}", "F1_ShiftMacro"
Application.OnKey "{F1}", "F1_OnlyMacro"

Edit:

To assign it from the beginning, add the following in the ThisWorkbook:enter image description here

Option Explicit

Private Sub Workbook_Open()
    Application.OnKey "{F1}", "RunMyCode"
End Sub

Upvotes: 5

XsiSecOfficial
XsiSecOfficial

Reputation: 964

To disable the current keystroke set to F1

use following VBA code

Sub disableF1()
Application.OnKey "{F1}", ""
End Sub

then to assign it to a macro you made

Public Sub RunMyMacro()

    Application.OnKey "{F1}", "RunMyCode"

End Sub

here is an example of the macro you want it to run:

Public Sub RunMyCode

    MsgBox "This is my macro to run!"

End Sub

Have a nice day

Regards Xsi

Upvotes: 2

Related Questions