简体   繁体   English

错误“下标超出范围”

[英]Error “subscript out of range”

I want to auto delete all VBA modules present in personal workbook, I am trying below code but this is showing an error 9 saying "subscript out of range " Please help me to solve this error 我想自动删除个人工作簿中存在的所有VBA模块,我正在尝试下面的代码,但这显示了错误9说“下标超出范围”,请帮助我解决此错误

Sub deletemodule()
    Dim vbCom As Object
    Dim i As Integer
    For i = 2 To 10
        On Error GoTo abc
        Set vbCom = Application.VBE.ActiveVBProject.VBComponents
        vbCom.Remove vbComponent:=vbCom.Item("Module" & i)
    Next
abc:
End Sub

Thanks in advance 提前致谢

Try to revert loop: 尝试还原循环:

For i = 10 To 2 step -1
On Error GoTo abc
Set vbCom = Application.VBE.ActiveVBProject.VBComponents
vbCom.Remove vbComponent:=vbCom.Item("Module" & i)
Next

This code removes all Standard & Class modules from the workbook. 此代码从工作簿中删除所有“标准和类”模块。
Note sure what other types there will be - Chart sheets, forms, macro sheets(?) 请注意,还有其他类型-图表,表格,宏表格(?)

Modules are a collection so you can step through them using a For...Each loop rather than needing to know how many or what they're called beforehand. 模块是一个集合,因此您可以使用For...Each循环逐步执行它们,而无需事先知道它们的数量或名称。

Public Sub DeleteAllModules()

    Dim vbcom As Object
    Dim vMod As Object

    Set vbcom = Application.VBE.ActiveVBProject.VBComponents

    For Each vMod In vbcom
        Select Case vMod.Type
            Case 1, 2 'Standard & Class modules
                vbcom.Remove vMod
            Case 100 'Sheet & ThisWorkbook modules
                'Do nothing
        End Select
    Next vMod

End Sub

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

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