title: Unable to add a table in the header of a batch of word documents using VBA
body: <p>I am attempting to write a macro that opens up .docx files within a specific folder, deletes the contents of the header, then inserts a table into the header and finally - saves and closes the document so it can move onto the next one in sequence. Everything is working fine - except for the line where it attempts to create the table. My code is below:</p>
  <pre><code>Sub BatchAddTableToHeaders()
  
      Dim wrd As Word.Application
      
      Set wrd = CreateObject(&quot;word.application&quot;)
      wrd.Visible = True
      FName = Dir(&quot;C:\MyFolder\*.docx&quot;)
      
      Do While (FName &lt;&gt; &quot;&quot;)
          With wrd
              ' Open the next document in the folder
              .Documents.Open (&quot;C:\MyFolder\&quot; &amp; FName)
              
              ' select the header, delete it and then insert a table
              .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader
              With .Selection
                  .WholeStory
                  .Delete
                  .Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
              End With
              
              .ActiveDocument.Save
              .ActiveDocument.Close
              
          End With
          FName = Dir
      Loop
      Set wrd = Nothing
  End Sub
  </code></pre>
  <p>The error that I receive is as follows:</p>
  <p><strong>Run-time error '-2147023170 (800706be)':</strong></p>
  <p><strong>Automation error</strong></p>
  <p><strong>The remote procedure call failed.</strong></p>
  <p>The strange thing is that it will happily insert a table into the header as long as I am not trying to open and run through a batch of documents. The following macro works perfectly fine:</p>
  <pre><code>Sub InsertTableIntoCurrentDocumentHeader()
      ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader
      With Selection
          .WholeStory
          .Delete
          .Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
      End With
  End Sub
  </code></pre>
  <p>Is anyone able to provide some insight into why my 'batch header' macro is failing?</p>