2016-08-04 107 views
0

我使用正則表達式搜索來查找MS-Word文檔中的特定單詞,並將搜索結果存儲到變量中。我的問題是我只想爲搜索結果應用自定義樣式將樣式應用於特定單詞

輸入: 全球[1,2]。在[1,3,4] [1,2,4,5] [1,2,6,7,8] [1,2] [1,2]

之前,期間或之後,我正在使用以下代碼

Sub RegexReplaces() 
    Set matches = New regExp 
    Dim Sure As Integer 
    Dim rng As Range 
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])" 
    matches.Global = True 
    Dim mat As MatchCollection 
    Set mat = matches.Execute(ActiveDocument.Range) 
    For Each m In mat 
     Sure = MsgBox("Are you sure?" + m, vbOKCancel) 
     If Sure = 1 Then 
      m.Style = ActiveDocument.Styles("Heading 1") 'this is the error line 
     Else 
      MsgBox "not1111" 
     End If 
    Next m 
End Sub 

回答

1

For Each m In mat循環遍歷mat集合中的每個項目。 M不是一個範圍。您需要設置從m.FirstIndex開始到m.FirstIndex + m.Length結束的範圍。然後,您需要選擇範圍並使用Selection.Style來設置範圍的樣式。

Sub RegexReplaces() 
    Set matches = New regExp 
    Dim Sure As Integer 
    Dim rng As Range 
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])" 
    matches.Global = True 
    Dim mat As MatchCollection 
    Set mat = matches.Execute(ActiveDocument.Range) 
    For Each m In mat 
     Sure = MsgBox("Are you sure?" + m, vbOKCancel) 
     If Sure = 1 Then 

      Set rng = ActiveDocument.Range(Start:=m.FirstIndex, End:=m.Length + m.FirstIndex) 
      rng.Select 
      Selection.Style = ActiveDocument.Styles("Heading 1") 
     Else 
      MsgBox "not1111" 
     End If 
    Next m 
End Sub 
+0

非常感謝答案,因爲我非常擔心如何做到這一點。這個答案對我來說意義重大。 – Kevin

+0

我很高興能幫上忙!感謝您接受我的回答。 – 2016-08-04 08:47:09

相關問題