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

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

我已经尝试了下面的代码,它的工作原理,但是当它找不到下一张表时,它给了我错误。 我打算分享这个,并希望是没有错误的。

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 

以下应该工作:

 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