Batch process word files in a folder to set top margins

I got the following code from the net and changed it from changing paper size to setting top margins of word documents to suit my needs

Sub ChangeTopMargin()
Dim myFile As String
Dim myPath As String
Dim myDoc As Document

'Change to the path where your documents are located.
'This code changes ALL documents in the folder.
'You may want to move only the documents you want changed to seperate folder.
myPath = "C:\Users\Rajesh\Documents\Clinical Material\OPD"

'Closes open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges

'Set the path with file name for change
myFile = Dir$(myPath & "*.doc")

    Do While myFile <> ""

    'Open the document and make chages
    Set myDoc = Documents.Open(myPath & myFile)
    myDoc.PageSetup.TopMargin = 168

    'Close and saving changes
    myDoc.Close SaveChanges:=wdSaveChanges

    'Next file
    myFile = Dir$()
    Loop
    MsgBox "Process complete!"
End Sub

Now when I run this code after saving the file and closing code editor, the existing document closes but nothing else really happens. Ideally each of the word files in the folder OPD should be opening, get changed, saved and closed till the Process Complete message box comes up. I am out of my depth here. I will appreciate any help.

Thanks

Answer
Answer

The path must end in a backslash \:

    myPath = "C:\Users\Rajesh\Documents\Clinical Material\OPD\"

I wouldn't close the open documents. Here is a modified version of the macro:

Sub ChangeTopMargin()
    Dim myFile As String
    Dim myPath As String
    Dim myDoc As Document
 
    'Change to the path where your documents are located.
    'This code changes ALL documents in the folder.
    myPath = "C:\Users\Rajesh\Documents\Clinical Material\OPD\"
 
    Application.ScreenUpdating = False
 
    'Set the path with file name for change
    myFile = Dir(myPath & "*.doc")
 
    ' Loop through the files
    Do While myFile <> ""
        'Open the document and make changes
        Set myDoc = Documents.Open(myPath & myFile)
        myDoc.PageSetup.TopMargin = 168

        'Close and saving changes
        myDoc.Close SaveChanges:=wdSaveChanges

        'Next file
        myFile = Dir
    Loop
 
    Application.ScreenUpdating = True
    MsgBox "Process complete!"
End Sub

---
Best wishes, HansV
https://www.eileenslounge.com

1 person found this reply helpful

·

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated February 23, 2024 Views 1,529 Applies to: