Insert and run macro into word using interop in c#

3.8k Views Asked by At

How can I insert and run a macro into a word document using Interop in c#?

1

There are 1 best solutions below

0
On
using System.Runtime.InteropServices;
using Microsoft.Vbe.Interop;
using Word = Microsoft.Office.Interop.Word.Application;

string file1, file2;

var word = new Word { Visible = true };
var doc = word.Documents.Open(file1);

var project = doc.VBProject;
var module = project.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);

var script = string.Format(
@"Sub MacroTest()
Const path1 As String = ""{0}""
Set doc1 = Documents.Open(path1)
End Sub", file2);

module.CodeModule.AddFromString(script);

word.Run("MacroTest");