views:

120

answers:

2

Does anyone know how to delete all VB code form an Excel workbook using C#? This code doesn’t work. It removes first (last one) VBComponent, but rises ArgumentException on second one.

        VBProject project = workbook.VBProject;
        int componentsCount = project.VBComponents.Count;

        for (int i = componentsCount; i >= 1; i--)
        {
            VBComponent component = project.VBComponents.Item(i);
            project.VBComponents.Remove(component);
        } 

Any suggestions? :)

+1  A: 

have you tried deleting the first one n times:

    VBProject project = workbook.VBProject;
    int componentsCount = project.VBComponents.Count;

    for (int i = 1; i <= componentsCount; i++)
    {
        VBComponent component = project.VBComponents.Item(1);
        project.VBComponents.Remove(component);
    }

you might need to tweak this, but i think the VBA collections are 1 based (might need to make the project.VBComponents.Item(0) instead

EDIT:

I found this post which explains how to do it in VBA, but presumably its not too difficult to translate...

Sam Holder
Yes, I've tried. Yes VB uses 1-based collections, so your code is working fine if not calling Remove. But I still getting ArgumentExcecption. I.e. I can delete 4-th element in the collection, but not others. I suspect that first 3 VBComponents are embeded (like first three workseets in a workbook) and cannot be removed... maybe I should clear their content instead of removing. Let me try :)
Bashir Magomedov
what does the code file look like? does it have 4 'things' in it or just one? What does it look like after you have removed everything you can, is it empty? (perhaps in a `try catch` block so you can ignore errors while you experiment)
Sam Holder
edited my answer to add some information found on another site which might be useful... They seem to use `On Error Resume Next` so i suspect some elements are non deletable
Sam Holder
Thank you Sam, you gave me an idea! And it works now (see my answer). Thanks again!
Bashir Magomedov
+1  A: 

I solved it with Sam's help. I suspect that each Excel workbook has some non-deletable VBComponents, hence instead of deleting them we can clear their content. It works now. Thank you Sam.

            VBProject project = workbook.VBProject;

        for (int i = project.VBComponents.Count; i >= 1; i--)
        {
            VBComponent component = project.VBComponents.Item(i);
            try
            {
                project.VBComponents.Remove(component);
            }
            catch(ArgumentException)
            {
                continue;
            }
        }

        for (int i = project.VBComponents.Count; i >= 1; i--)
        {
            VBComponent component = project.VBComponents.Item(i);
                component.CodeModule.DeleteLines(1, component.CodeModule.CountOfLines);
        }

Do not forget to save your workbook afterwards :)

Bashir Magomedov