I have written three different Private Sub functions, all of which do the same thing Private Sub txt_noRooms_KeyPress and Private Sub txt_length_KeyPress ensure that the user can only type in values 1 to 9 into the referenced text fields whereas Private Sub txt_studentNo_KeyPress allows the user to type in values 0 to 9 into the referenced text field.
Is there any way I can merge these three functions and have them still support the referenced cells and maintain the same conditions? I want to do this for the purpose of making the code more efficient.
Private Sub txt_noRooms_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_noRooms
Select Case KeyAscii
Case Asc("1") To Asc("9")
Case Asc("-")
If InStr(1, Me.txt_noRooms.Text, "-") > 0 Or Me.txt_noRooms.SelStart > 0 Then
KeyAscii = 0
End If
Case Asc(".")
If InStr(1, Me.txt_noRooms.Text, ".") > 0 Then
KeyAscii = 0
End If
Case Else
KeyAscii = 0
End Select
End Sub
Private Sub txt_length_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_length
Select Case KeyAscii
Case Asc("1") To Asc("9")
Case Asc("-")
If InStr(1, Me.txt_length.Text, "-") > 0 Or Me.txt_length.SelStart > 0 Then
KeyAscii = 0
End If
Case Asc(".")
If InStr(1, Me.txt_length.Text, ".") > 0 Then
KeyAscii = 0
End If
Case Else
KeyAscii = 0
End Select
End Sub
Private Sub txt_studentNo_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
' Restrict entry to txt_studentNo
Select Case KeyAscii
Case Asc("0") To Asc("9")
Case Asc("-")
If InStr(1, Me.txt_studentNo.Text, "-") > 0 Or Me.txt_studentNo.SelStart > 0 Then
KeyAscii = 0
End If
Case Asc(".")
If InStr(1, Me.txt_studentNo.Text, ".") > 0 Then
KeyAscii = 0
End If
Case Else
KeyAscii = 0
End Select
End Sub
You can set one private function and call it from each keypress: