简体   繁体   English

如何从Excel工作表中删除单个文件中的宏?

[英]How can I delete macros from a single file from a Excel sheet?

Scope: 范围:

Me and my team are developing an Excel Report for our costumer, using VBA. 我和我的团队正在使用VBA为我们的客户开发Excel报告。 There are Functions and Macros in this .xlms file that I don't want to make available for the customer. 此.xlms文件中有函数和宏,我不想让客户使用。

We've managed to delete all the macros from the workbook by using this code sample: 我们设法使用此代码示例删除工作簿中的所有宏:

 private void DeleteMacros (string reportPath)
    {
        // WorkBookManager is our own Wrapper for the Excel Workbook class
        WorkbookManager wb = new WorkbookManager (reportPath);
        wb.OpenWorkbook (false);

        //Lock workbook
        wb.RunMacro("ThisWorkbook.LockWorkbook");

        //Deleting the Macros from the workbook
        VBProject project = wb.GetInstance().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);
        }

        wb.CloseAndSave();
        wb.CleanUp();
    }

The Problem: 问题:

There are some macros in this workbook that we will still need, like ones used to navigate from one sheet to another, that we binded to buttons ( to avoid showing the sheet tabs at the botton of the report). 我们仍然需要这个工作簿中的一些宏,比如用于从一个工作表导航到另一个工作表的宏,我们绑定到按钮(以避免在报告的底部显示工作表标签)。

Question: 题:

Is there any way I can encapsulate those not important(/sensitive) macros in a single file on a single workbook and, somehow, delete all the other workbooks and their macros? 有没有什么办法可以将那些不重要(/敏感)的宏封装在单个工作簿的单个文件中,并以某种方式删除所有其他工作簿及其宏?

If not, which is the right way to do so? 如果没有,这是正确的方法吗?

Have you tried checking the properties (such as Name ) of each of component before deleting it? 在删除之前,您是否尝试检查每个组件的属性(如Name )? Just don't remove the ones you want to keep. 只是不要删除你想要保留的那些。

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

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