需要 Add/Set Read/Get Word/Excel 文档中的 CustomDocumentProperties delphi

Need To Add/Set Read/Get CustomDocumentProperties in Word/Excel Document in delphi

我编写了一些小代码来更新 CustomDocumentProperties。

但保存文件后退出。道具没有保存为文档的一部分? 可能吗? 如果是这样?正确的做法是什么?

感谢提前。

Var
  Doc : OleVariant;
  DocProps : OleVariant;
  Item : OleVariant;
  i : integer;
  Value : string;
  SaveChanges: OleVariant;
begin
  Memo1.Lines.Clear;
  WordApplication1.Connect;
  WordApplication1.Visible := false;

  WordApplication1.Documents.Open(Edit1.Text, EmptyParam, EmptyParam, EmptyParam,
                          EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                              EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                              EmptyParam, EmptyParam, EmptyParam, EmptyParam);


  Doc := WordApplication1.ActiveDocument;

  DocProps := Doc.CustomDocumentProperties;

  DocProps.Add(
               'MyOpinionOfThisDocument2',
               False, msoPropertyTypeString,
               'Utter drivel', EmptyParam);
  DocProps.Add(
               'Mz_Ident2',
               False, msoPropertyTypeString,
               '1997', EmptyParam);

  for I := 1 to DocProps.Count do // Iterate
  begin
    Item := DocProps.Item[i];
    Memo1.Lines.Add(Item.name + ' = ' + item.value);
  end; 

  SaveChanges := wdSaveChanges;
  WordApplication1.Quit(SaveChanges, EmptyParam, EmptyParam);
  WordApplication1.Disconnect;

end;

显然,如果您在代码中设置自定义文档属性,您需要告诉 Word 文档尚未保存,否则在询问时将无法保存 - 参见 http://www.vbaexpress.com/forum/showthread.php?16678-Custom-Document-Properties-Don-t-Always-Save。所以 我建议您将代码的中心部分更改为:

  DocProps := Doc.CustomDocumentProperties;

  if DocProps.Count = 0 then begin
    DocProps.Add(
                'MyOpinionOfThisDocument2',
                 False, msoPropertyTypeString,
                 'Utter drivel', EmptyParam);
    DocProps.Add(
                 'Mz_Ident2',
                 False, msoPropertyTypeString,
                 '1997', EmptyParam);
  end;
  Doc.Saved := False;

  for I := 1 to DocProps.Count do // Iterate
  [...]

通过此更改,我在 D7 + Word2010 中工作正常。像我建议的那样调用 Doc.Save,但没有。