Word 2007 VBA - 制作一些文字BOLD&其他ITALIC

时间:2013-02-08 13:47:00

标签: vba formatting ms-word word-vba

我有以下代码从Excel Cell&替换我的Word文档中的特定文本(出于此问题的目的,Excel单元格已被纯文本字符串替换)。

数据":进入"是不变的,然后是数据" aaa bbb"可以是任何东西,直到我们到达" "这也是不变的。那么"之后的数据of"," ccc ddd eee"可以是任何东西,直到它击中" - "这也是不变的。

是否可以制作" aaa bbb"数据 BOLD &大写,同时制作" ccc ddd eee"数据进入 ITALICS

":转到 ccc ddd eee的 AAA BBB - "

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

1 个答案:

答案 0 :(得分: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