Focus in User Form

D

dsc

I have a user form with a text box and several command buttons.

I'd like to have the focus on the text box when the form initializes,
preferably with the default text selected, so the user can just start
typing. Can't figure out how to do it.

Also, after typing in the text box, hitting "enter" just puts a line feed in
instead of accepting the text and continuing with the macro, as happens with
an InputBox. Is there any way to fix that?

Thanks in advance.
 
J

Jay Freedman

To follow up Malcolm's reply, the EnterKeyBehavior property of the text box
should have the value False, which is the default. The only way to get a new
line in the text box when you press Enter is to set that value to True.

As for the focus/selection part of your question... The text box will
automatically receive focus at initialization if you give it a TabIndex
value of 0 (or if all the controls with lower values than the text box have
their TabStop property set to False, such as labels). If you can't do that,
then you can include the text box's .SetFocus method in either
Userform_Initialize() or Userform_Activate().

To get the default value to be selected, use the text box's .SelStart and
..SelLength properties in the Userform_Initialize() or Userform_Activate()
procedure. For example:

Private Sub UserForm_Initialize()
With tbxEntry
.Text = "Hello World"
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
 
D

dsc

Thank you, Malcolm and Jay. I'm almost all fixed up.

I have a big "duh" coming my way, though.

I didn't tell the macro what I wanted it to do when I press enter with the
focus on the text box. Guess I thought it was going to read my mind.

What it does now when I hit enter is to pass the focus like the tab key
does.

How do I make it execute code when I press enter with the focus on the text
box?

The help file says to use KeyDown or KeyUp, but the help on those events
doesn't even mention the enter key.

Thanks again.
 
M

Malcolm Smith

Ah, in that case what you want is to set the .Default property of the
cmdOK button, or whatever you've called it, to True This then does what
you want.

Whilst you're at it, set the .Cancel property of your cancel button to
..True. This will act as if that button was clicked if the user hits the
Cancel key.

- Hope that this helps
Malc
 
D

dsc

Thanks. You've been a great help.

Had a bit of a problem with the macro running across my network, but that
seems to have been a hardware program with the hub. Had me going for a
while, though.
 

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