查找用给定颜色格式化的所有文本

时间:2016-05-31 08:36:21

标签: ms-word format word-vba find-replace

我正在寻找一种方法来创建一个新文档,其中包含我的文档中具有特定格式的所有文本。

见到目前为止我写的内容,但是我被困在这里:

  • 如何在文档结束时停止循环?或者如何为我的代码添加智能以避免静态循环,而是扫描我的所有文档"?
Option Explicit

Sub Macro1()
   Dim objWord  As Application
   Dim objDoc As Document
   Dim objSelection As Selection

    Dim mArray() As String
    Dim i As Long
    Dim doc As Word.Document

    For i = 1 To 100
      ReDim Preserve mArray(i)
      With Selection.Find
        .ClearFormatting
        .Font.Color = wdColorBlue
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
        .Execute
      End With

      mArray(i) = Selection.Text

    Next

   Set objWord = CreateObject("Word.Application")
   Set objDoc = objWord.Documents.Add
   objWord.Visible = True
   Set objSelection = objWord.Selection

    For i = 1 To 100
    objSelection.TypeText (mArray(i))
    Next
End Sub

1 个答案:

答案 0 :(得分:2)

感谢Cindy的好建议(我也可以在Loop through Word document, starting from beginning of file at start of each loop中找到相关信息),如果有一天这可以帮助某人:

  1. 通过Word的宏记录器

  2. 定义您要查找的格式
  3. 将自己定位在文档的开头

  4. 使用while循环检查wdFindStop - 它还演示了如何在VBA中使用String of String - :

  5. ...

    Sub Macro2()
        Dim mArray() As String
        Dim i As Long, n As Long
        Dim doc As Word.Document
        Dim isFound As Boolean
        isFound = True
        i = 1
        'For i = 1 To 40
        Do While (isFound)
          ReDim Preserve mArray(i)
          With Selection.Find
            .ClearFormatting
            .Font.Color = wdColorBlue
            .Text = ""
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = True
            isFound = .Execute
          End With
          mArray(i) = Selection.Text
          i = i + 1
        Loop
        'Next
        n = i - 2
        MsgBox n & " occurrences found."
    
        '
        ' create a new document with the phrases found
    
        Dim objWord  As Application
        Dim objDoc As Document
        Dim objSelection As Selection
        Set objWord = CreateObject("Word.Application")
        Set objDoc = objWord.Documents.Add
        objWord.Visible = True
        Set objSelection = objWord.Selection
        For i = 1 To n 'mArray's Size
          objSelection.TypeText (mArray(i))
          objSelection.TypeParagraph
        Next
    End Sub
    

    注意:我也可以从https://msdn.microsoft.com/en-us/library/office/aa211953%28v=office.11%29.aspx中获益匪浅,它解释了如何在不改变选择的情况下找到它:

     With ActiveDocument.Content.Find
      .Text = "blue"
      .Forward = True
      .Execute
      If .Found = True Then .Parent.Bold = True
     End With
    

    从这里开始:Find text only of style "Heading 1" (Range.Find to match style)