Visual Basic下拉字段必需



在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

对于任何表单字段,简单的解决方案是测试它是显示默认文本还是为空。例如,您可以将下面给出的'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

我有同样的问题和使用相同的代码。这段代码仍然可以用于下拉;不幸的是,使用这段代码,您将强制用户键入他们的答案,而不是要求用户从预先设计的列表中进行选择。

为了在下拉菜单中使用这个特定的代码,结果需要等于我们想要触发该消息的内容。即"选择一个项目"。因此,现在列表中的第一个选择应该是"选择一个项目",这样当用户切换到选项卡时,它将提示该消息并强制用户做出响应。我希望能找到一个比这更好的解决方案,但它看起来是这样的。

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
End Sub

最新更新