Re-Set Focus to the proper field...

BrianExcel

Well-known Member
Joined
Apr 21, 2010
Messages
975
I have a text box on a userform in which the user enters a 4-digit number and then presses 'Enter.' When the user presses enter the following code runs:

Code:
Private Sub txtCenter_Change()

Application.ScreenUpdating = False

    If KeyCode = vbKeyReturn Then
     btnCenterLookup_Click
        frmCenterLookup.txtCenter.SetFocus
    End If
End Sub

My problem is that the .setfocus command doesn't work. When the user hits enter, I don't need to erase the current value in the text box, but I basically want whatever 4-digit number the user enters next to overwrite the current one so the user can just enter a number and then press enter, enter another number, press enter again, etc.

What am I doing wrong?

PS - The btnCenterLookup_Click runs more code, but rather than having a button AND the enter code, which would require the same code twice, I wanted them to just press enter, so I left the button as not visible.
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
What would you recommend? I need it to function so that when the user presses enter the code runs, but then I need focus re-set to the same field.

Ideas?
 
Upvote 0
If you only have a TextBox and a hidden CommandButton try:

Code:
Private Sub txtCenter_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = vbKeyReturn Then
        With txtCenter
            .SelStart = 0
            .SelLength = Len(.Text)
            .SetFocus
        End With
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,602
Messages
6,179,848
Members
452,948
Latest member
UsmanAli786

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top