i am typing below code in each and every date text box keypress event to allow numbers and back slash keys only.

can any function or subroutine be created to avoide typing same code again and again in the project.

Private Sub Text1_KeyPress(KeyAscii As Integer)


Dim ch As String
ch = Chr$(KeyAscii)
If Not ( _
(ch >= "0" And ch <= "9") Or _
KeyAscii = 8 Or _
KeyAscii = 13 Or _
KeyAscii = 84 Or _
KeyAscii = 116 Or _
KeyAscii = 47) Then
    
' Cancel the character.
KeyAscii = 0
End If

If KeyAscii = 116 Or KeyAscii = 84 Then
KeyAscii = 0
Text1.Text = Date
End If

End Sub

Recommended Answers

All 2 Replies

Find code below however this may not be the best way of achieving what you want.

In the LostFocus event, you can check if they have entered a valid date as follows

if not isdate(text1.text) then
msgbox "Please enter a valid date"
text1.setfocus
text1.selstart = 0
text1.sellength = len(text1.text)
end if

however if you want to stick to your original here is the code.

Private Sub Text1_KeyPress(KeyAscii As Integer)

Keyascii = CheckChar(KeyAscii)
end sub

public function CheckChar(KeyAscii as integer) as integer
Dim ch As String 
CheckChar = KeyAscii
ch = Chr$(KeyAscii)
If Not ( _(ch >= "0" And ch <= "9") Or _KeyAscii = 8 Or _KeyAscii = 13 Or _KeyAscii = 84 Or _KeyAscii = 116 Or _KeyAscii = 47) Then ' Cancel the character.
CheckChar = 0
End If 
If KeyAscii = 116 Or KeyAscii = 84 Then
CheckChar= 0
End If
end function

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.