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

Excel VBA-生成新Word文档并保护表单,excel,vba,macos,ms-word,Excel,Vba,Macos,Ms Word,我有一个启用宏的excel文件(请注意,该文件在使用Office for Mac的Mac上运行),其中有几个保存的宏,其中一个是: 从保存的.dotx模板文件创建新的.docx文档文件 使用电子表格中的数据填充新.docx文件中的书签 保护新文档以仅允许最终用户编辑表单字段 将新文档保存到特定文件夹 除了第3点之外,我当前使用的代码有效,我使用Document.Protect方法应用所需的保护,但似乎没有效果/不起作用。也没有显示错误消息。请参见下面的当前代码: Sub GenerateDocT

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

  • 从保存的.dotx模板文件创建新的.docx文档文件
  • 使用电子表格中的数据填充新.docx文件中的书签
  • 保护新文档以仅允许最终用户编辑表单字段
  • 将新文档保存到特定文件夹
  • 除了第3点之外,我当前使用的代码有效,我使用Document.Protect方法应用所需的保护,但似乎没有效果/不起作用。也没有显示错误消息。请参见下面的当前代码:

    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"