I have a form on an Excel sheet that has two mandatory cells which are often left incompleted by users. I have the following code which won’t allow the user to save the sheet if the cells are not completed, will highlight them in red and display a message box:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
ok As Boolean
Dim xlSht As Worksheet
OK = False
Set xlSht = ThisWorkbook.Worksheets("Changes Form")
'Cell 1
If xlSht.Range("B13") = "" Then
xlSht.Range("B13").Interior.Color = RGB(255, 0, 0)
ok = True
Else
xlSht.Range("B13").Interior.ColorIndex = xlNone
ok = False
If xlSht.Range("E13") = "" Then
xlSht.Range("E13").Interior.Color = RGB(255, 0, 0)
ok = True
Else
xlSht.Range("E13").Interior.ColorIndex = xlNone
ok = False
End If
End If
If OK = True Then
MsgBox "Please review the highlighted cells and ensure the fields are populated."
Cancel = True
End If
End Sub
The code works however if there are no entries in both cells then it only colours cell B13. I think once the ‘ok = True’ bit of the code runs for B13, it skips the rest of the code to the end. I am unsure how to amend it so that both cells will be highlighted.
I thought about alerting the user through Data Validation however I have a listbox in both cells so I am not sure if it is still possible that way.
Thanks in advance for any help.
Replace your code with the below. If the first value is empty then you are missing the logic for the second. Also, no need to set to false if there is a value. Final thing I changed was your “ok” boolean to cellsNotPopulated so its more readable.