excel userform textbox cannot setfocus to itself

rberke
rberke used Ask the Experts™
on
simple form with only two textboxes.  Textbox1 accepts data, processes it and then tries to setfocus to itself so it can accept more data.  Textbox2 has other unrelated uses.


The following code did not work.  After data was entered, textbox2 would always get focus.

Private Sub Textbox1_AfterUpdate()
    debug.print textbox1.text ' actual processing program is irrelevant to today's post
    TextBox1.text = ""
    textbox1.setfocus
End Sub

The following code DID work fairly well.  Once the user starts entering data, they cannot exit the textbox until the data has been processed

The only problem is it is a little bit comlicated. If somebody has a better solution, please post and you will get the points.

Otherwise, I will PAQ this question tomorrow

------- my best solution so far -------------------

Dim CPUMadeChange As Boolean
Dim stopExit As Boolean
Private Sub Textbox1_AfterUpdate()
CPUMadeChange = True
TextBox1.text = ""  ' this fires the _change event. I use CPUMadeChange to keep it from
CPUMadeChange = False
End Sub
Private Sub Textbox1_Change()
If CPUMadeChange Then stopExit = True
End Sub

Private Sub Textbox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If stopExit Then
    Cancel = True
    stopExit = False
End If
End Sub

Private Sub TextBox3_Enter()
Stop
End Sub
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2011
Commented:
Can't you just use the Exit event and skip the AfterUpdate (which is IMO fairly pointless in VBA userforms)?
rberkeConsultant

Author

Commented:
That works great.

In the past I always used afterupdate and never exit.

So perhaps I should change to always using Exit and never AfterUpdate.

It sounds like your preference is to use Exit, but can you think of any situations where afterUpdate is better?

By the way, here is the much improved code

Private Sub Textbox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox1.text = "" Then Exit Sub
Debug.Print TextBox1
Cancel = True
TextBox1.text = ""
End Sub
Most Valuable Expert 2011
Top Expert 2011

Commented:
I don't think I've ever used AfterUpdate in a VBA userform that I can recall.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial