Search code examples
vbams-wordwsh

Unprotect multiple word documents inside a folder using VBA


I have multiple word documents, which need restrictions imposed on them from Developer mode.

I run the script using wscript passing a folder as argument, But it throes an error

Dim strFolder
Const xlTypePDF = 0
strFolder = WScript.Arguments(0)

if  Wscript.Arguments.Count > 0 Then

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objWord = CreateObject("Word.Application")
    Set objFolder = objFSO.GetFolder(strFolder)

    For Each Fil In objFolder.Files
        Set objFile = objFSO.GetFile(Fil)

        Set objDoc = objWord.Documents.Open(Fil,,TRUE)
        dirPath = objFSO.GetParentFolderName(objFile)
        fileBaseName = objFSO.GetBaseName(objFile)

'objWord.ActiveDocument.Unprotect Password:="pwd" 

        objWord.ActiveDocument.Close(False)
    Next

    objWord.Quit
Else
    Msgbox("Run usning cmd")
End If

Solution

  • Sub UnprotectDocsInFolder()
    Dim docfile As Document
    Dim docpath As String
    Dim docfilename As String
    Dim pwd As String
    
        'Path for the documents
        docpath = "C:\ProtectedDocs\"
        'Password
        pwd = "myPass"
    
        docfilename = Dir(docpath & "*.doc")
    
        Do Until docfilename = ""
            Set docfile = Documents.Open(docpath & docfilename)
            docfile.Unprotect pwd
            docfile.Close True
            docfilename = Dir()
        Loop
    End Sub
    

    You can use similar code to protect files in same manner.

    Sub ProtectDocsInFolder()
    Dim docfile As Document
    Dim docpath As String
    Dim docfilename As String
    Dim pwd As String
    
        'Path for the documents
        docpath = "C:\UnProtectedDocs\"
        'Password
        pwd = "myPass"
    
        docfilename = Dir(docpath & "*.doc")
    
        Do Until docfilename = ""
            Set docfile = Documents.Open(docpath & docfilename)
            docfile.Protect wdAllowOnlyFormFields, , pwd
            docfile.Close True
            docfilename = Dir()
        Loop
    End Sub