2015-04-06 162 views
-1

我對VBA相當陌生。我在來自各種作者的大文檔中用標題樣式標記文本。是否可以在粗體文本行上標識數字模式,並將適當的樣式應用於整行(通常在行尾有硬回車)。使用Word VBA,基於數字模式應用各種標題樣式

例如,我們的文檔經常被編號爲如下所示,並且我們會相應地標記文本。

1.0 text here  (apply Heading 1) 
1.2 text here  (apply Heading 2) 
1.2.1 text here (apply Heading 3) 
1.2.1.1 text here (apply Heading 4) 

2.0 text here  (apply Heading 1) 
2.2 text here  (apply Heading 2) 
….and so on 

我做了很多研究,但我不確定這是否可能。我們不使用任何類型的自動編號。

回答

0

是的,這是可能的。試試這個代碼:

Sub ApplyHeadings() 
    Dim rg1 As Range 
    Dim rg2 As Range 
    Dim pos As Long 
    Dim i As Long 
    Dim dots As Long 

    Set rg1 = ActiveDocument.Range 
    With rg1.Find 
     .MatchWildcards = True 
     .Text = "[0-9.]{2,}[!^13]@[^13]" 
     .Wrap = wdFindStop 
     While .Execute 
      Set rg2 = rg1.Duplicate 
      dots = 0 
      ' isolate the numbering 
      pos = InStr(rg2.Text, " ") 
      If pos > 0 Then rg2.End = rg2.Start + pos - 1 
      For i = 1 To Len(rg2.Text) 
       ' count the dots in the number 
       If Mid(rg2.Text, i, 1) = "." Then dots = dots + 1 
      Next i 
      ' apply correct heading level 
      Select Case dots 
       Case 1 
        If Mid(rg2.Text, 3, 1) = "0" Then 
         rg1.Style = ActiveDocument.Styles("Heading 1") 
        Else 
         rg1.Style = ActiveDocument.Styles("Heading 2") 
        End If 
       Case 2, 3 ' maybe more... 
        rg1.Style = ActiveDocument.Styles("Heading " & CStr(dots + 1)) 
       Case Else 
        ' do nothing 
      End Select 
      ' prepare for next find 
      rg1.Collapse wdCollapseEnd 
     Wend 
    End With 
End Sub 
+0

這真是太棒了謝謝!!!我甚至不確定這樣的事情是否有可能。節省多少時間! 有沒有什麼辦法可以在那裏只選擇粗體段落?現在,如果在引用特定部分的文本正文中有數字,它也將標題樣式應用於整個段落。 再次感謝你的幫助。 –

+0

我想通了,在行「.MatchWildcards = True」下面添加了「.Font.Bold = True」,所以它只會選擇實際上應該是標題的行。它現在幾乎可以完美運行,除非編輯小文檔(大約15頁)才能運行。如果該文件更大,Word 2010停止響應。 –

相關問題