how to use keydown event in VBA, with different key combinations?


  • hello , thanks for reading.

    I am making a project in Excel , where i have several userforms.

    i want to put keydown event on any userform, so that it will unload and other one will show.

    for example ..

    if keycode =vbkeyf1 then
          unload userform1

    elseif keycode = vbkeyf4 then
          unload userform1


    the above code works fine........I now want to use key combination e.g. shift+f1 or shift+f2 to trigger keydown event and do the same.

    please help.
    Sunday, October 04, 2009 12:08 AM


  • Hi,

    You need to check the Shift argument.

    Help says the following,

    KeyDown, KeyUp Events@import url(/Office.css);

    The settings for Shift are:

    Constant Value Description
    fmShiftMask 1 SHIFT was pressed.
    fmCtrlMask 2 CTRL was pressed.
    fmAltMask 4 ALT was pressed.

    So you can use code like this

    Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

        Const SHIFT_MASK = 1
        Const CTRL_MASK = 2
        Const ALT_MASK = 4

        If KeyCode = vbKeyF1 Then
            If Shift = SHIFT_MASK Then
                MsgBox "F1+Shift"
            ElseIf Shift = (SHIFT_MASK Or CTRL_MASK) Then
                MsgBox "F1+Ctrl+Shift"
            End If
        End If
    End Sub

    • Marked as answer by Tim Li Friday, October 09, 2009 2:43 AM
    Sunday, October 04, 2009 10:54 AM