'Require all variables to be defined
Option Explicit
'Declare public variables
Dim NotEntered As String
Dim ErrorCount As Integer
Public Validated As Boolean
Sub validate()
'Decalre variables
Dim n, result
'Reset variables in case this is not the first time it has been run
NotEntered = ""
ErrorCount = 0
'For each Named Range in the workbook, run the function to check if it is empty
For Each n In ActiveWorkbook.Names
If Not Left(n.Name, 3) = "nr_" Then
RangeIsEmpty (n.Name)
End If
Next n
If ErrorCount = 0 Then
result = MsgBox("All required fields populated.", vbOKOnly, "Form Validated Ok")
Validated = True
ElseIf ErrorCount = 1 Then
result = MsgBox("Please enter some data for the following field: " & vbCrLf & NotEntered, vbExclamation, "Missing Data")
Else
result = MsgBox("Please enter some data for the following fields: " & vbCrLf & NotEntered, vbExclamation, "Missing Data")
End If
End Sub
Function RangeIsEmpty(ByVal SourceRange As String) As Boolean
'Declare variable
Dim myRange
'Set the variable to the range specified by the named range
Set myRange = ActiveSheet.Range(SourceRange)
'Count the number of blank cells in the range. If True then there are no populated cells
RangeIsEmpty = (WorksheetFunction.CountBlank(myRange) = myRange.Count)
'If no populated cells, set public variable to the name of the named range
If RangeIsEmpty = True Then
NotEntered = NotEntered & vbCrLf & SourceRange
ErrorCount = ErrorCount + 1
End If
End Function