I have a number of fields on various forms that need data validation. If fields are empty (null), the form should not save and close, and the cursor should go to the appropriate field.
I don't want to re-write for every field on every form the same code again, so I created a public function (as standard module) doing the validation check:
Expand|Select|Wrap|Line Numbers
- Public Function ValidateField(ctl As Control, ctlLabel As String)
- 'Validate data entry: check for empty fields in required field
- Dim msg, nl, strID As String
- nl = vbNewLine
- msg = "Please enter valid data into field:" & nl
- 'Check field for null value and display message
- If IsNull(ctl) Or Trim(ctl & "") = "" Then
- MsgBox msg & ctlLabel, vbOKOnly, "Missing Data"
- ctl.SetFocus
- ctl = Nothing
- Exit Function '<<== THIS IS THE PROBLEM!!!
- End If
- End Function
On the form I have a "Save" button with the Click-command:
Expand|Select|Wrap|Line Numbers
- Private Sub cmdSave_Click()
- Call ValidateField(Me!Field1, "Company name")
- Call ValidateField(Me!Field2, "Family name")
- 'etc. for further fields
- 'Only if all validation is OK, further commands should be executed:
- ..... 'Whatever code here
- DoCmd.Close
- End Sub
In the public function the "Exit Sub" is not allowed. Is there a way to tell the function also to terminate the "Mother" Sub (in our case: the cmdSave_Click)???
Please also bear in mind that the public function will be executed from different forms, buttons (and thus subs), so I cannot hard-code something like "cancel the closing of form XY" into the function.
Of course I could write for each validation something like
If IsNull(Field1) then
Call ValidateField(Me!Field1, "Company name")
Else
Exit sub
End If
but this is exactly what I want to avoid! I do not want to have to write if...then statements for every single field I need to check, but only the one public function that does that for me!
Thanks for any help solving this problem!
blublu (Running Access 2003, VBA 6.5)