简体   繁体   中英

vba to delete blank columns in multiple worksheets.worksheet count is a variable

I am trying to delete all blank columns in multiple worksheets where the count of those worksheets are variable.

I have tried the following code and it works, however it gives me the error when it cannot locate the next sheet. I intend to share this and would like to be error free.

Sub delete_columns()
i = ThisWorkbook.Worksheets.count
a = 1
Do Until a = i
Dim MyRange As Range
Dim iCounter As Long
Set MyRange = ActiveSheet.UsedRange
For iCounter = MyRange.Columns.count To 1 Step -1
If Application.CountA(Columns(iCounter).EntireColumn) = 0 Then
Columns(iCounter).Delete 
End If
Next iCounter
i = i + 1
ActiveSheet.Next.Select
Loop
End Sub

The following should work:

Sub delete_columns()
    Dim ws As Worksheet
    Dim MyRange As Range
    Dim iCounter As Long
    'Loop through each worksheet - no need to Activate or Select each one
    For Each ws In ThisWorkbook.Worksheets
        Set MyRange = ws.UsedRange
        For iCounter = MyRange.Columns.count To 1 Step -1
            'Need to reference columns of MyRange, rather than columns of the
            'worksheet, because column 5 of MyRange might be column 7 of the
            'worksheet (if the first used cell was in column C)
            If Application.CountA(MyRange.Columns(iCounter).EntireColumn) = 0 Then
                MyRange.Columns(iCounter).Delete 
            End If
        Next iCounter
        'Or, if you want to delete empty columns which exist to the left
        'of the UsedRange, you could do the following
        'For iCounter = MyRange.Columns(MyRange.Columns.count).Column To 1 Step -1
        '    If Application.CountA(ws.Columns(iCounter).EntireColumn) = 0 Then
        '        ws.Columns(iCounter).Delete 
        '    End If
        'Next iCounter
    Next
End Sub

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