Results 1 to 5 of 5
  1. #1
    Lounger
    Join Date
    Oct 2008
    Location
    London
    Posts
    39
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I have a VB form with a textbox on it
    I want the user to enter a certain length of data say 6 characters. The must not be able to proceed with out entering the correct data required
    If i say
    if len (textbox.text) <> 3 then
    msgbox ()
    me.texttbox.setfocus
    It does not prevent the user proceeding

    Any advice please

  2. #2
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts
    You can check this in the QueryClose event of the userform, and set Cancel = True if the text box doesn't contain 6 characters:

    Code:
    Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
      If Not Len(Me.TextBox1) = 6 Then
        Me.TextBox1.SetFocus
        MsgBox "Please enter exactly 6 characters!", vbExclamation
        Cancel = True
      End If
    End Sub

  3. #3
    Super Moderator
    Join Date
    Dec 2000
    Location
    New York, NY
    Posts
    2,970
    Thanks
    3
    Thanked 29 Times in 27 Posts
    Alternatively, you can use the Textbox's own Exit event to prevent the user from leaving - this doesn't require SetFocus:

    Code:
    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
       If Not Len(TextBox1.Text) = 6 Then
          MsgBox "Please enter exactly 6 characters!", vbExclamation
          Cancel = True
       End If
    End Sub
    Gary

  4. #4
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts
    The Exit event of the text box will work well if the text box is the first control in the tab order. But if it isn't, the user can skip it and close the form without having to fill in the text box.

  5. #5
    Super Moderator
    Join Date
    Dec 2000
    Location
    New York, NY
    Posts
    2,970
    Thanks
    3
    Thanked 29 Times in 27 Posts
    Good point. I think both procedures are needed here.

Posting Permissions

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