不可能删除所有类型的模块,不能删除工作表,图表和ThisWorkbook的代码模块。在这些模块中,您必须删除内容而不是模块本身:

Sub DeleteModuleContent(ByVal wb As Workbook, _

ByVal DeleteModuleName As String)

' deletes the contents of DeleteModuleName in wb

' use this if you can't delete the module

On Error Resume Next

With wb.VBProject.VBComponents(DeleteModuleName).CodeModule

.DeleteLines 1, .CountOfLines

End With

On Error GoTo 0

End Sub

例如:

DeleteModuleContent ActiveWorkbook, "Sheet1"