Solved

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

Posted on 2012-03-22
5
527 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 500 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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

This code takes an Excel list of URL’s and adds a header titled “URL List”. It then searches through all URL’s in column “A”, looking for duplicates. When a duplicate is found, it is moved to the top of the list. The duplicate URL’s are then highlig…
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

751 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