none
Run Macro on Protected Word Document RRS feed

  • Question

  • Good morning!

    I was hoping for some help on a simple VBA issue. I am new to this and still learning, so explicit instructions or examples would really help! I made a document with a button that functions to auto-create pre-formatted rows in a document that will be used by others in my company. However, I want to protect this document so that they can only edit in fill in forms and use the button to add new rows to the tables. But the issue arises when I protect the file. 

    The button function is:

    Sub CommandButton1_Click
    Dim i As Integer 
    For i = 2 To 2 
    ActiveDocument.Tables(5).Rows(i).Select 
    Selection.Copy 
    ActiveDocument.Tables(5).Rows.Add ActiveDocument.Tables(5).Rows(ActiveDocument.Tables(5).Rows.Count).Range.Paste ActiveDocument.Tables(5).Rows.Last.Delete 
    Next i
    End Sub
    

    This code works perfectly to add pre-created rows to a certain table. And I have two buttons that function to automatically add to two separate tables.

    Yet, when I protect the file, I get:

    Run-time error '4605'

    This method or property is not available because the object refers to a protected area of the document.

    When I click to debug, the highlighted issue is with the Selection.Copy (line 5 above).

    Thank you again for all your help in this, its a great learning experience and if I can find this solution, it would be super helpful to apply to a bunch of different documents.

    Thanks!!

    Becca :)

    Wednesday, October 23, 2019 3:03 PM

All replies

  • Try this version:

    Sub CommandButton1_Click()
        ActiveDocument.Unprotect Password:="secret"
        With ActiveDocument.Tables(5)
            .Rows(2).Range.Copy
            .Rows.Add
            .Rows(.Rows.Count).Range.Paste
            .Rows.Last.Delete
        End With
        ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True, Password:="secret"
    End Sub

    Replace "secret" with the password that you used to protect the document ("" if none)


    Regards, Hans Vogelaar (http://www.eileenslounge.com)

    Wednesday, October 23, 2019 8:46 PM