The macro below loops through all Word files in a folder, calls another macro (or multiple others), then saves/closes. A called macro, also below, simply deletes comments in the file; however, I'm getting Run-time error 4605 (The command is not available); the debugger highlights the ActiveDocument.DeleteAllComments line. I tried to modify it based on some web searching, but I'm coming up short, having tried to modify the code to ignore the error.
Testing the macros on a set of files just now, it failed partway through the files; I can't determine how the file that was opened when it failed differs from the others. I then tried to run the macro again and it failed on the first file.
How can I resolve this?
Code:
Sub LoopAllWordFilesInFolder()
'Loop through all Word files in a user-selected folder and perform other macros.
'Adapted from: https://www.thespreadsheetguru.com/the-code-vault/2014/4/23/loop-through-all-excel-files-in-a-given-folder
Dim docDocument As Document
Dim strPath As String
Dim strFile As String
Dim strExtension As String
Dim FolderPicker As FileDialog
'Optimize macro speed
Application.ScreenUpdating = False
'Get target folder path from user
Set FolderPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FolderPicker
.Title = "Choose the folder containing your files"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
strPath = .SelectedItems(1) & "\"
End With
'In case the user cancels
NextCode:
strPath = strPath
If strPath = "" Then GoTo ResetSettings
strExtension = "*.doc*"
'Target path with file extension
strFile = Dir(strPath & strExtension)
'Loop through each file in the folder
Do While strFile <> ""
'Set variable equal to opened document
Set docDocument = Documents.Open(FileName:=strPath & strFile)
'Use DoEvents to ensure document has opened before moving on to next line of code.
'(https://answers.microsoft.com/en-us/msoffice/forum/msoffice_powerpoint-mso_other/vba-doevents/0bdc05d5-a54e-49a8-875d-5ee962acf78e)
DoEvents
'################################################################
'CALL OTHER MACRO(S) HERE.
Call CommentsDeleteAll
'################################################################
'Save and close document
docDocument.Close savechanges:=True
'Ensure document has closed before moving on to next line of code
DoEvents
'Get next file name
strFile = Dir
Loop
MsgBox "The macro has looped through the files in the folder you chose and completed the tasks."
'Reset macro optimization settings
ResetSettings:
Application.ScreenUpdating = True
End Sub
Code:
Sub CommentsDeleteAll()
ActiveDocument.DeleteAllComments
End Sub