代码之家  ›  专栏  ›  技术社区  ›  JohnZaj

如何使用VBA将样式应用于Word中的多个选项?

  •  0
  • JohnZaj  · 技术社区  · 16 年前

    我创建了一个宏,它将对文档中选择的任何内容应用特定的样式。但是,在草稿视图中,当用户单击样式区域窗格以选择段落,然后按住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

    1 回复  |  直到 16 年前
        1
  •  3
  •   Dirk Vollmar    16 年前

    看起来你的风格“正文,bt”是一个纯粹的段落风格。这意味着它只适用于完整的段落。

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

    对不连续选择的编程访问非常有限,并且只能使用单词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
    

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

    推荐文章