Search code examples
delphims-worddelphi-10.4-sydney

Delphi: Set Word ContentControl to temporary programattically


I am inserting a ContentControl into a MS Word document using Delphi 10.4

The content control is inserted, into a bookmark on the template, using the following snippet:

procedure TBF.SetPI;
var
  R: WordRange;
  bookmark: OleVariant;
  s: string;
begin
  s:= 'insert text here';
  bookmark := 'textValue';
  R := MF.WordDoc.Bookmarks.Item(bookmark).Range;
  R.Text := s;
  R.HighlightColorIndex := wdYellow;
  MF.WordDoc.ContentControls.Add(wdContentControlRichText,R);
end;

This successfully creates the ContentControl, however the control is persistant oonce the text has been edited.

Word has an option to mark ContentControls as "temporary" and the VBA for that is

Selection.ParentContentControl.Temporary = True

Delphi exposes the same as R.ParentContentControl.Temporary which requires a WordBool value.

Try as I might I cannot get Delphi to accept a True value and pass it to Word.


Solution

  • The solution was that I was trying to access the wrong instance of .ContentControl.Temporary which was compounded by my also setting the Range.Text value.

    The following is a working version of the above example.

    procedure TBF.SetPI;
    var
      R: WordRange;
      bookmark: OleVariant;
      s: string;
      cc: ContentControl;
    begin
      s := 'insert text here';
      bookmark := 'textValue';
      R := MF.WordDoc.Bookmarks.Item(bookmark).Range;
      R.Text := '';
      cc := MF.WordDoc.ContentControls.Add(wdContentControlRichText, R);
      cc.SetPlaceholderText(nil, nil, s);
      cc.Range.HighlightColorIndex := wdYellow;
      cc.Temporary := true;
    end;