Execute a function when any text field changes in the form? MS Access

Is there a way to run a function in VBA when the item data changes in any control? I tried Form_AfterUpdate and Form_DataChange but they don't do anything

+3


source to share


2 answers


You dont need to enter code After update / change event of controls, Key preview

The KeyPreview property can be used to indicate whether the form level keyboard events are raised before the keyboard event controls. Read / Write Boolean.

Use it carefully.



For example, using KeyPreview:

 Private Sub Form_KeyPress(KeyAscii As Integer)
      MsgBox "You pressed a key"
 End Sub

      

key preview

+1


source


Step 1. Create a function

Function DoStuff()
    Call RunMySub
End Function

      

Step 2: Create a macro (Named RunMyCode)

RunCode
  Function Name DoStuff()

      



Step 3: change the Form_Load () sub

Private Sub Form_Load()
Dim cControl As Control
On Error Resume Next
    For Each cControl In Me.Controls
        if cControl.ControlType = 109 'this is for text boxes
            'Depending on what your code does you can use all or some of these:
            cControl.OnExit = "RunMyCode"
            cControl.OnEnter = "RunMyCode"
            cControl.OnLostFocus = "RunMyCode"
            cControl.OnGotFocus = "RunMyCode"
            If cControl.OnClick = "" Then cControl.OnClick = "RunMyCode"
        end if
    Next cControl
On Error GoTo 0

      

You can use any of the attributes of the control, I find the "OnExit / OnEnter" and "OnLostFocus / OnGotFocus" pairs to be the most effective. I also like "OnClick", but I use an if statement so I don't overwrite actions (for buttons and stuff). There are a dozen other methods that you can assign a control action to - I'm sure you can find one or more that fit your purpose.

Note. I'm using a buggy wrapper because I'm wrapping this code with several different types of controls, and not all have all methods.

0


source







All Articles