2009-08-16 30 views
0

我创建了一个宏,该文件将特定的样式应用于文档中的所选内容。但是,如果考虑到草案中,当在风格方面窗格中的用户点击来选择一个段落,然后按Ctrl +点击一个额外的段落,不应用这个额外的选择时,这个宏运行:如何将样式应用于使用VBA的Word中的多个选择?

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

在Word 2007中对我有用吗? – RBarryYoung 2009-08-16 18:10:01

回答

2

外貌像你的风格“Body Text,bt”是纯粹的段落风格。这意味着它只适用于一个完整的段落。

但是,在您的屏幕截图中,仅选择了第二段的一部分。确保选择了完整的段落,或者如果该样式只应用于段落的一部分,则将样式“Body Text,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 

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

相关问题