Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 294
  • Last Modified:

How to code to stop saving Excel workbook in "Workbook_BeforeSave"

I added some codes inside "Workbook_BeforeSave" to check something.  If not meeting my requirements, I used "Exit Sub".  But the workbook was still saved.  Is anyway I can stop saving process?
0
jjxia2001
Asked:
jjxia2001
  • 2
2 Solutions
 
Martin LissRetired ProgrammerCommented:
Put

Cancel = True

in the code at the point you know something's wrong.
0
 
jjxia2001Author Commented:
I added it in and didn't work.  See my code below.


Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    On Error GoTo Errorhandler
   
               
        If Range("AccountNumber") = "" Then
        MsgBox ("Please enter SAI Number")
        Range("AccountNumber").Select
        Cancel = True
        Exit Sub
        End If
   
        If Range("PolicyEffectiveDate") = "" Then
        MsgBox ("Please enter Policy Effective Date")
        Range("PolicyEffectiveDate").Select
        Cancel = True
        Exit Sub
        End If
       
        Dim bln As Boolean
        bln = UserHasAccess()
       
        If bln Then
       
            Call getUserID
   
            frmWaitBox.Show modal
            subRemoveCloseButton frmWaitBox
            frmWaitBox.Repaint

            Call Driver
       
            Unload frmWaitBox
                   
            Exit Sub
        Else
            MsgBox ("Archiving of responses failed - possibly because you are offline.  Your Knowledge Edge results are still valid.")
            Exit Sub
        End If
   

Errorhandler:
    MsgBox ("Archiving of responses failed - possibly because you are offline.  Your Knowledge Edge results are still valid.")
 
    lngMessResult = SendErrorEmail("Error" + " contains one or more invalid range references")
 
End Sub
0
 
Martin LissRetired ProgrammerCommented:
There's probably something wrong with your range tests because this works for me.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Const TEST = 5

If TEST = 5 Then
    Cancel = True
    MsgBox "You can't close me"
    Exit Sub
End If

End Sub

Open in new window


To find out, put a breakpoint on the If Range("AccountNumber") = "" Then line and when the code gets there, press F8 repeatedly to trace the code execution line by line.

If you need it here's an article I wrote on how o use the Debugger.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now