Excel VBA - 生成新的 Word 文档并保护表单

Excel VBA - Generate New Word Document and Protect for Forms

我有一个启用了宏的 excel 文件(请注意,这是 Mac 上的 运行,使用 Office for Mac),其中有几个已保存的宏,其中之一即:

  1. 从保存的 .dotx 模板文件创建一个新的 .docx 文档文件。
  2. 使用电子表格中的数据填充新 .docx 文件中的书签。
  3. 保护新文档,只允许最终用户编辑表单域。
  4. 将新文档保存到特定文件夹。

我当前的代码除了第 3 点外都可以使用,我已经使用 Document.Protect 方法来应用所需的保护,但似乎没有 effect/doesn 不起作用。也没有显示错误消息。请参阅下面的当前代码:

Sub GenerateDocType(DocType As String)
    Dim form As Worksheet
    Dim db As Worksheet
    Dim WordApp As Object
    Dim WordDoc As Object
    Dim InPath As String
    Dim OutPath As String
    Dim OutFile As String
    Dim temp As String
    
        Set form = Worksheets("Bookings")
        Set db = Worksheets("Database")
    
        On Error Resume Next
        Set WordApp = GetObject(, "Word.application")
        If Err = 429 Then
            Set WordApp = CreateObject("Word.application")
            Err.Clear
            Application.Wait (Now + TimeValue("0:00:03"))
        End If
        On Error GoTo 0
        Set WordApp = GetObject(, "Word.application")
        WordApp.Visible = True

        f = form.Range("Booking_Ref").Value
        With db.Range("G2", "G" & i)
            Set r = .Find(What:=f)
        End With
    
        InPath = ThisWorkbook.path & Application.PathSeparator & "Templates" & Application.PathSeparator & "Booking Form.dotx"
        Set WordDoc = WordApp.Documents.Add(InPath)
        
        With WordDoc.Bookmarks
             .Item("BookingRef").Range.InsertAfter CStr(db.Cells(r.Row, 7).Value)
             'Have removed other bookmark inserts as these are not relevant to issue, they are similar to above line
        End With
        
        OutPath = ThisWorkbook.path & Application.PathSeparator & "Bookings" & Application.PathSeparator
        OutFile = "Booking Form - " & Replace(form.Range("Booking_Ref").Value, "/", "") & ".docx"

        WordDoc.SaveAs2 OutPath & OutFile
        WordApp.ActiveDocument.Protect Type:=wdAllowOnlyFormFields, noreset:=True, Password:="password"
        'Above line seems to have no effect on new document created
        WordDoc.Save
        WordApp.Quit
End Sub

任何关于如何正确保护新 .docx 文件的帮助都将被应用,不确定在 Mac 上这样做是否可能是原因。

谢谢。

您似乎在使用后期绑定,这意味着您不能使用 Word 对象库中的常量和枚举,例如wdAllowOnlyFormFields。所以你的代码应该是:

WordDoc.Protect Type:=2, noreset:=True, Password:="password"