Question

I have created a macro for excel which will pop up form that contains button and text field. Is there a way to assign hotkeys such as 'ctrl+Enter' or 'F12' to the buttons? The hotkey should work regardless of which field or button the focus is on.

(so far I have managed to create buttons/fields_Keydowns to check MSForms.ReturnInteger for vbKeyF12, but I have to do that for every field and button, is there an easier way?)

Say, I have 2 things on the form, button "CommandButton1" and textfield "TextBox1"

code for the button:

Private Sub CommandButton1_click()
ActiveCell.FormulaR1C1 = UserForm1.TextBox1.Text 
End Sub

The hotkey will be useful when I add in more fields and buttons...

Also how do i set the 'Escape' button to close/hide the form ?

Was it helpful?

Solution

To set the 'Escape' key to activate your button to close/hide the form: First, you need a button whose Click event hides your form. Then set the 'Cancel' property of that button to True.

When your form is displayed, and you press Esc, the form will close.

For a 'HotKey', set the Accelerator property of your button to a letter, then when your form is open, if you press Alt+[your letter], the Click event of that button will fire.

OTHER TIPS

The only way to do that is to add a KeyUp event for each control of your form which calls a central keyboard handling routine:

Option Explicit

Private Sub CommandButton1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    HandleKey KeyCode
End Sub

Private Sub CommandButton2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    HandleKey KeyCode
End Sub

Private Sub UserForm_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    HandleKey KeyCode
End Sub

Private Sub HandleKey(KeyCode As MSForms.ReturnInteger)
    MsgBox KeyCode
    Select Case KeyCode
    Case 112 'F1
        'Do something because F1 was pressed
    Case 113 'F2
        'Do something because F2 was pressed
    Case 114 'F3 etc.
    End Select
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top