How do I apply a style to multiple selections in W

2019-02-11 09:10发布

I created a macro that will apply a particular style to whatever is selected in the document. However, when in draft view, when the user clicks in the style area pane to select a paragraph and then Ctrl + clicks on an additional paragraph, this additional selection is not applied when this macro is run:

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

What do I need to add to this? Note: The workflow cannot change so that the user selects that actual text in the document; they are set on using the style area pane...

The workflow is as follows:

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

The (undesired) output is as follows:

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

1条回答
来,给爷笑一个
2楼-- · 2019-02-11 09:18

Looks like your style "Body Text,bt" is a pure paragraph style. That means it will only be applied to a complete paragraph.

However, in your screenshot there is only part of the second paragraph selected. Make sure the complete paragraph is selected or, if the style should only be applied to part of the paragraph, make your style "Body Text,bt" a linked (paragraph and character) style.

Programmatic access to discontiguous selections is very limited, and such selections can only be created using the Word UI. The MSDN article Limited programmatic access to Word discontiguous selections gives some more details.

If applying the style only to part of the paragraph (by making it a linked style) is not what you want you probably have to come up with a hack like this:

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

You probably want to add some error handling as well to make sure that the temporary style used is finally removed from the document.

查看更多
登录 后发表回答