+ Reply to Thread
Results 1 to 4 of 4

BeforeClose code working in debug but sporadically in actual execution - how can I test it

Hybrid View

  1. #1
    Registered User
    Join Date
    09-03-2014
    Location
    Columbus, OH
    MS-Off Ver
    Office 2007
    Posts
    7

    Question BeforeClose code working in debug but sporadically in actual execution - how can I test it

    I hate asking this question as I fear it will get no replies but I'm completely stumped. I have some code that runs BeforeClose based on a user selection from a user form. It cleans up the entire workbook to delete any unused rows or formulas that are hidden or result in blank values. That works exactly as expected (the clean up code) but it's unpredictable when actually running before close.

    Every time I try to debug it using the ways I'm familiar with (stepping through the code, breaking out and testing pieces of code) it works fine. I get no error message when it doesn't work, I just reopen the file and the rows that should have been deleted weren't. When I try it a second time it works fine.

    My only guess at this point is that I have some other code that's disabling it somehow, but I sure thought I'd notice that when doing a debug...

    My second issue is that my code is complicated and messy because I'm still an apprentice Excel coder at best and I fear an expert will take one look at it and say "I can't work with this - it's too crazy" - so I'm sharing what I THINK you may need to help, but I expect you may need more detail o kindhearted soul who's willing to give this a look!

    Option Explicit 'require all variables to be declared
    Public wb1 As Object 'make wb1 a public variable for use in any sheet or sub in this module
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    bCancelClose = False 'reset the bCancelClose variable since "cancel" may have been previously selected
    
    On Error GoTo ErrorHandler
    
    If bDoNotRun = False Then 'If yes isn't selected in the message box in the "cancel" case, continue with the BeforeClose code
       
        Application.OnKey "{Up}" 'return the up key to normal function
        Application.OnKey "{Left}" 'return the left key to normal function
    
        If WorksheetExists("Quick Import Mapping") Then
            If Sheets("Location").Range("K2").Value = vbNullString Or Sheets("Location").Range("K2") = "NA" Then 'check to see if the file is in Order stage and bypass the below code if so
                If Sheets("Quick Import Mapping").Range("A13") <> vbNullString And (Sheets("Access").Range("A13") <> vbNullString Or Sheets("CPE").Range("A13") <> vbNullString) Then 'check to see if the user entered both Quick Import data AND other data and warn them
                    MsgBox "Your worksheet contains both Quick Import and Bulk Upload data." & vbNewLine & vbNewLine & _
                    "Please remove data from the Quick Import Mapping sheet OR the Product sheets before saving for upload."
                    Cancel = True 'Cancel the close to allow the user to delete the conflicting data
                    Exit Sub
                End If
            End If
        End If
    
        UserForm1.Show 'show the workbook close options window/userform
        If bCancelClose = True Then 'if the bCancelClose variable has been set to True via the UserForm code, cancel the close process
            Cancel = True
        End If
        Exit Sub
        
    ErrorHandler:
        MsgBox "Description: " & Err.Description & vbNewLine & _
            "Error Number: " & Err.Number & vbNewLine & _
            "Error at Line: " & Erl & vbNewLine & _
            "On sheet: " & ActiveSheet.Name & vbNewLine & _
            "Please report this error information to the Bulk Import & Export in ProQuest Chatter group" & vbNewLine & _
            "Include a screen shot if possible."
        Resume Next
    
    End If
    End Sub
    Private Sub SaveforUpload_Button_Click()
        CleanUpForUpload
        ActiveWorkbook.Save
        Unload Me
    End Sub
    
    Private Sub SaveforEditing_Button_Click()
        ActiveWorkbook.Save
        Unload Me
    End Sub
    
    Private Sub CloseNoSave_Button_Click()
        Unload Me
        Call SetDoNotRun 'If the user chooses to close without saving, this bypasses the BeforeClose code so they aren't just asked again
        ThisWorkbook.Close savechanges:=False
    End Sub
    
    Private Sub CancelClose_Button_Click()
        Unload Me
        bCancelClose = True
    End Sub
    '------------------------------------------------------------------------------------------------
    ' Clean up the workbook for upload to PQ - delete all unused rows in all tabs containing XML code
    '------------------------------------------------------------------------------------------------
    Sub CleanUpForUpload()
    ' Turn off some Excel functionality so code runs faster
    '  called BeforeWorkbookClose in ThisWorkbook
    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    
    Dim ws As Worksheet
    
    On Error GoTo ErrorHandler
    
    If Application.WorksheetFunction.CountA(Worksheets("Location").Range("A13:A413")) = 0 Then
        GoTo BypassClean
    End If
    
        For Each ws In ThisWorkbook.Worksheets
            If Not ws.Name Like "_*" And ws.Name <> "Help" And ws.Name <> "Product Selection" And ws.Name <> "Private IP QoS Profiles" And ws.Name <> "Site Questionnaire" And ws.Name <> "EVC Configurations" And ws.Name <> "Order Details" Then
                If ws.Range("A13").Value <> vbNullString And ws.Visible = xlSheetHidden Then
                    UserForm1.Hide
                    MsgBox ws.Name & " is hidden but contains data." & vbNewLine & _
                    "Please select the tab in the Product Selection screen" & vbNewLine & _
                    "or delete the Quote Location Name(s) on that tab to continue", vbOKOnly
                    ws.Visible = xlSheetVisible
                    bCancelClose = True
                    GoTo BypassClean
                End If
                DeleteUnusedRows ws 'call the DeleteUnusedRows Sub passing the Worksheet name as "ws"
                DeleteBlankCells ws 'call the DeleteBlankCells Sub passing the Worksheet name as "ws"
            End If
        Next ws
    
    BypassClean:
    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Exit Sub
    
    ErrorHandler:
    MsgBox "Description: " & Err.Description & vbNewLine & _
            "Error Number: " & Err.Number & vbNewLine & _
            "Error at Line: " & Erl & vbNewLine & _
            "On sheet: " & ws.Name & vbNewLine & _
            "Please report this error information to the Bulk Import & Export in ProQuest Chatter group" & vbNewLine & _
            "Include a screen shot if possible."
    Resume Next
    
    End Sub
    '---------------------------------------------------------------------------------------------
    ' Delete all blank rows - called from CleanUpForUpload
    '---------------------------------------------------------------------------------------------
    Sub DeleteUnusedRows(ws As Worksheet)
        With ws
            On Error Resume Next
            ws.UsedRange.Offset(12).Columns(1).SpecialCells(4).EntireRow.Delete
            On Error GoTo 0
        End With
    End Sub
    
    '---------------------------------------------------------------------------------------------
    ' Delete all blank cells - called from CleanUpForUpload
    '---------------------------------------------------------------------------------------------
    Sub DeleteBlankCells(ws As Worksheet)
    ' This code actually copies all of the non-null cells (user-entered or a formula
    '   that evaluates to something other than "") and pastes it as a "clean" value
    '   that does not contain any non-printable characters - this effectively removes
    '   any formulas that PQ would see as actual values unintentionally
    
    Dim Rng As Range
        With ws
            On Error Resume Next
            Set Rng = Application.Intersect(.UsedRange, .Cells.Resize(.Rows.Count - 12).Offset(12))
            Rng.Value2 = ws.Evaluate("IF(ROW(" & Rng.Address & "),CLEAN(" & Rng.Address & "))")
            On Error GoTo 0
        End With
    End Sub
    Function SetDoNotRun() 'Code to set the value for the trigger that keeps the BeforeClose code from running (see ThisWorkbook)
        bDoNotRun = True
    End Function
    Function SetCancelClose() 'Code to set the value for the trigger that allows the user to cancel the save and close (see UserForm1)
        bCancelClose = True
    End Function
    If you made it through all of that without giving up, any guess why it would work sometimes and not others, or any suggestions on how to test it differently to find the problem myself?

  2. #2
    Forum Expert GeneralDisarray's Avatar
    Join Date
    09-15-2011
    Location
    Pittsburgh, PA, USA
    MS-Off Ver
    Windows Excel 2016
    Posts
    1,416

    Re: BeforeClose code working in debug but sporadically in actual execution - how can I tes

    Every time I try to debug it using the ways I'm familiar with (stepping through the code, breaking out and testing pieces of code) it works fine. I get no error message when it doesn't work, I just reopen the file and the rows that should have been deleted weren't. When I try it a second time it works fine.
    When you step through the code to completion, are the changes saved? Upon reopen, you see what you should see?
    Remember, saying thanks only takes a second or two. Click the star icon(*) below the post you liked, to give some Rep if you think an answer deserves it.

    Please,mark your thread [SOLVED] if you received your answer.

  3. #3
    Forum Guru
    Join Date
    07-25-2011
    Location
    Florida
    MS-Off Ver
    Excel 2003
    Posts
    9,652

    Re: BeforeClose code working in debug but sporadically in actual execution - how can I tes

    Throwing out some ideas to see what sticks.

    Can you determine in your debugging if the cleanup happens but it's not saved, or if the cleanup doesn't happen and it is saved, or both the cleanup and save don't happen?


    With this code...
    Private Sub SaveforUpload_Button_Click()
        CleanUpForUpload
        ActiveWorkbook.Save
        Unload Me
    End Sub
    
    Private Sub SaveforEditing_Button_Click()
        ActiveWorkbook.Save
        Unload Me
    End Sub
    If you have more than one workbook open, the ActiveWorkbook may not be the same as ThisWorkbook. Are you saving the right workbook here.



    Where do you declare bDoNotRun? Is it in a standard code module (e.g.; Module1) and declared as Public? Can you monitor bDoNotRun? One possibility is that it's getting set to True on one occasion then later not reset back to False when you want to cleanup.
    Surround your VBA code with CODE tags e.g.;
    [CODE]your VBA code here[/CODE]
    The # button in the forum editor will apply CODE tags around your selected text.

  4. #4
    Registered User
    Join Date
    09-03-2014
    Location
    Columbus, OH
    MS-Off Ver
    Office 2007
    Posts
    7

    Re: BeforeClose code working in debug but sporadically in actual execution - how can I tes

    GeneralDisarray - yes, if I step through the code completely it does all of the coded deletions and other pieces with no issues. I can stop just about anywhere and step through it (I've tried just about every stop point I can think of) and then let it run past that point (F5) and it will work as designed. It will also work as designed if I F8 through every single step (uber tedious but I had to do it to be sure!)

    AlphaFrog - I feel like I'm responding to a celebrity I see your name here so often in my searches! I thought that since the userform was in the correct workbook that it would force the active workbook to be the correct one but I can certainly change that to make it safer.

    bDoNotRun was my best guess as to the culprit as well but I don't think I've tested it/debugged it thoroughly so it's well worth another look. I declare it as a Public function in my function module (just a regular module - I named a module for functions, one for main code and one for just admin stuff/testing)

    Public bCancelClose As Boolean 'Used in BeforeClose with the Cancel button
    Public bDoNotRun As Boolean 'Used in SetDoNotRun function to bypass BeforeClose code when needed
    Option Explicit
    I'll watch bDoNotRun and see if anything funky is happening there and then report back.

    Thank you both VERY much for trudging through that code!
    Last edited by lorikgator; 11-19-2015 at 03:08 PM. Reason: Fixed code wrapper

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Problems with BeforeClose Event code
    By tmbarnard in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 01-03-2015, 06:05 PM
  2. [SOLVED] BeforeClose event not running/working when file is closed through VBA in another file
    By jaimelwilson in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-27-2014, 03:43 AM
  3. VBA Code Runs in Debug Mode But Returns Type Mismatch Error Outside Debug Mode
    By valerie.k.chiang in forum Excel Programming / VBA / Macros
    Replies: 7
    Last Post: 01-24-2014, 03:48 PM
  4. [SOLVED] Debug: How to debug this code?
    By reach78 in forum Excel Programming / VBA / Macros
    Replies: 10
    Last Post: 09-25-2013, 07:16 AM
  5. VLOOKUP returning #N/A sporadically
    By Bobbo Jones in forum Excel Formulas & Functions
    Replies: 2
    Last Post: 03-13-2013, 10:15 PM
  6. Beforeclose sub suddenly stopped working
    By cuewoz in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-04-2010, 12:29 PM
  7. Shared Workbook updating sporadically
    By Maddman in forum Excel General
    Replies: 1
    Last Post: 02-28-2005, 10:06 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1