page numbering macro causes crash...

Hi.  I have this code and it runs okay as long as I don't have too many pages with graphics on them.  I can re-create the crash many times and would like to know if there is something else I can add to this so that the crash does not happen.  Maybe something that will check when the page deletion process is taking longer than normal and the macro will pause to allow processing?

Dim s As Shape

    For Each pageThis In ActiveDocument.Pages
        Set sPageNumThis = pageThis.Shapes.FindShape("pagetotal")
        If Not sPageNumThis Is Nothing Then
            sPageNumThis.Text.Story = CStr(ActiveDocument.Pages.Count)
        End If
    Next pageThis

Parents
  • If you really, really want to have something that normally runs automatically when triggered by document events, then one way to temporarily "switch it off" would be to use a boolean variable with a scope that makes it available to all subs in the project. You could set the value of that variable using a couple of simple subs, and you could have your subs in ThisMacroStorage check that variable, when they are triggered, to know whether they should execute the code that you normally want to run automatically.

    So, something like this in your code module:

    Option Explicit
    Public blnSuppressRenumber As Boolean
    
    Sub set_suppress_renumber_true()
    
        blnSuppressRenumber = True
    End Sub
    
    Sub set_suppress_renumber_false()
    
        blnSuppressRenumber = False
    End Sub
    
    Sub renumber_pages()
    
        MsgBox "Page renumbering would take place now."
    End Sub
    

    and then something like this in ThisMacroStorage:

    Option Explicit
    Dim WithEvents CurDoc As Document
    
    Private Sub GlobalMacroStorage_WindowActivate(ByVal Doc As Document, ByVal Window As Window)
        Set CurDoc = Doc
    End Sub
    
    Private Sub GlobalMacroStorage_WindowDeactivate(ByVal Doc As Document, ByVal Window As Window)
        Set CurDoc = Nothing
    End Sub
    
    Private Sub CurDoc_PageCreate(ByVal Page As Page)
        If Not blnSuppressRenumber Then
            renumber_pages
        End If
    End Sub
    
    Private Sub CurDoc_PageDelete(ByVal Count As Long)
        If Not blnSuppressRenumber Then
            renumber_pages
        End If
    End Sub
    

    Seriously, though, when it comes to something that walks through the whole document, changing content on every page, I would probably NOT choose to have it automatically triggered every time that I added or removed a page. I would probably just run the macro manually when I wanted to update it.

    If I were worried about someone saving or printing a document without updating, then I might try running it automatically based on GlobalMacroStorage_DocumentBeforeSave or GlobalMacroStorage_DocumentBeforePrint, and see if that worked OK.

Reply Children