【问题标题】:Insert Table from Builiding Block in specified location in the word document.在 Word 文档中的指定位置从 Building Block 插入表格。
【发布时间】:2015-12-11 18:33:05
【问题描述】:

我想插入一个定义为构建块的表。我在文档中的指定位置放置了一个内容控件,并通过“selectcontetcontrolsbytag”引用它。不幸的是,当表格插入内容控件时,它被转换为 RichText。这是我的代码:

ThisDocument.SelectContentControlsByTag("TermsConditions").Item(1).Range = _
ActiveDocument.AttachedTemplate.BuildingBlockTypes.Item(wdTypeTables).Categories.Item("Terms and Conditions Translation").BuildingBlocks.Item("Terms and Conditions Eng")

您能帮我用正确的代码在指定位置插入构建块吗?我也希望这个构建块被另一个替换,当用户从用户表单、组合框等中选择其他项目时。

【问题讨论】:

    标签: vba excel ms-word


    【解决方案1】:

    我的问题的完整解决方案是:

    1. Cindy Meister 提出的解决方案替换内容中的内容 控制:
    2. 要更改内容控件“TermsConditions”中的内容,我添加了以下代码:

      如果 doc.SelectContentControlsByTag("TermsConditions").Item(1).Range.Text doc.SelectContentControlsByTag("TermsConditions").Item(1).PlaceholderText 那么 doc.SelectContentControlsByTag("TermsConditions").Item(1).Range.Cut 别的 结束如果

    【讨论】:

    • 如果您为经常重复使用的对象声明变量并使用它,您的代码将更有效地执行并且更易于阅读。例如: Dim ccTermConditions as Word.ContentControl : Set ccTermConditions = doc.SelectContentControlsByTag.Item(1) : If ccTermConditions.Range.Text ccTermConditions.PlaceholderText Then ccTermConditions.Range.Cut : End If (因为新行是不可能的在注释中,冒号 (:) 表示代码中的新行。)
    【解决方案2】:

    我不确定你所说的“它被转换为富文本”是什么意思......

    插入 BuildingBlock 的公认方法是使用将目标 Range 对象传递给的 BuildingBlock.Insert 方法。例如(基于您的代码示例):

    Dim doc as Word.Document
    Dim rngTarget as Word.Range
    Set doc = ActiveDocument
    Set rngTarget = doc.SelectContentControlsByTag("TermsConditions").Item(1).Range 
    doc.AttachedTemplate.BuildingBlockTypes.Item(wdTypeTables).Categories.Item("Terms and and Conditions Translation").BuildingBlocks.Item("Terms and Conditions Eng").Insert rngTarget, true
    

    查看 VBA 语言参考中的示例...

    此外,您不应在代码中使用 ThisDocument,而应使用 ActiveDocument。 (更好的是,声明一个 Document 对象,将 ActiveDocument 分配给它,然后使用它。)

    【讨论】:

    • 成功了!我是 VBA 的新手。一开始我尝试了插入方法,但我认为它只能与 Selection.Range 目标一起使用。无论如何,我目前正在尝试解决您的代码中的一个小缺陷。我只能将我的表格插入“termsConditions”内容控件一次。我正在寻找在内容控件中清除/重置/删除/内容(在这种情况下为表格!!比文本更棘手)而不删除它的代码。这将允许我将内容控件中的一个表替换为另一个表。你能帮帮我吗?
    • 内容控件是只包含表格,还是包含其他内容?如果只有表格,请确保内容控件的属性“无法删除内容控件”已激活。那么您应该能够删除整个 ContentControl.Range 而无需删除内容控件。
    • 是的,它包含一张桌子。我试过你的解决方案。那没起效。当我已经放置在某个表格中时,我无法删除内容。它也被保护不被删除。我找到了另一个解决方案。请在下面查看我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多