Taedrin
Taedrin

Reputation: 535

"Rich text controls cannot be applied here" when trying to add multiple nested content controls

I have a VSTO word add-in which is supposed to let the user add potentially nested content controls at/around the current selection. I am having difficulty getting content controls to be added, even under circumstances when I think they should be able to be added.

The following VBA code replicates one of the issues on a blank document:

Public Sub DoTest()
    AddControls "Test"
    AddControls "Test2"
    Application.Selection.MoveRight WdUnits.wdCharacter
    Application.Selection.MoveRight WdUnits.wdCharacter
    Application.Selection.TypeText " "
    AddControls "Test3"
    AddControls "Test4" 'ERROR: "Rich text controls cannot be applied here"
End Sub

Public Sub AddControls(ByVal name As String)
    Dim richTextControl1 As ContentControl
    Set richTextControl1 = Application.ActiveDocument.ContentControls.Add(wdContentControlRichText)

    richTextControl1.Tag = name
    richTextControl1.Title = name
    richTextControl1.SetPlaceholderText , , " "

    Application.Selection.SetRange richTextControl1.Range.Start, richTextControl1.Range.End
End Sub

At the point that the test errors out, the selection range starts at 6 and ends at 7 (which is the same range for the "Test3" rich text content control). What am I doing incorrectly here?

I understand that the Test and Test2 controls are surrounding the paragraph when they are created (denoted by the content controls being white), and that the Application.Selection.TypeText " " instruction outside of the content controls causes Test and Test2 to be pulled inside of the paragraph (denoted by the content controls turning grey). When Test3 is created it is also inside of the paragraph. This can be verified by saving the document as XML and reading through the file in your favorite text editor.

I can work around the issue by typing a space inside of the parent content control before adding a child content control, and then deleting the space after. However, this forces the child content control to always be inside of a paragraph (as a "grey" control). This is not acceptable, as the user needs to be able to insert tables inside of the content controls (which is not possible if the content control is inside of a paragraph, since paragraphs cannot contain tables)

Upvotes: 0

Views: 2586

Answers (1)

Taedrin
Taedrin

Reputation: 535

I figured out what the issue is. Apparently, Word has difficulty with whitespace as placeholder text. Any combination of tabs and spaces will result in an error when trying to insert the Test4 content control.

A workaround is to use a non-breaking space (Chr(160)) instead of a normal space as the placeholder text. Word seems to treat it as a normal character.

Upvotes: 1

Related Questions