需要 Visual Basic 下拉字段

问题描述 投票:0回答:2

在word中制作表格时,是否有代码可以使下拉列表成为必填字段。我有代码使自由文本字段成为必填字段,但没有下拉列表。以下是我的免费文本

Sub MustFillIn()
    If ActiveDocument.FormFields("CompName").Result = "" Then
        Do
            sInFld = InputBox("This field is required, please fill in below.")
        Loop While sInFld = ""
        ActiveDocument.FormFields("CompName").Result = sInFld
    End If
End Sub
vba drop-down-menu ms-word required
2个回答
0
投票

任何表单域的简单解决方案是测试它是否显示默认文本或为空。例如,您可以将下面的“GetBkMk”作为 on_entry 宏,将“MustComplete”宏作为 on_exit 宏,让每个“强制性”表单域。文档中的所有文本和下拉表单域只需要一对这样的宏。

Option Explicit
Dim BkMk As String, bSel As Boolean

Sub AutoOpen()
With ActiveDocument.FormFields(1)
  If .EntryMacro = "GetBkMk" Then BkMk = .Name
End With
End Sub

Sub GetBkMk()
  If bSel = False Then
    BkMk = Selection.Bookmarks(1).Name
    bSel = True
  Else
    With ActiveDocument.Bookmarks(BkMk).Range.Fields(1)
      If .Type = wdFieldFormTextInput Then .Result.Select
      If .Type = wdFieldFormDropDown Then .Select
    End With
  End If
End Sub

Sub MustComplete()
With ActiveDocument.FormFields(BkMk)
  Select Case .Type
    Case wdFieldFormTextInput
      If .Result = .TextInput.Default Or .Result = "" Then
        bSel = True
        Application.OnTime When:=Now + TimeValue("00:00:01"), Name:="GetBkMk"
        MsgBox "This field is required, please complete it."
      Else
        bSel = False
      End If
    Case wdFieldFormDropDown
      If .Result = .DropDown.ListEntries(1).Name Then
        bSel = True
        Application.OnTime When:=Now + TimeValue("00:00:01"), Name:="GetBkMk"
        MsgBox "This field is required, please make a selection."
      Else
        bSel = False
      End If
  End Select
End With
End Sub

0
投票

我和你有同样的问题并且使用了相同的代码。这段代码仍然可以用于下拉菜单;不幸的是,使用此代码,您将强制用户键入他们的答案,而不是要求用户从预先设计的列表中进行选择。 为了将此特定代码与下拉列表一起使用,结果需要等于我们想要触发此消息的结果。即“选择一个项目”。所以,现在列表中的第一个选项应该是“选择一个项目”,所以当用户使用 Tab 键结束时,它会提示该消息并强制用户做出响应。我希望找到比这更好的解决方案,但这就是它的样子。

Sub MustFillIn()
If ActiveDocument.FormFields("CompName").Result = "Choose an item" Then
    Do
        sInFld = InputBox("This field is required, please fill in below.")
    Loop While sInFld = "Choose an item"
    ActiveDocument.FormFields("CompName").Result = sInFld
End If

结束子

© www.soinside.com 2019 - 2024. All rights reserved.