Prevent cursor/focus from moving

S

Slim Slender

Create a small Userform. Put two TextBoxes in it. Add the following
code.

Private Sub UserForm_Initialize()
TextBox1.Value = "0.00"
TextBox2.Value = "0.00"
End Sub

Private Sub TextBox1_KeyDown(ByVal KeyCode _
As MSForms.ReturnInteger, _
ByVal Shift As Integer)

Dim sHours As String
Dim v As Integer

Select Case KeyCode
Case 37 ' Left
v = -1
Case 38
v = 4
Case 39 ' Right
v = 1
Case 40
v = -4
Case Else
v = 0
End Select

sHours = TextBox1.Text
If IsNumeric(sHours) And v <> 0 Then
sHours = sHours + v * 0.25
If sHours < 0 Then sHours = 0
TextBox1.Text = Format(sHours, "#0.00")
End If
End Sub

Private Sub TextBox2_KeyDown(ByVal KeyCode _
As MSForms.ReturnInteger, _
ByVal Shift As Integer)

Dim sHours As String
Dim v As Integer

Select Case KeyCode
Case 37 ' Left
v = -1
Case 38
v = 4
Case 39 ' Right
v = 1
Case 40
v = -4
Case Else
v = 0
End Select

sHours = TextBox2.Text
If IsNumeric(sHours) And v <> 0 Then
sHours = sHours + v * 0.25
If sHours < 0 Then sHours = 0
TextBox2.Text = Format(sHours, "#0.00")
End If
End Sub

When the boxes are stacked, pressing the up arrow in the upper box has
the desired effect but pressing the down arrow increments the amount
by -1.00 then the cursor/focus jumps to the lower box. Similar
opposite behavior in the lower box. This does not happen when the
boxes are side-by-side. Can I control this, keep cursor/focus in boxes
when stacked?
 
C

Chip Pearson

Put

KeyCode = 0

at the end of both of your KeyDown events. This cancels the keystroke.

Cordially,
Chip Pearson
Microsoft Most Valuable Professional,
Excel, 1998 - 2010
Pearson Software Consulting, LLC
www.cpearson.com
 

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