Home > Net >  How to close current Word document and stop all VBA code running
How to close current Word document and stop all VBA code running

Time:11-24

I am creating a Word template that performs a bunch of actions when Document_New is initialised. For example, I am pulling in and applying Custom Document Properties from an XML file in one sub, and referring to them in a second.

I'm trying to add some error handling to close the document with an error message and prevent the rest of the VBA from running, and I can get to the point where the document closes, but the rest of the VBA code continues to execute. Ideally I need to close just this new document (other Word documents may be open on a device) and stop any more processing of VBA.

ThisDocument.Close SaveChanges:=wdDoNotSaveChanges

When this is in place, the template seems to close, but the newly created document still exists and the template VBA continues to run.

Is anyone able to suggest a way to close the template and abort the creation of the new document?

EDIT: Including an example of how I'm looking for errors.

In Document_New - I call ValidateProperties that loops through an arrayProps array that stores properties required for the template. Each property in the array is checked using the function CustomDocumentPropertyExists and if that returns false I call the sub ExitFailedValidation. This is the sub I want to call if the template fails a validation test. I want to be able to cleanly close the new document without saving and leave any other Word windows open.

Sub ValidateProperties()
    Dim arrayProps(1)   As String
    Dim i               As Long
    
    arrayProps(0) = "prop-doc-blueprint"
    arrayProps(1) = "prop-doc-stationery"
    
    For i = 0 To UBound(arrayProps)
        If CustomDocumentPropertyExists(arrayProps(i)) = False Then
            ExitFailedValidation ("The required custom document property " & arrayProps(i) & " is missing. Please check " & _
                "the config.xml file to ensure it is included.")
        End If
    Next i
End Sub

Sub ExitFailedValidation(Message As String)

    MsgBox "The Template failed to load and validate." & vbCrLf & vbCrLf & _
        Message, vbCritical, "Error loading template"
    
    MsgBox ThisDocument.Name
    MsgBox ActiveDocument.Name
    
    ThisDocument.Close SaveChanges:=wdDoNotSaveChanges
    ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
    
End Sub

CodePudding user response:

The Document_New() is the entrance point in code, so it should handle the tasks that need to be run and take appropriate action should an error occurs or something did not go as expected as in your case.

In order to be able to do that, the tasks it calls must report their status, e.g. completed, failed, something is missing etc.

Therefore, change the ValidateProperties() sub into a function that returns true or false and pass a string to it as an output parameter that will hold the error message if the function fails. If all goes well, it will simply be unused.

The main point of the app. This method decides what happens in the app.

Private Sub Document_New()
    
    Dim errorMessage As String
    
    If Not TryValidateProperties(errorMessage) Then
        ExitFailedValidation errorMessage
        Exit Sub
    End If
    
    'all good - continue
    
End Sub

The ValidateProperties() sub changed to a method that returns true or false with an optional error message if something is wrong. Since false is the default value of a boolean, exiting the function if a property doesn't exist will return false - no need to set it explicitly.

Private Function TryValidateProperties(ByRef outMessage As String) As Boolean
    
    '...
    
    For i = 0 To UBound(arrayProps)
        If Not CustomDocumentPropertyExists(arrayProps(i)) Then
            outMessage = "The required custom document property " & arrayProps(i) & " is missing. Please check " & _
                "the config.xml file to ensure it is included."
            Exit Function
        End If
    Next i
    
    'all good
    TryValidateProperties = True
    
End Function

Lastly, the helper method for communicating the error. In my opinion, the document shouldn't be closed here, but within the Document_New() method if property validation fails, but I'll leave this with you.

Private Sub ExitFailedValidation(Message As String)
    MsgBox Message
End Sub

To add error handling in a method:

Sub T()
    On Error GoTo Trap

    'main method body


Leave:
    'Release any references here, e.g. close db connection, release file handle etc.
    Exit Sub
    
Trap:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Sub
  • Related