访问VBA不会更改Word颜色

时间:2018-09-13 00:14:33

标签: ms-access access-vba

我正在使用Access更改Word文档中的值,并且我希望将小于零的数字的字体颜色更改为红色。这是我的通话代码:

Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Activate
Set doc = oWord.Documents.Open(fpath & "AF Final Costs Notification template.docx", True)
Set oSelection = oWord.Documents(1).Content
oSelection.Select
Set sel = oWord.Selection

Source_Text = "[EstProjCost_AF]"
Replacement_Text = Format(Me.EstProjCost_IF, "currency")
Call Replace_Text(sel, Source_Text, Replacement_Text)

这是我的子程序:

Private Sub Replace_Text(sel, Source_Text, Replacement_Text)

Replacement_Text = Nz(Replacement_Text, "--NULL--")
With sel
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    With .Find
        .Text = Source_Text
        .Replacement.Font.Color = wdColorBlack
        If IsNumeric(Replacement_Text) Then
            If Replacement_Text < 0 Then
                .Replacement.Font.Color = wdColorRed
            End If
        End If
        .Replacement.Text = Replacement_Text
        .Forward = True
        .Wrap = 1 'wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        sel.Find.Execute Replace:=2  'wdReplaceAll
    End With
End With

End Sub

任何帮助将不胜感激。

ETA:这是Word宏,可以正常运行:     子change_font()     昏暗Replacement_Text作为字符串

'
' change_font Macro
'
'
    Replacement_Text = "def"
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    If IsNumeric(Replacement_Text) Then
        If CInt(Replacement_Text) < 0 Then
            Selection.Find.Replacement.Font.Color = wdColorRed
        End If
    End If
    With Selection.Find
        .Text = "abc"
        .Replacement.Text = Replacement_Text
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

1 个答案:

答案 0 :(得分:0)

我能够找到解决方法。由于我要更改的所有文本都具有“(-9999.99)”模式,因此我在最后一次替换之后添加了以下代码:

With sel
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find.Replacement.Font.Color = wdColorRed
    With .Find
        .Text = "\(-*\)"
        .Replacement.Text = "^&"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    .Find.Execute Replace:=wdReplaceAll
End With

我仍然想知道为什么原始代码无法正常工作,但是也许有一个更好的论坛可以要求...