简体   繁体   English

使用 Office 自动化从 Delphi 打开文档时,为什么 Document_Open 宏不在 Word 中运行

[英]Why does the Document_Open Macro not run in Word when opening the document from Delphi using Office Automation

I am trying to use Office Automation in Delphi Tokyo to open a Word document (using Word 2016).我正在尝试在 Delphi Tokyo 中使用 Office Automation 打开 Word 文档(使用 Word 2016)。 The document has a Document_Open macro that prompts the user to optionally run another macro.该文档有一个 Document_Open 宏,它提示用户有选择地运行另一个宏。

When I run the following code:-当我运行以下代码时: -

Doc := IDispatch(WordApp.Documents.Open([*filename*])) as _Document;

the document opens, but the Document_Open macro does not run.文档打开,但 Document_Open 宏不运行。 Also, if I try to run the second (main) macro manually, I get an error saying "The macros in this project are disabled ..."此外,如果我尝试手动运行第二个(主)宏,我会收到一条错误消息“此项目中的宏已禁用......”

However, if I open the same document from the Word file menu, the macros run as expected, so they are clearly not disabled.但是,如果我从 Word 文件菜单打开同一个文档,宏会按预期运行,因此它们显然没有被禁用。

The VBA project is digitally signed and Word is set to "Disable all macros except digitally signed macros". VBA 项目经过数字签名,Word 设置为“禁用除数字签名宏之外的所有宏”。

How do I get my macros to run when opening the document from within Delphi?从 Delphi 中打开文档时,如何让我的宏运行?

BrakNicku led me to the answer. BrakNicku 引导我找到答案。

I have found that unless you set WordApp.AutomationSecurity to msoAutomationSecurityByUI, macros are disabled irrespective of the settings in Word.我发现除非您将 WordApp.AutomationSecurity 设置为 msoAutomationSecurityByUI,否则无论 Word 中的设置如何,宏都会被禁用。

So the answer to my question is:-所以我的问题的答案是:-

WordApp := GetActiveOleObject('Word.Application');

//store AutomationSecurity setting
LogonAutomationSecurity := WordApp.AutomationSecurity;

try
  //set AutomationSecurity
  WordApp.AutomationSecurity := msoAutomationSecurityByUI;
  Doc := IDispatch(WordApp.Documents.Open([*filename*])) as _Document;
  ...

finally
  WordApp.AutomationSecurity := LogonAutomationSecurity;
end;

Then, provided the user's Trust Settings allow the macro to run, it will!然后,只要用户的信任设置允许宏运行,它就会!

I hope this helps someone.我希望这可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM