如何使用Visual Basic突出显示Word文档中的文本

问题描述:

我不敢相信我无法找到这个(简单)问题的答案,但是我找不到. (例如,并没有真正的帮助,我也找不到答案此处.)我想这样做的目的是弄清楚如何使用Visual Basic(而非VBA)以编程方式(i)更改Word文档中特定段落或范围内的字体颜色,或(ii)突出显示文档中的相同文本. 我已经使用了以下各种排列方式:

I can't believe I'm not able to find the answer to this (simple) question, but I can't. (This for instance didn't really help, nor could I find an answer here.) All I want to do is to figure out how to use Visual Basic (not VBA) to programmatically (i) change the font colour in a specific paragraph or range in a Word document, or (ii) highlight the same text in the document. I've used various permutations of:

myDoc.range.font.ColorIndex = Word.WdColor.wdColorRed
myDoc.range.Highlight = Word.WdColor.wdColorTurquoise

(其中myDoc是Word文档),但会不断收到错误消息(例如,突出显示不是范围或段落的成员,或其他我尝试的内容).我可以在VBA中执行此操作,但是在VB中执行此操作使我很困惑. 我确定我缺少一些基本的知识,但我不知道是什么... 我正在使用Visual Studio 2015,Windows 10,Word 2010,并且在代码顶部有Imports Microsoft.Office.Interop和Imports Microsoft.Office.Interop.Word. 谢谢你的尽心帮助.一定要简单!

(where myDoc is a Word document), but keep getting error messages (eg, 'highlight not a member of range, or paragraphs, or whatever else I try). I can do this in VBA but doing this in VB has stumped me. I'm sure I'm missing something quite basic but I can't figure out what... I'm using Visual Studio 2015, Windows 10, Word 2010, and I've got Imports Microsoft.Office.Interop and Imports Microsoft.Office.Interop.Word at the top of my code. Thanks for any help you can offer. It's got to be simple!

感谢A Friend和Jason B为我解决了这个问题.
对于遇到此问题的其他人,最终对我有用的是:

Thanks to A Friend and Jason B for solving this for me.
For anyone else who's run into this, what worked for me finally was:

nDoc.range.HighlightColorIndex = WdColorIndex.wdYellow  
nDoc.range.font.colorindex = WdColorIndex.wdRed

在VBA中是:

nDoc.Range.HighlightColorIndex = wdYellow

TnTinMn,它可能是相同的对象模型,但是困难在于找出VB中有时需要的附加参数(或任何合适的词)(此处为"wdColorIndex"). Jason给出的链接是指向VBA的,但是到目前为止,我还没有找到VB的相应页面.

TnTinMn, it may be the same object model but the difficulty is figuring out the additional parameters (or whatever the right word is) that are sometimes needed in VB (here, 'wdColorIndex'). The link Jason gave is to a VBA reference but so far I've failed to find a corresponding page for VB.

再次感谢所有!