Vba word защита документа

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Document.Protect method (Word)

vbawd10.chm158007763

vbawd10.chm158007763

word

727bafe9-48ea-6b2f-2262-778f66487cbd

06/08/2017

medium

Document.Protect method (Word)

Protects the specified document from unauthorized changes.

Syntax

expression.Protect (Type, NoReset, Password, UseIRM, EnforceStyleLock)

expression A variable that represents a Document object.

Parameters

Name Required/Optional Data type Description
Type Required WdProtectionType The type of protection to apply.
NoReset Optional Variant False to reset form fields to their default values; True to retain the current form field values if the document is protected. If Type is not wdAllowOnlyFormFields, NoReset is ignored.
Password Optional Variant If supplied, the password to be able to edit the document, or to change or remove protection.
UseIRM Optional Variant Specifies whether to use Information Rights Management (IRM) when protecting the document from changes.
EnforceStyleLock Optional Variant Specifies whether formatting restrictions are enforced for a protected document.
Type Required WDPROTECTIONTYPE
NoReset Optional Variant
Password Optional Variant
UseIRM Optional Variant
EnforceStyleLock Optional Variant

Return value

VOID

[!includeSupport and feedback]

Благодарю, это работает. А можно ли так же активировать шифрование документа, а не ограничение на редактирование?
Так же встаёт вопрос, как теперь программно снять защиту документа для обращения к его содержимому.
Если вас, конечно, это не затруднит.

Добавлено через 7 минут
Если использовать информацию отсюда: http://www.excel-vba.ru/chto-u… a-proekta/ и адаптировать её для MS Word так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    Dim objVBProject As Object, objVBComponent As Object, objWindow As Object
 
    Documents.Open FileName:=pu, Visible:=False
    Set objVBProject = ActiveDocument.VBProject
 
    For Each objWindow In objVBProject.VBE.Windows
        If objWindow.Type = 6 Then
            objWindow.Visible = True
            objWindow.SetFocus: Exit For
        End If
    Next
 
    SendKeys "password", True: SendKeys "{ENTER}", True
    Documents(pu).Paragraphs(1).Range.Text = "Text2Text"
    MsgBox Documents(pu).Paragraphs(1).Range
    Set objVBProject = Nothing: Set objVBComponent = Nothing: Set objWindow = Nothing
    ActiveDocument.Close True

То «Отсутсвует доверие к программируемому доступу к проекту Visual Basic» На строку «Set objVBProject = ActiveDocument.VBProject».

Добавлено через 7 минут
Возможно, такая реакция вызвана тем, что стоит пароль на VBA-проект.
Тогда ещё больше вопросов…

Using VBA, I believe you’d be looking for the protect method:

Application.ActiveDocument.Protect wdAllowOnlyRevisions, password:="password"

With protect, you can specify the type of protection, the password, and various components of the protection (style lock, resetting of form fields, etc.).
More on protect can be found here.

Likewise, VBA has a similar method for unprotecting a Word document, if you know the password. This is the aptly named unprotect method.

Application.ActiveDocument.Unprotect "password"

More on unprotect can be found here.

Word Document Password Protection – 2 most used Methods

Yes, there are more than one methods available to password protect a Word document.

And it confused the programmers all the time about, which code to use to unprotect the document & read the content.

Here are 2 of the most used methods:

  1. Document level Password with Encryption
  2. Document level Protection for Editing.

Lets see each of these categories and how to deal them when we automate the process through VBA.

1.VBA Macro to Open Word Document with Password Protection

A word document can be saved with protection on & a password set for encryption. This option can be found in this menu navigation

  • File -> Info -> Protect Document -> Encrypt with password
  • Type password & click ok
  • Save & close document

Now, everytime the word document is opened, it will ask for a password. It will only display the contents of the file, if the entered password is correct.

Well, manually you can type the password. But how to deal with these password protected files with a VBA code.

Sub openWordwithPassword()
    'Define
    Dim sFileName As String
    Dim passwd As String
    Dim oWord As Object
    Dim oDoc As Object
    
    'Init
    Set oWord = CreateObject("Word.Application")
    oWord.Visible = True
    sFileName = "C:Filepath.docx"
    passwd = "enteryourpasswordhere"
    
    'Open document using password
    Set oDoc = oWord.Documents.Open(sFileName, PasswordDocument:=passwd)
    
    'Do pocessing
    Debug.Print oDoc.Content
    oDoc.Save
    
    'Save with password
    oDoc.SaveAs Filename:=sFileName, Password:=passwd

    'Close
    oDoc.Close
End Sub

Once the document is opened using this method, its content can be edited or extracted. This is a document level password protection. In case your document is only writeprotected, then use the below method.

2. VBA Code to Unprotect Word Document – Enable Editing

The below code unprotects a word document with password for readonly. Then in the next step, you will be able to edit or read contents

Then, after processing the data, the code enables writeProtection on the document. i.,e edit is disabled & file is saved.

Sub UnprotectwordwithPassword()
    'Define
    Dim sFileName As String
    Dim passwd As String
    Dim oWord As Object
    Dim oDoc As Object
    
    'Init
    Set oWord = CreateObject("Word.Application")
    oWord.Visible = True
    sFileName = "C:Filepath.docx"
    passwd = "enteryourpasswordhere"
    
    'Open document using password
    Set oDoc = oWord.Documents.Open(sFileName, PasswordDocument:=passwd)
    If ActiveDocument.ProtectionType <> -1 Then oDoc.Unprotect passwd
    
    'Do pocessing
    Debug.Print oDoc.Content
    
    'Protect again with password
    objDoc.Protect 3, , passwd '3- - Refer end of the page for more parameters
    oDoc.Save

    'Close
    oDoc.Close
End Sub

This VBA code is very useful, then you have multiple files to be marked as readonly or protected from users editing it. It is tough to open and edit each document one by one and then enable a password.

Instead, with this process, you can place all the word documents in a folder. Then make the macro to read files one by one and enable password protection.

With document.Protect function You can use one of these parameters which serves different purpose.

-> wdProtectionType & corresponding value

  • wdAllowOnlyComments = 1
  • wdAllowOnlyFormFields = 2
  • wdAllowOnlyReading = 3
  • wdAllowOnlyRevisions = 0
  • wdNoProtection = -1

External Reference:
1. Here is another related topic from Microsoft forum about Word document password protection.

Понравилась статья? Поделить с друзьями:
  • Vba word заменить картинку
  • Vba word заменить все слова
  • Vba word замена таблицы
  • Vba word выбрать строку в таблице
  • Vba word выбрать строки