2

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

数据“: go to”是不变的,那么数据“aaa bbb”可以是任何东西,直到我们到达“of”,它也是不变的。那么“of”之后的数据,“ccc ddd eee”可以是任何东西,直到它碰到“-”,这也是恒定的。

是否可以将“aaa bbb”数据设为粗体和大写,同时将“ccc ddd eee”数据设为斜体

“:去ccc ddd eeeAAA 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
4

1 回答 1

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

于 2013-02-08T21:21:37.100 回答