I've been working with VBA in a template spreadsheet to prevent users from saving without certain fields being populated. As the time has gone by, I've been requested to make a few stipulations on the entries being required based on the contents of other cells. I have a bunch of data validation with drop-downs in my spreadsheet, so I'm too concerned about the targeting specific phrases to bypass requiring an entry to save the document. I need to keep all of the existing mandatory fields, but add in the exemptions below.
I currently have column M as a required columns if another of the other specified columns in that row are filled. Per above, trying to make column M required for all scenarios except the following. In the attempt to simplify the criteria, I've substituted the actual text required in both scenarios:
- Column M is not required if column G = "Alpha" and column J = "Bravo".
- Column M is not required if if the last four characters in column H are "abcd".
My current code is below. This is revised from when the question was initially asked
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Const CHECK_RNG As String = "A1:D1,F1:K1,N1:N1,S1:Y1,AE1"
Dim ws As Worksheet
Dim rg As Range, c As Range
Dim bCanSave As Boolean, sep As String
Dim sWarning As String, sMissing As String, r As Long, ct As Long
Set ws = Sheets("Main")
sWarning = "File not saved!" & vbNewLine & "Mandatory cells missing in rows: " & vbNewLine
bCanSave = True
For r = 2 To 1000
Set rg = ws.Rows(r).Range(CHECK_RNG)
ct = Application.CountA(rg)
If ct > 0 And ct <> rg.Cells.Count Then
bCanSave = False
sMissing = sMissing & sep & r
sep = ","
End If
Next r
If Not bCanSave Then
MsgBox sWarning & sMissing, vbExclamation
Cancel = True
End If
End Sub