Solved

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

Posted on 2012-03-22
5
531 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
Outlook for dependable use in a very small business   This article is about using the Outlook application (part of Microsoft Office) in a very small business, or for homeowners where dependability and reliability are critical requirements. This …
This Micro Tutorial demonstrates in Microsoft Excel how to consolidate your marketing data by creating an interactive charts using form controls. This creates cool drop-downs for viewers of your chart to choose from.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

627 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