简体   繁体   中英

VBA Delete Excel column and header if all cells in column (except header) are empty?

I have some vba code that populates an excel table with specific texts. I'm hoping to add a function to the code that deletes a column (and the header) if that column is empty (no text strings present). I have searched for some codes but none have been able to work. Any suggestions?

Below simple function will check, if given column is empty. Optional argument let you set, if empty column should include headers.

Function IsColumnEmpty(ByVal rngColumn As Range, Optional bIncludeHeaders As Boolean = True) As Boolean
    IsColumnEmpty = False
    If bIncludeHeaders = True Then
        If WorksheetFunction.CountA(rngColumn) = 1 Then
            IsColumnEmpty = True
        End If
    Else
        If WorksheetFunction.CountA(rngColumn) = 0 Then
            IsColumnEmpty = True
        End If
    End If
End Function

To delete an empty column you can use it as below:

If IsColumnEmpty(Sheets(1).Column(1)) = true then
    Sheets(1).Column(1).Delete
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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