2013-02-08 19 views
2

我有以下代碼從Excel單元格中選擇數據&取代了我的Word文檔中的一段特定文本(就這個問題而言,Excel單元格已被替換由純文本字符串)。Word 2007 VBA - 編寫一些文本BOLD和其他ITALIC

數據「:去」是恆定的,那麼數據「aaa bbb」可以是任何東西,直到我們到達「也」是恆定的。那麼在「之後」,「ccc ddd eee」之後的數據可以是任何東西,直到它碰到也是恆定的「 - 」。

是否有可能使 「AAA BBB」 數據BOLD &大寫,而使得 「CCC DDD EEE」 數據爲斜體

「:去AAA BBB CCC的 DDD EEE - 」

Selection.HomeKey Unit:=wdStory 
Selection.Find.ClearFormatting 
Selection.Find.Replacement.ClearFormatting 
With Selection.Find 
    .Text = "MOTMDIV1" 
    .Replacement.Text = ": goes to aaa bbb of ccc ddd eee - " 
    .Forward = True 
    .Wrap = wdFindContinue 
    .Format = False 
    .MatchCase = True 
    .MatchWholeWord = False 
    .MatchWildcards = False 
    .MatchSoundsLike = False 
    .MatchAllWordForms = False 
End With 

Selection.Find.Execute Replace:=wdReplaceAll 

回答

2

如果你改變你的查找和替換單一查找和全部替換,Word將突出替換文本允許你可以改變被替換範圍的屬性。我已經修改了你的代碼中強調這一點:

Sub ReplaceAndFormat() 
    Dim sConst1 As String, sConst2 As String, sReplaceMent As String 
    Dim rRange As Range, rFormat As Range 

    'Set your constants. This is where you can read in from Excel or whereever 
    sConst1 = "aaa bbb" 
    sConst2 = "ccc ddd eee" 

    'Build the replacement string 
    sReplaceMent = ": goes to " & sConst1 & " of " & sConst2 & " - " 

    'Your replacement code 
    Selection.HomeKey Unit:=wdStory 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    With Selection.Find 
     .Text = "MOTMDIV1" 
     .Replacement.Text = sReplaceMent 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = False 
     .MatchCase = True 
     .MatchWholeWord = False 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
     .Execute Replace:=wdReplaceOne 

     'If we replace one by one Word will select the range after it finds it 
     If .Found Then 
      'After you've done the replacement, set it to a range so you can format 
      Set rRange = Selection.Range 

      'We know the length of all the strings so we can set the range of the "aaa bbb" etc etc 
      Set rFormat = ActiveDocument.Range(rRange.Start + 10, rRange.Start + 10 + VBA.Len(sConst1)) 
      'Set the formats for the first part 
      rFormat.Font.Bold = True 
      rFormat.Font.AllCaps = True 

      'Repeat for the second part 
      Set rFormat = ActiveDocument.Range(rRange.Start + 14 + VBA.Len(sConst1), rRange.Start + 14 + VBA.Len(sConst1) + VBA.Len(sConst2)) 
      rFormat.Font.Italic = True 
     End If 
    End With 
End Sub 

注:Repeating Microsoft Word VBA until no search results found

+0

我:如果你想查找和替換搜索文本的所有instantences那麼你會通過這樣的文件必須循環看看這個週末吧,我現在不能喝了,因爲我喝了幾杯啤酒,但是謝謝CuberChase ... – 2013-02-08 22:56:58

+0

不用擔心隊友。你知道他們在澳大利亞這裏說什麼。 「如果你喝酒和編碼你是一個血腥的白癡」。哦,不用等,這是關於駕駛。 – CuberChase 2013-02-08 23:39:58

+0

對不起,我還沒有回到你身邊,一直卡在代碼的不同部分......沒有忘記這個!這是一個很好的工作,喝酒和編碼不會被忽視,我從來沒有做任何事情;-)! – 2013-02-12 18:40:08

相關問題