Empty/Blank Modules in Excel

Vishesh's picture
While working on Excel VBA project at times you leave a blank or empty module. However, this can be removed using the following code. Copy it in any general module and run.
Public Sub RemoveEmptyModules()
    'This CANNOT remove Sheet modules
    'Can remove Standard modules and Class modules only
    'For this to you should have the option "Trust access to the VBA project object model"
    'checked. This is under macro security.
    
    Dim objVbComponent      As Object
    Dim lngStartLine        As Long
    Dim lngLineCount        As Long
    Dim lngCntRemove        As Long
 
    Const ct_pp_none        As Long = 1
    Const ct_StdModule      As Long = 1
    Const ct_ClsModule      As Long = 2
 
    For Each objVbComponent In ActiveWorkbook.VBProject.VBComponents
        Select Case objVbComponent.Type
        Case ct_StdModule, ct_ClsModule
            lngStartLine = objVbComponent.CodeModule.CountOfDeclarationLines + 1
            lngLineCount = objVbComponent.CodeModule.CountOfLines
            If lngLineCount < lngStartLine Then
                ActiveWorkbook.VBProject.VBComponents.Remove objVbComponent
                lngCntRemove = lngCntRemove + 1
            End If
        End Select
    Next objVbComponent
    If lngCntRemove = 0 Then
        MsgBox "No empty modules present.", vbInformation, "Excel Experts Tip"
    Else
        MsgBox lngCntRemove & " empty module(s) removed.", vbInformation, "Excel Experts Tip"
    End If
 
    Set objVbComponent = Nothing
End Sub

Fantastic!!

Fantastic!!