Text/Number Validation in Text Boxes

Vishesh's picture
Copy the following code in a general module and call it from any of the textboxes' keypress event.

For its usage download the attachment.

Function AllowTextOnly(AscKey As MSForms.ReturnInteger, Optional blnConvUpperCase _
    As Boolean = False, Optional blnAllowSpace As Boolean = True) As Integer
 
    Select Case AscKey
 
    Case Asc("a") To Asc("z"), Asc("A") To Asc("Z"), Asc(" ")
 
        If blnConvUpperCase Then
 
            AllowTextOnly = Asc(UCase(Chr(AscKey))) 'Convert to uppercase

        Else
 
            AllowTextOnly = AscKey
 
        End If
 
    Case Else
 
        AllowTextOnly = 0
 
    End Select
 
    If blnAllowSpace = False And AscKey = Asc(" ") Then
 
        AllowTextOnly = 0
 
    End If
 
End Function
 
 
 
Function AllowNumOnlyDecimalOptional(strText As String, AscKey As _
    MSForms.ReturnInteger, Optional blnAllowDecimal As Boolean = False) As Integer
 
    Select Case AscKey
 
    Case Asc(0) To Asc(9)
 
        AllowNumOnlyDecimalOptional = AscKey
 
    Case Else
 
        If blnAllowDecimal = True And AscKey = Asc(".") Then
 
            AllowNumOnlyDecimalOptional = AscKey
 
        Else
 
            AllowNumOnlyDecimalOptional = 0
 
        End If
 
    End Select
 
    If Len(strText) > 0 Then
 
        If Not IsNumeric(strText & Chr(AscKey)) Then
 
            AllowNumOnlyDecimalOptional = 0
 
        End If
 
    End If
 
End Function
 
 
 
Function AllowNumOnlyNoDecimal(AscKey As MSForms.ReturnInteger) As Integer
 
    Select Case AscKey
 
    Case Asc(0) To Asc(9)
 
        AllowNumOnlyNoDecimal = AscKey
 
    Case Else
 
        AllowNumOnlyNoDecimal = 0
 
    End Select
 
End Function
AttachmentSize
TextBoxDataEntryValidation.xls43.5 KB