Consulting

Results 1 to 2 of 2

Thread: Keycode 13 only for textbox input on userform

  1. #1
    VBAX Expert Dave's Avatar
    Joined
    Mar 2005
    Posts
    795
    Location

    Keycode 13 only for textbox input on userform

    I can't seem to resolve how to keep the focus in a textbox of a userform when using the enter key (Keycode 13). What is supposed to happen is: you enter data into the userform textbox then select enter to transfer the data to a worksheet in 3 seconds (application ontime). If you select an image control on the userform before the 3 secs, then the data transfer is cancelled. This works. What doesn't work is if you again select enter before the 3 secs, the focus goes to the command button and runs that routine. So, how to keep the focus on the textbox so that only the textbox receives the keycode 13 input? I set up an empty wb with a Sheet1, a module1, and a userform1 with a command1, textbox1 and image1. The following code will demonstrate my frustrations. Thanks for any suggestions and assistance. Dave
    module code...
    Public StopCnt As Boolean, Cnt As IntegerPublic Sub update()
    If Not StopCnt Then
    Cnt = Cnt + 1
    Sheets("sheet1").Range("A" & Cnt).Value = UserForm1.TextBox1.Text
    UserForm1.TextBox1.Text = vbNullString
    MsgBox "Update"
    End If
    End Sub
    Userform code...
    Private Sub CommandButton1_Click()
    MsgBox "Command"
    End Sub
    
    
    Private Sub Image1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                              ByVal X As Single, ByVal Y As Single)
    StopCnt = True
    UserForm1.TextBox1.Text = vbNullString
    UserForm1.TextBox1.SetFocus
    End Sub
    
    
    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
    Application.OnTime Now + TimeValue("00:00:03"), procedure:="update"
    StopCnt = False
    UserForm1.TextBox1.SetFocus
    End If
    End Sub

  2. #2
    VBAX Expert Dave's Avatar
    Joined
    Mar 2005
    Posts
    795
    Location
    Fairly simple solution. To keep the focus on the textbox after keycode 13 just set the keycode to 0. Solved. Dave
    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
    KeyCode = 0
    Application.OnTime Now + TimeValue("00:00:03"), procedure:="update"
    StopCnt = False
    UserForm1.TextBox1.SetFocus
    End If
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •