Set focus on controls of modeless form

  • Thread starter Thread starter Robert Crandal
  • Start date Start date
R

Robert Crandal

When I initially load my modeless form, the input focus
usually begins on my first textbox control (or any other
control).

However, if you click on the spreadsheet, then click
back to the modeless control, the input focus is lost
(ie. not set on any control). How can I set the
input focus back on Textbox1 if someone clicks on
the spreadsheet and then clicks back to the modeless form???

I already tried the following code, but it doesnt work:

Private Sub UserForm_Activate()
UserForm1.TextBox1.SetFocus
End Sub
 
Hi Robert,

I don't know why the following works. I suspect some kind of bug but use the
userform click event and then set the focus to another control first then to
the one you really want.

Private Sub UserForm_Click()
Me.TextBox2.SetFocus
Me.TextBox1.SetFocus
End Sub
 
Hi OssieMac,

The code below works, but it assumes that the user will click somewhere
WITHIN the userform. If the user clicks on the top title bar to
re-activate the userform that code will not work.

How can I detect if the form is activated by a click on the top title
bar??
 
I don't know the answer to that one Robert. I think that Excel is missing
something here and it should work.
 
Userforms do not expose a 'GotFocus' event, which is not the same as the
Userform's VBA Activate event.

Simplest approach would be with an OntIme macro to check which window is
currently active, which you can get with the GetForegroundWindow API.

If you need to know more accurately when user activates Excel or Userform,
or some other window (actually just beforehand), a low level hook along the
lines of the 'CBTProc Function' as demonstrated to you in one of your other
threads would keep you informed. Overkill I would have thought though for
this objective alone.

Regards,
Peter T
 
Back
Top