Solved

Request for VBA code to password protect all Word docs in a folder

Posted on 2012-03-22
5
513 Views
Last Modified: 2012-03-23
Title says it all, doesn't matter if code is in Word or Excel, but it is Word docs that I need to protect. Password can be the same for all.

Thanks!
0
Comment
Question by:newparadigmz
  • 3
5 Comments
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
Why is this an Excel problem? I can do Word
0
 
LVL 41

Accepted Solution

by:
dlmille earned 500 total points
Comment Utility
I personally like running from a script or Excel, but the code wouldn't change much running from Word.

Be sure to make a backup of your folder while testing - in fact always a good idea, anyway.

The app prompts for a directory, then opens each file assuming no password, then changes the password (see code for password constant you can change) and saves the file.  

If there is an error opening or changing a password, you are prompted to skip that file and continue or abort.

Here's the code:
Option Explicit
Const Passwd = "Password"
Sub protectAllWordInFolder()
Dim dialogFile As FileDialog
Dim fDir As String
Dim fName As String
Dim strPath As String
Dim fPathFname As String
Dim oWordApp As Object ' late binding 'Word.Application 'early binding
Dim oWordDoc As Object ' late binding 'Word.Document 'early binding
Dim xMsg As Long

    strPath = ThisWorkbook.Path 'initial path for directory prompt
    
    ' Open the file dialog
    Set dialogFile = Application.FileDialog(msoFileDialogFolderPicker)
    With dialogFile
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .InitialFileName = strPath & "\"
        .Title = "Select Folder for Processing"
        .Show
    End With
    If dialogFile.SelectedItems.Count > 0 Then
        fDir = dialogFile.SelectedItems(1)
        
        fName = Dir(fDir & "\*.doc*")
        
        If fName <> vbNullString Then
            
            Set oWordApp = CreateObject("Word.Application")
            
            Do
                fPathFname = fDir & "\" & fName
                'oWordApp.Visible = True
                On Error Resume Next
                Set oWordDoc = oWordApp.Documents.Open(Filename:=fPathFname)
                oWordDoc.Password = Passwd
                If Err.Number <> 0 Then
                    xMsg = MsgBox("Could not open word document or change password: " & fPathFname, vbYesNo, "Skip and Continue? (YES) Abort? (NO)")
                    If xMsg = vbNo Then GoTo gracefulExit
                    If Not oWordDoc Is Nothing Then oWordDoc.Close savechanges:=False
                Else
                    oWordDoc.Close savechanges:=True
                End If
                fName = Dir()
            Loop Until fName = vbNullString
            
            oWordApp.Quit
            Set oWordApp = Nothing
        End If
    Else
        fDir = ""
    End If
        
gracefulExit:

    'cleanup
    If Not oWordDoc Is Nothing Then oWordDoc.Close savechanges:=False
    If Not oWordApp Is Nothing Then oWordApp.Quit

    Set dialogFile = Nothing
End Sub

Open in new window


See attached.

Cheers,

Dave
processWordDocs-r1.xls
0
 
LVL 41

Expert Comment

by:dlmille
Comment Utility
And, here's the same code but written to run from Word.  I just pasted it in a new module in my Normal template for a quick test:
Option Explicit

Const Passwd = "Password"
Sub protectAllWordInFolder()
Dim dialogFile As FileDialog
Dim fDir As String
Dim fName As String
Dim strPath As String
Dim fPathFname As String
Dim oWordDoc As Word.Document
Dim xMsg As Long

    strPath = ThisDocument.Path 'initial path for directory prompt
    
    ' Open the file dialog
    Set dialogFile = Application.FileDialog(msoFileDialogFolderPicker)
    With dialogFile
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .InitialFileName = strPath & "\"
        .Title = "Select Folder for Processing"
        .Show
    End With
    If dialogFile.SelectedItems.Count > 0 Then
        fDir = dialogFile.SelectedItems(1)
        
        fName = Dir(fDir & "\*.doc*")
        
        If fName <> vbNullString Then
            
            Do
                fPathFname = fDir & "\" & fName
                'Application.Visible = True
                On Error Resume Next
                Set oWordDoc = Application.Documents.Open(FileName:=fPathFname)
                oWordDoc.Password = Passwd
                If Err.Number <> 0 Then
                    xMsg = MsgBox("Could not open word document or change password: " & fPathFname, vbYesNo, "Skip and Continue? (YES) Abort? (NO)")
                    If xMsg = vbNo Then GoTo gracefulExit
                    If Not oWordDoc Is Nothing Then oWordDoc.Close savechanges:=False
                Else
                    oWordDoc.Close savechanges:=True
                End If
                fName = Dir()
            Loop Until fName = vbNullString
            
        End If
    Else
        fDir = ""
    End If
        
gracefulExit:

    'cleanup
    If Not oWordDoc Is Nothing Then oWordDoc.Close savechanges:=False

    Set dialogFile = Nothing
End Sub

Open in new window


Cheers,

Dave
0
 

Author Closing Comment

by:newparadigmz
Comment Utility
Once again, very much appreciated.

Agreed on running from Excel, also increases odds of an answer as there are much more experts in that than Word.

two quick questions for my curiousity please;

Why is the constant outside of the sub?

How come I do not see the Word docs open on the Open command?
They always do for Excel.
0
 
LVL 41

Expert Comment

by:dlmille
Comment Utility
>> Why is the constant outside of the sub?
because I wanted you to notice it.  

I also generally put constants outside the subs, and more often make them public as my code gets larger and I'm sharing with other modules.  Just my personal style.

>>How come I do not see the Word docs open on the Open command?
because the oWordApp is not visible.  Uncomment line 33 if you want to see it, but only for debugging purposes as it can run more slowly and you might interact between it and the running macro - not a good combination for fast typists like me who inadvertently interacts with Windows prompts about 5% of the time when popups hit me in the face while I'm typing, lol.

Dave
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

A few years ago I was very much a beginner at VBA, and that very much remains the case today.  I'll do my best to explain things as I go in the hope that other beginners can follow.  If you just want to check out a tool that creates a Select Case fu…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
This Micro Tutorial will demonstrate in Microsoft Excel how to add style and sexy appeal to horizontal bar charts.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now