Search code examples
vbams-access

AutoKeys in Access VBA to Open/Close a form


I've created a form called frm_autokeys where the user is given an bunch of options such as export to Word, export to Excel etc (All of these functions work).

I want the form to open and close when the user presses F4. I've wrote a macro (hate them would rather have this in VBA code if there's a way?) called AutoKeys to have the form open but can't write an if statement to check if the form is open or not in order to call the close function for the form.

Has anyone worked out a way to do this?


Solution

  • You can do this by checking if the form is loaded, and using an If block with an Else block:

    Open an If block.

    Condition: CurrentProject.AllForms!frm_autokeys.IsLoaded
    Action: CloseWindow Form frm_autokeys
    
    Else block connected to If block
    Action: OpenForm frm_autokeys
    

    The AXL:

    <?xml version="1.0" encoding="UTF-16" standalone="no"?>
    <UserInterfaceMacros xmlns="http://schemas.microsoft.com/office/accessservices/2009/11/application">
        <UserInterfaceMacro MinimumClientDesignVersion="14.0.0000.0000">
            <Statements />
            <Sub Name="{F4}">
                <Statements>
                    <ConditionalBlock>
                        <If>
                            <Condition>[CurrentProject].[AllForms]![frm_autokeys].[IsLoaded]</Condition>
                            <Statements>
                                <Action Name="CloseWindow">
                                    <Argument Name="ObjectType">Form</Argument>
                                    <Argument Name="ObjectName">frm_autokeys</Argument>
                                </Action>
                            </Statements>
                        </If>
                        <Else>
                            <Statements>
                                <Action Name="OpenForm">
                                    <Argument Name="FormName">frm_autokeys</Argument>
                                </Action>
                            </Statements>
                        </Else>
                    </ConditionalBlock>
                </Statements>
            </Sub>
        </UserInterfaceMacro>
    </UserInterfaceMacros>
    

    Of course, you can defer to VBA by using the RunCode action in macros, but you can't directly handle keypresses in VBA (without a lot of hackery, that is, since VBA can use WinAPI anything is possible)