Question

Sorry if this is so simple of a question, but for the life of me I can't figure out how to do something.

I have a cell in a table in Word that I want to programmatically enter text in. Inside of that text I need a Content Control. So the text will look like this:

mytable.Cell(1,).Range.Text = What <color> is **this**? 

Where <color> equals the content control and "this" is bold. Obviously the .Text property doesn't work here, but I can't figure out how to insert this string with a content control and formatting on the word "this".

Any advice?

Was it helpful?

Solution

I usually use a step-by-step approach...

Dim cc As Word.ContentControl
Dim rng As Word.Range
Set rng = ActiveDocument.Tables(1).Cell(2, 3).Range
' Exclude the end of cell marker
rng.SetRange rng.Start, rng.End - 1
rng.Text = "What "
rng.Collapse direction:=Word.WdCollapseDirection.wdCollapseEnd
Set cc = rng.ContentControls.Add(wdContentControlText, rng)
With cc
  ' set what you need
  ' the following are just names.
  .Tag = "color"
  .Title = "color"
End With
' Word does not extend the range to include the CC
' We want to step beyond it
rng.SetRange cc.Range.End + 1, cc.Range.End + 1
Set cc = Nothing
rng.InsertAfter "is "
rng.Collapse direction:=WdCollapseDirection.wdCollapseEnd
rng.InsertAfter "this"
rng.Font.Bold = True
rng.Collapse direction:=WdCollapseDirection.wdCollapseEnd
rng.InsertAfter "?"
rng.Font.Bold = False
Set rng = Nothing

As for the content control, it depends on what you mean. If you just need to insert a control with the Title or Tag "color", the above would be enough. But if you have controls connected to a custom XML data store, then you would need to use .XmlMapping.SetMapping to set its Xpath to point to the correct item in the store.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top