vba 从excel文件中删除所有VBA模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18518493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:31:52  来源:igfitidea点击:

Remove all VBA modules from excel file?

excel-vbavbaexcel

提问by user1283776

Is it possible to remove all VBA modules from an Excel file using VBA?

是否可以使用 VBA 从 Excel 文件中删除所有 VBA 模块?

The names of the modules if they exist at all are unknowns before running this script.

在运行此脚本之前,模块的名称(如果它们存在)是未知的。

回答by Kazimierz Jawor

Obviously, you can. The following code will do the job:

显然,你可以。以下代码将完成这项工作:

Sub compact_code()

On Error Resume Next
    Dim Element As Object
    For Each Element In ActiveWorkbook.VBProject.VBComponents
        ActiveWorkbook.VBProject.VBComponents.Remove Element
    Next

End Sub

This will remove all modules including ClassModules and UserForms but keep all object modules (sheets, workbook).

这将删除所有模块,包括 ClassModules 和 UserForms,但保留所有对象模块(工作表、工作簿)。

回答by user1283776

Here is a similar alternative that removes only the ClassModules:

这是一个类似的替代方案,它只删除了 ClassModules:

On Error Resume Next
With wbk.VBProject
    For x = .VBComponents.Count To 1 Step -1
        If .VBComponents(x).Type = vbext_ct_StdModule Then
            .VBComponents.Remove .VBComponents(x)
        End If
    Next x
End With
On Error GoTo 0