I'm often opening, from Excel, all Word documents inside a folder.
And sometimes during the treatments, Word crash without throwing an error.
So I've added a bit of error handling to restart Word and reopen the doc I was working on.
I'm just wondering if I'm doing it properly, or if I should go further like :
- Test the error number
- If it's 462 : The remote server machine does not exist or is unavailable, go to RestartWord
- If it's something else, show the error message
It may also not be only Error 462, but I don't have any other examples for this.
My code :
Private Sub Update_Word_DocMs_In_Folder(ByVal FolderToScan As String, _ ByVal PathTxtWithInfo As String) Dim oW As Object, NewFile As String '''Boolean to detect if it was the initial launch Dim NormalWordLaunch As Boolean NormalWordLaunch = True Set oW = OpenOrReopen("Word.Application", NormalWordLaunch) On Error GoTo RestartWord NewFile = Dir(FolderToScan & "*.docm") Do While NewFile <> vbNullString '''ErrHdl: Jump back here after re-creating a Word's instance ReOpenWordFile: Call OpenWordDocAndApplyTreatment(oW, FolderToScan & NewFile, PathTxtWithInfo) NewFile = Dir() Loop oW.Quit On Error GoTo 0 Set oW = Nothing Set oDoc = Nothing Exit Sub RestartWord: If Err.Number <> 462 Then MsgBox Err.Number & vbCrLf & Err.Description, vbCritical + vbOKOnly, "Error not handled" DoEvents Resume Else Set oW = OpenOrReopen("Word.Application", NormalWordLaunch) '''ErrHdl: If this isn't the initial launch go back to the loop If Not NormalWordLaunch Then Resume ReOpenWordFile End If End Sub
Function to handle creating an app instance :
Function OpenOrReopen(ByVal ClassName As String, NormalLaunch As Boolean) As Object Set OpenOrReopen = Nothing On Error Resume Next '''Check if there is already an instance Set OpenOrReopen = VBA.GetObject(, ClassName) On Error GoTo 0 If OpenOrReopen Is Nothing Then '''If there isn't any instance, create one Set OpenOrReopen = VBA.CreateObject(ClassName) Else '''If detected instance is visible, create a new one If OpenOrReopen.Visible Then Set OpenOrReopen = VBA.CreateObject(ClassName) End If '''Set instance to be hidden OpenOrReopen.Visible = False OpenOrReopen.Options.UpdateLinksAtOpen = False '''For ErrHdl: Change boolean the 1st time If NormalLaunch Then NormalLaunch = False End Function
Code for treatment :
Sub OpenWordDocAndApplyTreatment(WordApp As Object, _ ByVal FileFullName As String, _ ByVal PathTxtWithInfo As String) Dim oDoc As Object Set oDoc = WordApp.Documents.Open(FileFullName) With oDoc Do While .ReadOnly DoEvents Loop '''Some treatment to update doc's properties WordApp.Run "Properties_Updating.Properties_Update", PathTxtWithInfo DoEvents .Save .Close End With 'oDoc End Sub