Moh Tarvirdi
Moh Tarvirdi

Reputation: 705

How to call a Word macro with parameters

I want to run a macro (Sub) of a Word document from Delphi.

My macro in Word is

Sub Macro1()  
  'Do Something
End Sub  

and in Delphi

Word := CreateOleObject('Word.Application');  
Word.visible := true;  
Word.Documents.Open('c:\_3\Doc\2.docm', true, false);  
word.Run('Macro1');  

and works well
But when I want to enhance the macro and add parameters as

Sub Macro1( param1 as string, param2 as string)  
 'Do Something  
End Sub  

and calling as

word.Run('Macro1 "Book", "Pool"');  

I get error as
"Unable to run the specified macro"
How can I call a macro (Sub) with parameters?

Upvotes: 3

Views: 5344

Answers (2)

user2136695
user2136695

Reputation: 11

macro code :

Sub TestParams(param1 As String)
   MsgBox "Param1 := enter code here" & param1
End Sub

It was a nightmare for me too becuase as soon as you create the macro with parameters it does not display in list of macros.

I eventually got it working by doing the following
delphi code :

procedure TUtils.RunMacro;
var Test : olevariant;
begin
  Test := 'Hello Word';
  WordApplication.Run('TestParams',Test);
end;

Upvotes: 1

RRUZ
RRUZ

Reputation: 136391

You must pass the macro parameters values just as normal parameters.

word.Run('Macro1', 'Book', 'Pool');  

for more info read the Application.Run Method MSDN documentation.

Upvotes: 3

Related Questions