2012-07-14 26 views
1

我想搜索整個MSWord文檔以查找帶有通配符的文本並恢復找到的字符串。使用VBA在Word中搜索帶有Content.Find對象的文本,並恢復找到的文本

類似的東西:

Sub Macro1() 
    Dim c As Range 
    Set c = ActiveDocument.Contentsdf 
    c.Find.ClearFormatting 
    c.Find.Replacement.ClearFormatting 
    With c.Find 
     .Text = "start[abcde]end" 
     .Replacement.Text = "" 
     .Forward = True 
     .wrap = wdFindStop 
     .Format = False 
     .MatchCase = False 
     .MatchWholeWord = False 
     .MatchWildcards = True 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False ' 
    End With 

    c.Find.Execute 
    While c.Find.Found 
     Debug.Print c.Find.TextFound 
     c.Find.Execute 
    Wend 
End Sub 

c.Find.TextFound不存在的方法。有什麼方法可以在沒有重複發生的情況下恢復文本到Selection.Text

+0

你要搜索'* abcde *'還是'start * end'? – 2012-07-14 10:55:10

+0

我想搜索以「開始」開頭的字符串,以「結束」結尾,並在中間包含任何「a」,「b」,「c」,「d」,「e」字母。 – javier 2012-07-14 11:58:26

+0

你能舉個例子嗎? 'start [a] end'或者'start [asd] end'或者'startaend'或者'startasdend' – 2012-07-14 12:03:40

回答

2

試試這個。

Sub Sample() 
    Dim c As Range 
    Dim StartWord As String, EndWord As String 

    StartWord = "Start": EndWord = "End" 

    Set c = ActiveDocument.Content 
    c.Find.ClearFormatting 
    c.Find.Replacement.ClearFormatting 
    With c.Find 
     .Text = StartWord & "*" & EndWord 
     .Replacement.Text = "" 
     .Forward = True 
     .Wrap = wdFindStop 
     .Format = False 
     .MatchCase = False 
     .MatchWholeWord = False 
     .MatchWildcards = True 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False ' 
    End With 

    c.Find.Execute 
    While c.Find.Found 
     Debug.Print c.Text 
     '~~> I am assuming that the start word and the end word will only 
     '~~> be in the start and end respectively and not in the middle 
     Debug.Print Replace(Replace(c.Text, StartWord, ""), EndWord, "") 
     c.Find.Execute 
    Wend 
End Sub 
+0

非常感謝。我會嘗試! – javier 2012-07-14 20:56:16

相關問題