2016-08-23 300 views
1

如何將一個段落與一個編號標題的文本部分對齊? e.g:Word VBA匹配段落標題文字縮進

1.1.2 This Is A Numbered Heading 
     This is the aligned text I'm trying to achieve 
This is aligned to the numbers not the text 

2.4 This Is Another Example 
    This is where the text should be 

我知道了CharacterUnitLeftIndent,CharacterUnitFirstLineIndent,FirstLineIndent等方面的性能,但幾個小時的實驗&在線搜索無法弄清楚如何以編程方式實現這一目標後。我知道如何測試標題樣式以及如何參考以下段落,所以只需知道如何獲得縮進權限即可。

回答

1

要使用宏來實現此目的,您必須檢查文檔中的每個段落,並檢查它是否是「標題」樣式。如果是,則選取第一個製表符的值設置爲後續段落的縮進。

UPDATE1:下面代碼的早期版本中設置的段落爲Document級第一個製表位,並沒有準確地抓住了Heading風格的製表位集。以下代碼更新可準確確定每個Heading縮進製表符。

UPDATE2:示例文本原始我在該第一文獻中示出使用:

enter image description here

自動執行第一行縮進前述標題的標籤級別的代碼是原始Sub從第一個例子:

Option Explicit 

Sub SetParaIndents1() 
    Dim myDoc As Document 
    Set myDoc = ActiveDocument 

    Dim para As Paragraph 
    Dim firstIndent As Double 'value in "points" 
    For Each para In myDoc.Paragraphs 
     If para.Style Like "Heading*" Then 
      firstIndent = myDoc.Styles(para.Style).ParagraphFormat.LeftIndent 
      Debug.Print para.Style & " first tab stop at " & _ 
         firstIndent & " points" 
     Else 
      Debug.Print "paragraph first line indent set from " & _ 
         para.FirstLineIndent & " to " & _ 
         firstIndent 
      para.FirstLineIndent = firstIndent 
     End If 
    Next para 

    '--- needed to show the changes just made 
    Application.ScreenRefresh 

End Sub 

而結果看起來l IKE在此(紅線手動添加,以顯示對齊): enter image description here

如果你想在對齊縮進標題樣式整段,該代碼被修改成這樣:

Option Explicit 

Sub SetParaIndents2() 
    Dim myDoc As Document 
    Set myDoc = ActiveDocument 

    Dim para As Paragraph 
    For Each para In myDoc.Paragraphs 
     If para.Style Like "Heading*" Then 
      '--- do nothing 
     Else 
      para.Indent 
     End If 
    Next para 

    '--- needed to show the changes just made 
    Application.ScreenRefresh 

End Sub 

的,所得文本看起來像這樣: enter image description here

+0

非常感謝您的建議。我運行了你的代碼,它縮進了第一行,超出了標題的文本(大約2英寸左右),用於接下來的段落的第一行,但是保持段落的其餘部分不變。是否可以修改以設置正確縮進並影響整個段落? – Absinthe

+0

您只需要將'Paragraph'告知'Indent',它就會自動選取前面標題樣式的製表符。我在示例中使用的樣式是內置的「標題1」,「標題2」和「標題3」。 – PeterT

+0

這對我來說不起作用,但我猜這是因爲我給出的文檔狀態糟糕,而不是你的解釋。感謝你的深入,我學到了很多東西。我通過迭代每個段落並強制縮進來通過自定義樣式匹配頁眉來匹配它。 – Absinthe