Solved Running a public sub when form gets focus

dobseh

Member
Local time
Today, 15:00
Joined
Jul 9, 2022
Messages
49
I've got a form that is essentially a switchboard with a series of buttons that are a user journey through a process. Each button opens another form or report, some of these forms are a popup, others are a fullpage form, one button can return just a msgbox message if certain criteria are met. I'm trying to execute a piece of code that runs every time the user returns to the main form, but I cannot work out which event actually fires when this occurs. "On got focus" doesn't work because there are enabled buttons on the form so it never gets the focus.

I had though "On activate" would fire, and it does for the forms which are not a pop-up, but for both the msgbox and the pop-ups it does not. I could probably work around this by changing the active window away from the main form before I open the pop-up or fire the msgbox then move it back when they exit, but this seems a little hacky. What event(s) should I be using in this situation or is there a better way to do this?
 
One method I use is to use a form instance with Withevents. This all goes in the calling form.

Top of calling form module -
Code:
Dim WithEvents MyForm as form

Code:
private sub SomeButton_Click()

     docmd.openform "SomeForm"

     set MyForm = forms("SomeForm")

     MyForm.OnClose = "[Event Procedure]"

end sub

Code:
Private sub MyForm_Close()

' whatever code you want to run goes here

     set MyForm = Nothing

End Sub

When the called form closes it will run the code in Private sub MyForm_Close()

here's a quick example
 

Attachments

Last edited:
One method I use is to use a form instance with Withevents. This all goes in the calling form.

Top of calling form module -
Code:
Dim WithEvents MyForm as form

Code:
private sub SomeButton_Click()

     docmd.openform "SomeForm"

     set MyForm = forms("SomeForm")

     MyForm.OnClose = "[Event Procedure]"

end sub

Code:
Private sub MyForm_Close()

' whatever code you want to run goes here

     set MyForm = Nothing

End Sub

When the called form closes it will run the code in Private sub MyForm_Close()

here's a quick example
That does the job perfectly, thank you kindly!
 

Users who are viewing this thread

Back
Top Bottom