Set focus on controls of modeless form

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
 
O

OssieMac

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
 
R

Robert Crandal

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??
 
O

OssieMac

I don't know the answer to that one Robert. I think that Excel is missing
something here and it should work.
 
P

Peter T

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top