Delphi: 以编程方式将 Word ContentControl 设置为临时

Delphi: Set Word ContentControl to temporary programattically

我正在使用 Delphi 10.4

将 ContentControl 插入到 MS Word 文档中

使用以下代码段将内容控件插入到模板的书签中:

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;

这成功创建了 ContentControl,但是一旦文本被编辑,该控件就会保持不变。

Word 有一个选项可以将 ContentControls 标记为“临时”,VBA 是

Selection.ParentContentControl.Temporary = True

Delphi 与 R.ParentContentControl.Temporary 公开相同,后者需要 WordBool 值。

尽我所能,我无法让 Delphi 接受 True 值并将其传递给 Word。

问题是您试图将 Delphi 布尔值分配给 WordBool。

Delphi 布尔值是 8 位(1 字节大小)。但 WordBool 实际上是 16 位的(2 字节大小)。

有关此检查的更多信息System.WordBool

解决方案是我试图访问 .ContentControl.Temporary 的错误实例,我还设置了 Range.Text 值。

以下是上述示例的工作版本。

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;