如何防止重复内容控件嵌套(单词2016)

时间:2018-07-12 16:54:01

标签: ms-word word-vba word-2016

我在Word 2016中构建的表单存在问题,除了ContentControls和BuildingBlocks的常规文档之外,我从Microsoft找不到任何东西。

以下是我尝试使用添加和删除命令按钮以及名为InspectorName并标记为InspectorName的重复内容控件创建的简单Word表单的示例:

enter image description here

我使用以下vba代码将此内容控件作为BuildingBlock插入,同时在段落标记之前突出显示了内容控件

Public Sub getTemplateName()
 Dim objTemp As Template
 Dim myrange As Range
 Dim myblock As BuildingBlock
 Set objTemp = ActiveDocument.AttachedTemplate
 Set myrange = Selection.Range
 Set myblock = objTemp.BuildingBlockEntries.Add("InspectorName", _
 wdTypeCustom1, "InspectorName", myrange)
End Sub

我现在正在尝试构建一个过程,如果存在内容控件(即计数不为0),则将使用最后插入的内容控件的折叠范围来插入使用上述过程构建的构造块。这是我下面的代码。

Public Sub insertBuildingBlock()
 Dim objBB As BuildingBlock
 Dim myrange As Range
 Dim objTemp As Template
 Dim mycount As Integer
 Set objTemp = ActiveDocument.AttachedTemplate
 Set objBB = objTemp.BuildingBlockTypes(wdTypeCustom1) _
.Categories("InspectorName").BuildingBlocks("InspectorName")
 mycount = ActiveDocument.SelectContentControlsByTag("InspectorName").Count
 If mycount <> 0 Then
  Set myrange = ActiveDocument.SelectContentControlsByTag("InspectorName"). _
  Item(mycount).Range
  myrange.Collapse wdCollapseEnd
  objBB.Insert myrange
 End If
End Sub

此代码运行后会发生-两个内容控件嵌套。

enter image description here

我已经尝试了几乎所有我知道的东西,因此,任何输入将不胜感激!

1 个答案:

答案 0 :(得分:0)

折叠内容控件的“范围”时,范围的“焦点”仍在内容控件内。添加此行:

  myrange.MoveStart wdCharacter, 1

完整代码:

Public Sub insertBuildingBlock()
 Dim objBB As BuildingBlock
 Dim myrange As Range
 Dim objTemp As Template
 Dim mycount As Integer
 Set objTemp = ActiveDocument.AttachedTemplate
 Set objBB = objTemp.BuildingBlockTypes(wdTypeCustom1) _
.Categories("InspectorName").BuildingBlocks("InspectorName")
 mycount = ActiveDocument.SelectContentControlsByTag("InspectorName").Count
 If mycount <> 0 Then
  Set myrange = ActiveDocument.SelectContentControlsByTag("InspectorName"). _
  Item(mycount).Range
  myrange.Collapse wdCollapseEnd
  myrange.MoveStart wdCharacter, 1  '<-----
  objBB.Insert myrange
 End If
End Sub