2015-04-06 34 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停止响应。 –

相关问题