0

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

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by PM312
0

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

Edited by ChrisPadgham: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.