How to highlight text in a Word document using Vis

2019-09-14 07:20发布

问题:

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

(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!

回答1:

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

In VBA it's:

nDoc.Range.HighlightColorIndex = wdYellow

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.

Thanks again all!



回答2:

Did you try:

myDoc.Range.HighlightColorIndex = Word.WdColor.wdColorTurquoise 

https://msdn.microsoft.com/en-us/library/office/ff841064.aspx

I would not expect the code you posted to work in VBA as there is no Highlight Property from what I can gather.