title: Programmatically extract macro (VBA) code from Word 2007 docs
body: <p>Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?</p>
  
  <p>I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).</p>
  
  <p>Any tips or resources would be appreciated.</p>
  
  <p><strong>Edit</strong>: thanks to everyone, <a href="https://stackoverflow.com/users/3655/aardvark">Aardvark</a>'s answer was exactly what I was looking for.  I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.</p>
  
  <pre><code>using Microsoft.Office.Interop.Word;
  using Microsoft.Vbe.Interop;
  
  ...
  
  public List&lt;string&gt; GetMacrosFromDoc()
  {
      Document doc = GetWordDoc(@"C:\Temp\test.docm");
  
      List&lt;string&gt; macros = new List&lt;string&gt;();
  
      VBProject prj;
      CodeModule code;
      string composedFile;
  
      prj = doc.VBProject;
      foreach (VBComponent comp in prj.VBComponents)
      {
          code = comp.CodeModule;
  
          // Put the name of the code module at the top
          composedFile = comp.Name + Environment.NewLine;
  
          // Loop through the (1-indexed) lines
          for (int i = 0; i &lt; code.CountOfLines; i++)
          {
              composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
          }
  
          // Add the macro to the list
          macros.Add(composedFile);
      }
  
      CloseDoc(doc);
  
      return macros;
  }
  </code></pre>