2009-08-16 28 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 

你可能想添加一些錯誤處理,以確保使用的臨時樣式最終從文檔中刪除。

相關問題