Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VbComponents.Remove doesn't always remove module

Tags:

excel

vba

I'm trying to use Chip Pearson's code for overwriting an existing VBA code module with an import from another project. Original code here.

The particular section I'm looking at is:

With ToVBProject.VBComponents
    .Remove .Item(ModuleName)
End With

But this VBComponents.Remove 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:

    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

The module deletion hasn't taken effect yet, so VBComp is not Nothing, as far as the debugger knows. So the .import won't be called.

Even if I comment out the if VBComp.Type = vbext_ct_document then and end if so that the new module's code will overwrite the existing one no matter what VBComp.Type it is, the module will still end up getting deleted once the code finishes executing, and no import will happen to replace it.

What's odd is that this doesn't happen with all modules; some actually get deleted in real time after the VBComponents.Remove call.

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 .Remove call to:

    With ToVBProject.VBComponents
        .Item(ModuleName).name = ModuleName & "_remove"
        .Remove .Item(ModuleName & "_remove")
    End With

so that by changing the name, ModuleName appears to no longer exist and therefore the .import call will occur. This assumes, of course, that no module named ModuleName & "_remove" actually exists.

Is there a better solution?

like image 620
sigil Avatar asked Nov 05 '13 22:11

sigil


1 Answers

I have ran into things like this before. The 'DoEvents' command often helps. Have you given that a shot?

Other times, I have placed the command in a do while loop and used a boolean to continually check if the command in question has succeeded. Including the DoEvents command in the loop is sometimes needed.

Just remember to put something in the loop so that after so many cycles it will give up. Getting stuck in an infinite loop can be pesky.

like image 196
Steve B Avatar answered Oct 27 '22 05:10

Steve B