0

I am trying to use Office Automation in Delphi Tokyo to open a Word document (using Word 2016). The document has a Document_Open macro that prompts the user to optionally run another macro.

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. 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.

The VBA project is digitally signed and Word is set to "Disable all macros except digitally signed macros".

How do I get my macros to run when opening the document from within Delphi?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Andrew
  • 59
  • 5
  • Can you create/open the Word application object, enable macros/events, then call application.documents.open(...) ? – Joseph Willcoxson May 23 '22 at 13:59
  • I am not sure what you mean. Is there a way to enable macros/events from within VBA? I don't see how it would help, since the macros run correctly when I open the file from within Word, but I am willing to give anything a go! – Andrew May 23 '22 at 14:56
  • What is the value of `WordApp.AutomationSecurity` before you open the file? – BrakNicku May 24 '22 at 05:10
  • msoAutomationSecurityLow. I tried changing it to msoAutomationSecurityForceDisable, but it didn't make any difference – Andrew May 24 '22 at 10:38

1 Answers1

2

BrakNicku led me to the answer.

I have found that unless you set WordApp.AutomationSecurity to msoAutomationSecurityByUI, macros are disabled irrespective of the settings in 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.

Andrew
  • 59
  • 5