Log in

View Full Version : Code to: un-protect w/password, attach document, re-protect with password



wolfgrrl
09-13-2019, 08:26 AM
Good Morning! 🌞

I have the code set up for the attach button, but it doesn't function properly when the form is password protected. This is the code I have:


Private Sub CommandButton2_Click()' Browse & Select File
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the File that you want to insert"
If .Show = True Then
FiletoInsert = .SelectedItems(1)
Else
Exit Sub
End If
End With
End Sub

I need to add code to un-protect the document with a password and re-protect it once the attachment is attached. I've also added to a screenshot to show my protection settings.

Can anyone assist?

Thank you!

Kilroy
09-13-2019, 12:08 PM
Try this.


Private Sub CommandButton2_Click() ' Browse & Select File
strPassword = "your password here"
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect Password:=strPassword
End If
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the File that you want to insert"
If .Show = True Then
FiletoInsert = .SelectedItems(1)
Else
Exit Sub
End If
End With
Application.ActiveDocument.Protect wdAllowOnlyFormFields, Password:=strPassword
End Sub

wolfgrrl
09-20-2019, 07:38 AM
Try this.


Private Sub CommandButton2_Click() ' Browse & Select File
strPassword = "your password here"
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect Password:=strPassword
End If
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the File that you want to insert"
If .Show = True Then
FiletoInsert = .SelectedItems(1)
Else
Exit Sub
End If
End With
Application.ActiveDocument.Protect wdAllowOnlyFormFields, Password:=strPassword
End Sub


Thank you! This helped!!!