This usually goes in the Worksheet_Change event, to trap errors before it goes any further.
'validated? strType = Cells(Range("Fieldlist").Row + 1, Target.Column).Value intType = Cells(Range("Fieldlist").Row + 2, Target.Column).Value If ValidateData(Target.Value, strType, intType) Then 'do this if data is valid Call HighlightCell(Target) Else Target.Select Exit Sub End If
Function ValidateData(varData As Variant, strType As String, intType2 As Integer) As Boolean ValidateData = True 'if text then test for length If strType = "202" And Len(varData) > intType2 Then MsgBox "The text is too longer than " + Str(intType2) + " characters" ValidateData = False Exit Function End If 'if a Date is not a Date (IDEA: and check if DATE IN THIS CENTURY?) If strType = "7" Then If Not IsDate(varData) Then MsgBox "This does not look like a proper Date " '+ (varData) + "." ValidateData = False End If End If 'if a Number is not a Number If strType = "3" Then If Not IsNumeric(varData) Then MsgBox "This does not look like a Number " '+ (varData) + "." ValidateData = False End If End If 'NB: cell format will change to Date if a date is entered in a Number cell. So, replace format from RowMask? End Function
Improvements:
- Check if a Date is in a date range. eg. this century.
- Show the dubious data in the message.
- Excel will change the Cell Format to Date if the entered data is a Date. Change this back. Ideally from the RowMask.
- Check for other types of data. eg. True/False