How to delete VB code from an Excel sheet using C#?

心不动则不痛 提交于 2019-12-24 02:00:58

问题


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:


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 :)




回答2:


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...



来源:https://stackoverflow.com/questions/2948878/how-to-delete-vb-code-from-an-excel-sheet-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!