2016-07-04 94 views
0

我正在处理Excel VBA中的大型项目并遇到以下问题。我使用VBA使Excel在MS Word中编译模板。我想在模板中突出显示某些短语黄色。它曾经在某个时刻工作,但之后停止工作,原因不明。当我现在运行代码时,该部分无错地执行,但这些单词不会突出显示,即使我确信它们在模板中。我使用debug.print来查找.replacement.highlight值的值,并在立即窗口中显示9999999,如果将鼠标光标悬停在中断模式下的表达式上,则显示-1。.replacement.highlight = true在MS Word中VBA不起作用

代码的相关片段引述如下:

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 [email protected]@@>>>" 
     .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

+0

我还没有尝试过你的代码,但是在你设置.Replacement.Highlight之前,你是否尝试过使用“.Replacement.ClearFormatting”以及.ClearFormatting? (以防万一某些东西在它不应该“粘住”的时候) – 2016-07-05 09:41:31

回答

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 )完成任务后。

+0

起初它看起来好像会起作用,但随后就停止了。这似乎是重新启动系统(不只是应用程序)的帮助,但问题是相当不稳定的,我发现很难将其固定在任何特定的情况下。有没有人遇到过类似的问题? – Tyro

+0

你是否应用了最后的变更?任何更新? – EEM

+0

嗨,还没有。我把我的笔记本电脑留在了办公室,所以周末不能试一试,但我明天会试一试并回复你。不过,我不认为我将.find函数应用于错误的文档,因为如果我键入.Replacement.Text =“abc”,它将在适当的文档中被替换。我还希望不要在子例程结束时退出文档以允许用户编辑模板。我认为,当子结束时,我确实将WdApp设置为无。我会尝试.Replacement.ClearFormatting,看看它是如何工作的。 – Tyro

相关问题