.replacement.highlight = true在MS Word VBA中不起作用

时间:2016-07-04 16:31:26

标签: vba excel-vba word-vba highlighting excel

我在Excel VBA中处理更大的项目并遇到以下问题。我使用VBA使Excel在MS Word中编译模板。我想强调模板黄色中的某些短语。它曾经在某个时候起作用,但之后就停止了,原因并不明显。当我现在运行代码时,部件执行时没有错误,但是单词不会突出显示,即使我确定它们在模板中。我使用debug.print查找.replacement.highlight值的值,它在立即窗口中显示9999999,如果我将鼠标光标悬停在中断模式下的表达式上,则显示-1。

代码的相关片段如下所示:

Dim WdApp As Word.Application
Set WdApp = New Word.Application
With WdApp
    .ActiveDocument.Select
    With .Selection.Find
    'the code creating the document and writing the template continues here
        .ClearFormatting
        .Text = "{Optional: Please also confirm the terms of transactions and other key information (for example: rights of return, allowances and rebates, special agreements, payment terms, incoterms, etc.) which may affect the accounting for the transactions.}"
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = PlaceholderAdditionalInfoRequest
        .Replacement.Text = .Text
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = "<<<@@@Client's Letterhead@@@>>>"
        .Replacement.Text = .Text
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = "{Optional: A statement of account with the above invoices marked is attached. ALTERNATIVELY: Copies of the above invoices are attached.}"
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
   End With
End With

有人知道发生了什么吗?我很感激任何指针,特别是如果用简单的英语表达的话:)我是VBA的新手,并且没有正式的编程教育。

致以最诚挚的问候,

TYRO

1 个答案:

答案 0 :(得分:0)

试试这个:

Options.DefaultHighlightColorIndex = wdYellow

之前:

With .Selection.Find

您似乎不是将Find函数应用于模板,而是应用于在创建模板之前激活的文档。 尝试移动这些行:

the code creating the document and writing the template continues here…

在这些行之前:

.ActiveDocument.Select With .Selection.Find

使Word应用程序WdApp可见(WdApp.Visible = True)以查看代码正在执行的操作,并确保在任务完成后将其关闭(WdApp.Quit)。