PDA

View Full Version : Modify font color in portion of table cell



slhussey
06-11-2012, 04:42 PM
I have a VB.NET program that is attempting to create a Word document that contains a table. The text is formatted using styles from a template. After adding the text, I need to optionally change the color of some of the text. The following code does not work and I need to know why.

oRange = oTable.Cell(r, 4).Range
oRange.SetRange(oRange.Text.IndexOf(vbCr) + 10, oRange.Text.IndexOf(vbCr) + 25)
oRange.Font.ColorIndex = Word.WdColorIndex.wdRed

If I remove the SetRange, I can change the entire cell contents to red, but that is not the desire.

Any help or guidance would be most appreciated.

Tinbendr
06-12-2012, 04:21 AM
Welcome to the board!

IndexOf is not available to VBA.

SetRange is expecting a start and end number, so
SetRange(oRange.Start + 10, oRange.End - 25)

Or move the Start/End
oRange.MoveEnd wdCharacter, -25
oRange.MoveStart wdCharacter, 10

Also remember, when you set a range on a Word table cell, it includes the End-of-Cell marker.

slhussey
06-12-2012, 09:55 AM
Thanks David, I found another posting via Google that gave me a clean answer. The table cell object has a paragraph collection that I could address a single paragraph and accomplish what I needed. BTW, my code is VB.NET, not VBA but I duplicated the functionality in VBA and was still unable to make it work.

Solution was:

oRange = oTable.Cell(r, 4).Range.Paragraphs.Item(4).Range
oRange.Font.ColorIndex = Word.WdColorIndex.wdRed

Frosty
06-12-2012, 11:39 AM
The .Item property is typically the default item for a built-in collection, so you can also use
oRange = oTable.Cell(r,4).Range.Paragraphs(4).Range
without needing to explicitly use the .Item property.

Going forward, even though you're programming in VB.NET, it will probably help you to actually record a macro in Word doing roughly what you want to accomplish in your application... that will give you some insight into the various objects/built-in enumerations you're looking to adapt into .NET. You will, of course, have to further specify with the prefix "Word." in order to gain access to those particular areas of the object model.

Good luck!