vba删除多个工作表中的空白列。工作表计数是一个变量

时间:2017-03-13 21:39:33

标签: excel vba excel-vba

我正在尝试删除多个工作表中的所有空白列,其中这些工作表的计数是可变的。

我已经尝试了以下代码并且它可以工作,但是当它无法找到下一个工作表时它会给我错误。我打算分享这个,并希望没有错误。

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

1 个答案:

答案 0 :(得分:3)

以下内容应该有效:

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