【问题标题】:.replacement.highlight = true in MS Word VBA does not work.replacement.highlight = true 在 MS Word VBA 中不起作用
【发布时间】:2016-11-06 10:38:56
【问题描述】:

我在 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 新手,没有接受过正规的编程教育。

最好的问候,

泰罗

【问题讨论】:

  • 我没有尝试过您的代码,但您是否尝试过在设置 .Replacement.Highlight 之前使用“.Replacement.ClearFormatting”以及 .ClearFormatting? (以防万一有些东西在不应该的时候“粘住”)

标签: vba excel ms-word highlighting


【解决方案1】:

试试这个:

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)。

【讨论】:

  • 起初它似乎可以工作,但后来就停止了。似乎重新启动系统(不仅仅是应用程序)会有所帮助,但问题相当不稳定,我发现很难将其归结为任何特定场景。有没有人遇到过类似的问题?
  • 嗨,还没有。我把笔记本电脑忘在办公室了,所以不能在周末试一试,但我明天会试一试,然后回复你。不过,我不认为我将 .find 函数应用于错误的文档,因为如果我输入 .Replacement.Text= "abc" 它将在适当的文档中被替换。我也不想在子例程结束时退出文档以允许用户编辑模板。我认为,当 sub 结束时,我确实将 WdApp 设置为空。我会试试 .Replacement.ClearFormatting 看看它是如何工作的。
  • 我猜其中一种解决方案奏效了。从那以后我就再也没有遇到过这个问题。但是,我没有时间对其进行广泛的测试,因为我也忙于其他事情。无论如何,感谢您的帮助。
猜你喜欢
  • 2018-10-02
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多