根据文档

时间:2018-02-02 20:43:32

标签: vba ms-word word-vba dropdown

我在Microsoft Word 2016中制作文档,我希望这是一个用户将填写的表单(使用下拉列表内容控件) - 从那里我已经为列表中的所有项目分配了数字他们的价值观我需要用一些单词(由值的总和确定)填充文本框,我遇到了麻烦。从未使用VBA-我甚至不知道我的第一行是否正确。我真的不确定如何开始文档以及如何填充所有下拉列表的总和。我没有使用其他文档中的宏,我只想根据用户在word文档中选择的内容进行填充。我在文本框中用标签命名我的字段,我想要文本" account" "帐户2"等出现。谢谢!

Set myField = Selection.FormFields(1)
If myField.Type = wdFieldFormDropDown Then
 Num = myField.DropDown.ListEntries.Count
 If Num >= 75 Then
 myField.Value = "Account 1"
 End If
 If Num > 50 Then
 myField.Value = "Account 2"
 End If
 If Num <= 50 Then
 myField.Value = "Account 3"
 End If
 End If
End Sub

1 个答案:

答案 0 :(得分:0)

If you plan to use Content Controls then FormField object in your code is not correct. Form fields are "legacy" - they're still quite useful, but it's a different part of the object model.

Content Controls are "embedded" in the document and have events to trigger code. That means you need to double-click the ThisDocument entry in the Project for the parent document in the VB Editor. Then select "Document" from the dropdown to the left of the Code Window and "ContentControlOnExit" from the dropdown on the right. That will insert the event stub in the code window for ThisDocument (see picture).

enter image description here

A Content Control event will trigger for all content controls in the document, which means you need to distinguish which content control triggered it. The event passes in a ContentControl object which can be tested for this purpose, usually using Select Case.

The sample code shows how to do this, how to get the count of the ListEntries, how to select a specific content control by its title (or by its tag) and how to write content to the content control. (Since what you want to do with Num in your code, above, is not clear to me I don't try to include that. But it looks like here, as well, you could use Select Case.)

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _
                                          Cancel As Boolean)
    Dim cc As Word.ContentControl
    Dim doc As Word.Document
    Dim countListEntries As Long

    Set doc = ContentControl.Parent
    Select Case ContentControl.Title
        Case "SelectAccount"
            countListEntries = ContentControl.DropdownListEntries.Count
            Set cc = doc.SelectContentControlsByTitle("Account").Item(1)
            'Set cc =doc.SelectContentControlsByTag("Account").Item(1)
            cc.Range.Text = ContentControl.Range.Text & " " & countListEntries
        Case Else
    End Select
End Sub