With the VBA code below, when the workbook 'Schedule Checks.xlsm' is closed an not open,…
- User
With the VBA code below, when the workbook 'Schedule Checks.xlsm' is closed an not open, I still get the message "DAILY SCHEDULE WORKBOOK WAS FOUND OPEN" The code is not correctly identifying when the workbook is closed.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wb As Workbook Dim scheduleFile As Workbook Dim scheduleFileFound As Boolean For Each wb In Workbooks If wb.Name = "Schedule Checks.xlsm" Then ' Workbook is open, proceed with your code Exit For End IfNext wb
On Error Resume Next Set scheduleFile = Workbooks("Schedule Checks.xlsm") On Error GoTo 0 If Err.Number = 0 Then ' Check for error specifically scheduleFileFound = True ' Workbook is open, display a message box with options Dim response As Integer response = MsgBox("DAILY SCHEDULE WORKBOOK WAS FOUND OPEN" & vbCrLf & vbCrLf & _ "YES to close it and Save Changes" & vbCrLf & _ "NO to close it and NOT Save Changes?", _ vbCritical + vbYesNo, "CLOSE OPEN WORKBOOK") If response = vbYes Then ' Close and save changes scheduleFile.Close SaveChanges:=True Else ' Close without saving changes scheduleFile.Close SaveChanges:=False End If Else ' Workbook is not open, proceed to the "Closer" section GoTo Closer End IfCloser: Application.ScreenUpdating = False ThisWorkbook.Worksheets("Today").Range("G2").Value = "no" ThisWorkbook.Worksheets("Today").Range("G21").Value = "" ThisWorkbook.Worksheets("Notes").Activate Application.ScreenUpdating = True
End Sub
- Assistant
The issue with the code is that it is checking for the open workbook using the workbook name, but the workbook name includes the file extension (.xlsm) which is not included in the window title when the workbook is open.
To fix this issue, you can modify the code to check the window title instead of the workbook name. Here's the updated code:
Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim wb As Workbook Dim scheduleFile As Workbook Dim scheduleFileFound As Boolean For Each wb In Workbooks If InStr(1, wb.Windows(1).Caption, "Schedule Checks") > 0 Then ' Workbook is open, proceed with your code Set scheduleFile = wb scheduleFileFound = True Exit For End If Next wb If scheduleFileFound Then ' Workbook is open, display a message box with options Dim response As Integer response = MsgBox("DAILY SCHEDULE WORKBOOK WAS FOUND OPEN" & vbCrLf & vbCrLf & _ "YES to close it and Save Changes" & vbCrLf & _ "NO to close it and NOT Save Changes?", _ vbCritical + vbYesNo, "CLOSE OPEN WORKBOOK") If response = vbYes Then ' Close and save changes scheduleFile.Close SaveChanges:=True Else ' Close without saving changes scheduleFile.Close SaveChanges:=False End If End If Application.ScreenUpdating = False ThisWorkbook.Worksheets("Today").Range("G2").Value = "no" ThisWorkbook.Worksheets("Today").Range("G21").Value = "" ThisWorkbook.Worksheets("Notes").Activate Application.ScreenUpdating = True End Sub