【问题标题】:Word VBA - How to stop people from saving a form if they have not filled out required fields using DocumentBeforeSave?Word VBA - 如果人们没有使用 DocumentBeforeSave 填写必填字段,如何阻止他们保存表单?
【发布时间】:2020-06-24 20:40:14
【问题描述】:

如果未填写所有必填字段,我目前正在制作表单并试图阻止某人执行“另存为”或“保存”。下面的示例只是工程师姓名的一个字段。目的是如果用户在这种情况下没有填写名为“EngName”的表单字段,则文档将显示错误消息“保存已取消,需要工程师姓名”。我想我很接近,但不了解 VBA,希望能提供任何帮助。

Public WithEvents App As Word.Application

Private Sub Document_Open()
Set App = Word.Application
End Sub

Private Sub App_DocumentBeforeSave(ByVal Doc as Document, SaveAsUI AS Boolean, Cancel As Boolean)
    With ActiveDocument.FormFields("EngPhone")
       If Len(.Results) < 1 Then Cancel = True
           MsgBox ("Save Cancelled, Engineer Name Required")
       End If
    End With
End Sub

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    试试:

    Private Sub wdApp_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    If Trim(ActiveDocument.FormFields("EngPhone").Result) = "" Then
      Cancel = True
      MsgBox ("Save Cancelled, Engineer Name Required")
    End If
    End Sub
    

    您需要将上述代码添加到“ThisApplication”类模块中,并且仍然需要您的实例化代码,该代码位于普通代码模块中。更多详情请见:https://wordmvp.com/FAQs/MacrosVBA/AppClassEvents.htm

    【讨论】:

    • 当试图在 Visual Basic 中保存它并且在受限编辑中该字段为空时,它并没有阻止我保存但我并不完全肯定,如果这只是因为我只是没有以某种方式正确调用它来触发它
    • 好的,知道了。这是我第一次发现你甚至可以在 Word 中编码,所以希望这个方向足以让我完成这个,但我们会看到。无论如何谢谢你
    • 我从未感到如此欣喜若狂。我花了 8 个小时试图弄清楚,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多