title: VbComponents.Remove doesn't always remove module
body: <p>I'm trying to use Chip Pearson's code for overwriting an existing VBA code module with an import from another project.  Original code <a href="http://www.cpearson.com/excel/vbe.aspx" rel="noreferrer">here</a>.</p>
  
  <p>The particular section I'm looking at is:</p>
  
  <pre><code>With ToVBProject.VBComponents
      .Remove .Item(ModuleName)
  End With
  </code></pre>
  
  <p>But this <code>VBComponents.Remove</code> call will sometimes only actually take effect once VBA execution has stopped--that is, the delete operation doesn't take effect until all statements are finished, or if the code hits a breakpoint and then I stop debugging.  This is a problem because of the following code for either importing a new module or replacing the existing module's code with the new module:</p>
  
  <pre><code>    Set VBComp = Nothing
      Set VBComp = ToVBProject.VBComponents(CompName)
  
      If VBComp Is Nothing Then
          ToVBProject.VBComponents.import filename:=FName
      Else
          If VBComp.Type = vbext_ct_Document Then
              'delete the module's code,
              'import a temp module,
              'copy over the temp module code,
              'delete the temp module
          End If
      End If
  </code></pre>
  
  <p>The module deletion hasn't taken effect yet, so <code>VBComp</code> is not <code>Nothing</code>, as far as the debugger knows.  So the <code>.import</code> won't be called.</p>
  
  <p>Even if I comment out the <code>if VBComp.Type = vbext_ct_document then</code> and <code>end if</code> so that the new module's code will overwrite the existing one no matter what <code>VBComp.Type</code> it is, the module will still end up getting deleted once the code finishes executing, and no import will happen to replace it. </p>
  
  <p>What's odd is that this doesn't happen with all modules; some actually get deleted in real time after the <code>VBComponents.Remove</code> call.</p>
  
  <p>I've seen several different posts about this on various forums, and no satisfactory solution.  For now I'm using a workaround of changing the <code>.Remove</code> call to:</p>
  
  <pre><code>    With ToVBProject.VBComponents
          .Item(ModuleName).name = ModuleName &amp; "_remove"
          .Remove .Item(ModuleName &amp; "_remove")
      End With
  </code></pre>
  
  <p>so that by changing the name, <code>ModuleName</code> appears to no longer exist and therefore the <code>.import</code> call will occur.  This assumes, of course, that no module named <code>ModuleName &amp; "_remove"</code> actually exists.</p>
  
  <p>Is there a better solution?</p>