Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop Through All Word Documents in Directory

VB for apps

Loop Through All Word Documents in Directory

by  GeekGirlau  Posted    (Edited  )
You can loop through all the *.doc files in a directory with this macro. This example was used to recover corrupted documents. The code opens the file, selects the whole document and copies it, pastes to a new document, and saves the file with the original name, but in a new directory. However by changing the highlighted section in the middle, you can perform any action on all the nominated documents.


Sub LoopThruFile()
Dim strPath As String
Dim strNewPath As String
Dim strFullPathDoc As String
Dim strFileName As String


strPath = "F:\Data\TestFolder\"
strNewPath = strPath & "Recovered\"

strFullPathDoc = Dir(strPath & "*.doc", vbNormal)

Do While strFullPathDoc <> ""
strFileName = ExtractFileName(strFullPathDoc)

Documents.Open strPath & strFileName

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Change this section to perform a different action

Selection.WholeStory
Selection.Copy
Documents.Add Template:="Normal", NewTemplate:=False
Selection.Paste
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

' Depending on what you're doing, you may want to use Save rather than SaveAs
' use this option to save to a different location


ActiveDocument.SaveAs strNewPath & strFileName
ActiveWindow.Close

strFullPathDoc = Dir ' Get next entry.
Loop
End Sub

Function ExtractFileName(strFullPath As String)
Dim txt As String


On Error Resume Next

txt = "" & strFullPath

While InStr(txt, "\") > 0
txt = Mid$(txt, InStr(txt, "\") + 1)
Wend

If InStr(txt, ":") > 0 Then
txt = Mid$(txt, InStr(txt, ":") + 1)
End If

ExtractFileName = txt
End Function
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top