rhuber
rhuber

Reputation: 3

Execute macro on all files in a folder and subfolder

I want to execute a Word-macro for all the doc and docx files in a folder and the subfolders. My code only executes the macro for the folder (not for the subfolders). Is there a possible way to do that?

My macro so far:

Sub Aufruf()
Dim File
Dim path As String

' Path to your folder. MY folder is listed below. I bet yours is different.
' make SURE you include the terminating "\"
path = "C:\Users\RHU\Desktop\VBA\"

File = Dir(path & "*.doc*")
Do While File <> ""
Documents.Open fileName:=path & File

' This is the call to the macro you want to run on each file the folder
Call Datumsfelder


' Saves the file
ActiveDocument.Save
ActiveDocument.Close
' set file to next in Dir
File = Dir()
Loop
End Sub

Upvotes: 0

Views: 1451

Answers (1)

baka_toroi
baka_toroi

Reputation: 74

Go to Tools -> References and from there add Microsoft Scripting Runtime. This will give you access to the File System Object (FSO). It contains many useful features such as getting subfolders.

Then you can loop through them with something like the code below:

Sub myFunction()

Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim anotherFolder As Folder
Dim myFile as File

Set myFolder = FSO.GetFolder("C:\a\")

For Each anotherFolder In myFolder.SubFolders
    Debug.Print anotherFolder
    For Each myFile In anotherFolder.Files
        'Here the myFile object will allow you to open each file in the current folder
         Documents.open myFile.Path
         'Do more stuff, then save and close the file
    Next
Next

End Sub

Mind you, this will go just one level deep. If you need to go deeper you will need to join several For loops.

Upvotes: 1

Related Questions