【问题标题】:How do I apply a style to multiple selections in Word using VBA?如何使用 VBA 将样式应用于 Word 中的多个选择?
【发布时间】:2009-08-16 17:43:09
【问题描述】:

我创建了一个宏,它将对文档中选择的任何内容应用特定样式。但是,在草稿视图中,当用户在样式区域窗格中单击以选择一个段落,然后 Ctrl + 单击另一个段落时,运行此宏时不会应用此附加选择:

Sub BodyTextApply()
    Selection.Style = ActiveDocument.Styles("Body Text,bt")
End Sub

我需要添加什么?注意:工作流程无法更改,因此用户选择文档中的实际文本;它们被设置为使用样式区域窗格...

工作流程如下:

alt text http://img6.imageshack.us/img6/1994/91231840.png

(不需要的)输出如下:

alt text http://img34.imageshack.us/img34/1239/outputt.png

【问题讨论】:

  • 我在 Word 2007 上工作正常吗?

标签: vba ms-word coding-style selection


【解决方案1】:

看起来您的样式“Body Text,bt”是纯段落样式。这意味着它只会应用于一个完整的段落。

但是,在您的屏幕截图中,仅选择了第二段的一部分。确保选择了整个段落,或者,如果样式只应用于段落的一部分,则将您的样式“正文文本,bt”设置为链接(段落和字符)样式。

对不连续选择的编程访问非常有限,并且只能使用 Word UI 创建此类选择。 MSDN 文章Limited programmatic access to Word discontiguous selections 提供了更多详细信息。

如果仅将样式应用于段落的一部分(通过使其成为链接样式)不是您想要的,您可能必须想出这样的技巧:

Sub BodyTextApply()

    Dim oRange As Range

    ' create a temporary character style
    ActiveDocument.Styles.Add "_TEMP_STYLE_", wdStyleTypeCharacter

    ' apply the temporary style to the discontiguous selection
    Selection.Style = ActiveDocument.Styles("_TEMP_STYLE_")

    Set oRange = ActiveDocument.Range

    With oRange.Find
        .ClearAllFuzzyOptions
        .ClearFormatting
        .ClearHitHighlight
        .Style = ActiveDocument.Styles("_TEMP_STYLE_")
        .Text = ""
        .Wrap = wdFindStop

        ' search for all occurences of the temporary style and format the
        ' complete paraphraph with the desired style
        Do While .Execute
            oRange.Paragraphs(1).Style = ActiveDocument.Styles("Body Text,bt")
        Loop

    End With

    ' cleanup
    ActiveDocument.Styles("_TEMP_STYLE_").Delete

End Sub

您可能还想添加一些错误处理,以确保最终从文档中删除使用的临时样式。

【讨论】:

  • 非常感谢这个“Hack Around”。几天来我一直在寻找这样的解决方案。这让我很开心!!!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2020-02-21
  • 2020-04-10
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多