简体   繁体   English

如何使用 C# 从 Excel 工作表中删除 VB 代码?

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

Does anyone know how to delete all VB code form an Excel workbook using C#?有谁知道如何使用 C# 从 Excel 工作簿中删除所有VB 代码? This code doesn't work.此代码不起作用。 It removes first (last one) VBComponent, but rises ArgumentException on second one.它删除了第一个(最后一个)VBComponent,但在第二个上引发了 ArgumentException。

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?有什么建议?

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.我怀疑每个 Excel 工作簿都有一些不可删除的 VBComponents,因此我们可以清除它们的内容而不是删除它们。 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之后不要忘记保存您的工作簿

have you tried deleting the first one n times:您是否尝试过删除第一个 n 次:

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.您可能需要对此进行调整,但我认为 VBA 集合是基于 1 的(可能需要改为创建project.VBComponents.Item(0)

EDIT:编辑:

I found this post which explains how to do it in VBA, but presumably its not too difficult to translate...我发现这篇文章解释了如何在 VBA 中做到这一点,但大概它不太难翻译......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM