Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2012-03-22
5
Medium Priority
?
542 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
ID: 37755128
Why is this an Excel problem? I can do Word
0
 
LVL 42

Accepted Solution

by:
dlmille earned 2000 total points
ID: 37755471
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 42

Expert Comment

by:dlmille
ID: 37755519
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
ID: 37758617
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 42

Expert Comment

by:dlmille
ID: 37758641
>> 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft's Excel has many features that most people will never need nor take advantage of.  Conditional formatting is one feature that you may find a necessity once you start using it.
Lost Word File? Eagerly, need it back? Read ahead; this File Recovery guide is for you.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

916 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