Search code examples
ms-accessms-access-2016

To paste a macro from Stack Overflow into Access


My question seems to be very silly, but I haven't found solution myself.

Is there a way to simply paste a macro (example) from Stack Overflow in Access? Or, alternatively, paste it from Access to Stack Overflow?

I know, it is very easy in Word and Excel. But I can't understand how to do it in Access.


Solution

  • Basic questions certainly deserve asking, if they're not duplicates.

    There are a couple of different cases:

    1. Add VBA on a form event (this case)

      • Open up the form in design view
      • Identify the control you want to add the macro to (the part before the _ is the control name, the part after the _ is the event name, so the KeyDown event on the form control.

      • Identify the event you want to add code to on the event pane

      • Press the builder ... thing
      • Choose Code Builder and press OK.
      • You will see some event code has already been added. Replace that with the copy-pasted code.

    enter image description here

    1. Add VBA (function or sub) outside of a form (triggered elsewhere, such as a user-defined function for use in queries)
      • Open up the VBA editor by hitting Alt + F11
      • Choose Insert -> Module in the top bar
      • Paste the code
    2. Paste a normal, non-VBA macro using AXL
      • Create a macro on the create tab on the ribbon
      • Select the body of the macro by clicking the blank space inside it (not the area where you can create new controls)
      • Hit Ctrl + V to paste
    3. Paste an Access data macro using AXL
      • Open the table you want to add the data macro to in design view.
      • In the ribbon, click Create data macros, choose and click the right event. You can identify the event by looking at the event property of the datamacro tag, for example <DataMacro Event="AfterInsert"> = On After Insert
      • Select the body of the macro by clicking the blank space inside it (not the area where you can create new controls)
      • Hit Ctrl + V to paste

    Note that questions about non-VBA macros rarely contain the AXL necessary to paste it. Pasting AXL is somewhat contra-intuitive, as you don't paste it in a textbox and the result isn't text.