Results 1 to 4 of 4

Thread: Restrict # of Decimal Positions in a Text Box

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2001
    Location
    London, Ontario
    Posts
    5

    Restrict # of Decimal Positions in a Text Box

    Does anyone have sample code on how I can restrict a user from
    entering no more than 1 digit following a decimal point in a text
    box? For example:

    89.9 is valid
    91 is valid

    93.87 is invalid

    I can't seem to find a slick way to do this.

    Thanks,
    Ron

  2. #2
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649
    The following code only allows digits and a period (and only one period) with only one decimal after that period.
    Be aware that this code only consider a period as a decimal sign so it's not localized for countries that use other signs (like commas in Scandinavia).
    VB Code:
    1. Private Sub Text1_KeyPress(KeyAscii As Integer)
    2.     Dim nPos As Long
    3.    
    4.     Select Case KeyAscii
    5.         Case vbKeyBack
    6.             'We allow this so we do nothing
    7.         Case vbKey0 To vbKey9, Asc(".")
    8.             nPos = InStr(Text1, ".")
    9.             If nPos Then
    10.                 If Text1.SelStart > nPos Or KeyAscii = Asc(".") Then
    11.                     KeyAscii = 0
    12.                 ElseIf Text1.SelStart = nPos And Len(Text1.Text) > nPos Then
    13.                     KeyAscii = 0
    14.                 End If
    15.             End If
    16.         Case Else
    17.             'we dont allow any other characters
    18.             KeyAscii = 0
    19.     End Select
    20. End Sub
    Best regards

  3. #3

    Thread Starter
    New Member
    Join Date
    Jun 2001
    Location
    London, Ontario
    Posts
    5
    Thanks Joacim. Your code works like a charm.

    Ron

  4. #4
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649
    Yes, as you might have noticed is that even if you typed one decimal you can still type in new digits before the decimal point.

Posting Permissions

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



Click Here to Expand Forum to Full Width