I have a number of documents in a folder. They are in a variety of formats. I have written a macro to loop through them one at a time, modify the format and save the file to a "NewFiles" folder. Occasionally a file has a problem and halts the code due to an error. I want to place them in a folder called "BadFiles", but I cant seem to get it to work. Any help is appreciated!

Here is the code thus far:

  1. Sub LoopDirectory()
  2. ' This code will allow the user to browse to a folder where MS Word documents reside.
  3. ' When executed to will loop through all documents
  4. ' Then run the referenced subs and save the modified files in a subdirectory called NewFiles.

  5. Application.FileDialog(msoFileDialogFolderPicker).Show
  6. vDirectory = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
  7. On Error GoTo Err:
  8. If Len(Dir(vDirectory & "\" & "NewFiles", vbDirectory)) = 0 Then
  9. MkDir vDirectory & "\" & "NewFiles"
  10. MkDir vDirectory & "\" & "BadFiles"
  11. End If
  12. vFile = Dir(vDirectory & "\" & "*.*")
  13. Do While vFile <> ""
  14. Documents.Open FileName:=vDirectory & "\" & vFile
  15. RemoveHeadAndFoot 'Call sub from below
  16. ActiveDocument.SaveAs (vDirectory & "\" & "NewFiles" & "\" & ActiveDocument.Name)
  17. ActiveDocument.Close
  18. vFile = Dir
  19. Loop
  20. End Sub
  21. Err:
  22. If Err.Number <> 0 Then
  23. msg "Error: " & Err.Number
  24. Err.Clear
  25. ActiveDocument.SaveAs (vDirectory & "\" & "BadFiles" & "\" & ActiveDocument.Name)
  26. ActiveDocument.Close
  27. End If
  28. End sub

  29. Sub RemoveHeadAndFoot()
  30. ' This code will remove existing Headers and Footers in all documents in the folder.
  31. Dim oSec As Section
  32. Dim oHead As HeaderFooter
  33. Dim oFoot As HeaderFooter
  34. For Each oSec In ActiveDocument.Sections
  35. For Each oHead In oSec.Headers
  36. If oHead.Exists Then oHead.Range.Delete
  37. Next oHead
  38. For Each oFoot In oSec.Footers
  39. If oFoot.Exists Then oFoot.Range.Delete
  40. Next oFoot
  41. Next oSec
  42. End Sub