PDA

View Full Version : [SLEEPER:] Protecting Word document from Excel



szczasiek
02-04-2019, 08:55 AM
Hi

I have a macro in Excel, that is replacing values in Word with data stored in Worksheet. Then this changed Word is saved as new document. What is struggle is a command in VBA in Excel putting a password on Word document restricting it from edition.

Code i have now is as below:

Option Explicit

Public Sub INDEMNITY()
Dim ws As Worksheet, msWord As Object
Dim wbA As Workbook
Dim strPath As String
Dim itm As Range
Dim customer_name As String
Set wbA = ActiveWorkbook
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
Set ws = ActiveSheet
Set msWord = CreateObject("Word.Application")
customer_name = Range("f10").Value
With msWord
.Visible = True
.Documents.Open strPath & "E-Commerce_Indemnity.docx"
.Activate
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
For Each itm In ws.UsedRange.Columns("A").Cells
.Text = itm.Value2
' Find all strings in col A
.Replacement.Text = itm.Offset(, 1).Value2
' Replacements from col B
.MatchCase = False
.MatchWholeWord = False
.Execute Replace:=2
' wdReplaceAll (WdReplace Enumeration)
Next
End With
With msWord
.ActiveDocument.SaveAs Filename:=strPath & customer_name & "_E-commerce_Indemnity_letter.docx".
.Quit
End With
msWord.DisplayAlerts = True
End With
End Sub


I was trying command

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

But returns me error that Variable is not defined, for wdAllowOnlyRevisions

Kenneth Hobs
02-04-2019, 09:16 AM
When using late binding, object constant/enumeration values have to be set as you did elsewhere.


wdAllowOnlyRevisions = 0

OF course Application.ActiveDocument means Word Application, not Excel. Use:

msWord.ActiveDocument.Protect 0, password:="password"