Word 2007中的VBA - 让一些文本加粗和其他ITALIC(Word 2007 VBA -

2019-08-16 20:12发布

我有以下代码从Excel细胞选择数据与替换我的Word文档中的特定一段文本(对于这个问题的目的,Excel单元已经由纯文本字符串替换)。

数据“:去”是不变的,则数据“AAA BBB”可以是任何东西,直到我们达到了“”这也是不变的。 再经过“的”的数据,“CCC DDD EEE”可以是任何东西,直到它击中了“ - ”,这也是不变的。

是否有可能使“AAA BBB”数据BOLD&大写,而使得“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

Answer 1:

如果你改变你的查找和替换单一查找和全部替换,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

注意:如果你想查找和替换搜索文本的所有instantences那么你会通过这样的文件必须循环: 重复的Microsoft Word VBA直到没有找到搜索结果



文章来源: Word 2007 VBA - Making some text BOLD & other ITALIC