I am using Workbook_BeforeSave event to check whether all the mandatory cells are filled before saving the document. If there are any mandatory cells that are empty, it will ask the user to fill them before saving the document.
The code is working as expected. But the only issue I am facing is that when user clicks Close(X) without filling the mandatory cells, excel is prompting whether the user wants to Save / Don't Save the changes before closing the workbook or Cancel the prompt and if the user clicks Save, Workbook_BeforeSave event is called and it informs the users that there are empty mandatory cells to be filled and closes the document abruptly.
I don't want to close the workbook when the user clicks Save while there are mandatory cells to be filled. If he clicks Don't Save its ok close the document without filling the mandatory cells.
How to do this.
Code,
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wb As Workbook
Dim ws1 As Worksheet
Dim userange, userange1, userange2 As Range
Dim iCell, positionrng As Range
Dim usedrow As Long
Dim usecolumn As Long
Dim rowposition As Long
Dim ws1lastrow, lastcol As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets("CAPEX FY21-22")
rowposition = 9
criteria = ws1.Range("BM9").Value
investment = ws1.Range("BT9").Value
roi = ws1.Range("BU9").Value
justification = ws1.Range("BW9").Value
ws1lastrow = ws1.Cells(Rows.Count, criteria).End(xlUp).Row
If ws1.Cells(rowposition, criteria).Value = "" Or ws1.Cells(rowposition, criteria).Value = Empty Then
GoTo exiting:
End If
Set userange1 = ws1.Range(ws1.Cells(rowposition, criteria), ws1.Cells(ws1lastrow, investment))
Set userange2 = ws1.Range(ws1.Cells(rowposition, roi), ws1.Cells(ws1lastrow, justification))
Set userange = Union(userange1, userange2)
For Each iCell In userange
If IsEmpty(iCell) = True Then
MsgBox ("Document cannot be saved!" & vbCrLf & "Mandatory cell(s) are empty!" & vbCrLf & "Please fill the highlighted cell to save.")
iCell.Activate
ActiveCell.Interior.Color = RGB(255, 255, 0)
Application.Goto ActiveCell, Scroll:=True
Cancel = True
Exit Sub
GoTo exiting:
End If
Next
saves:
MsgBox ("Document saved")
exiting:
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
While workbook is closing, an event BeforeClose gets called. The solution might be to put your validation logic there, and prevent workbook from closing when validation didn’t succeed.