优化/精简Excel VBA以删除空列

我一直在使用下面的代码从jonhaus.hubpages.com删除我有空的列。

'Delete empty columns Dim c As Integer c = ActiveSheet.Cells.SpecialCells(xlLastCell).Column Do Until c = 0 If WorksheetFunction.CountA(Columns(c)) = 0 Then Columns(c).Delete End If c = c - 1 Loop 

然而,正如我一直在写VBA,它变得有点臃肿和缓慢…我试图通过消除循环,复制/粘贴等优化和简化我的代码。

你们是否对代码做了相同的build议(删除整个静态列)而不需要循环“Do Until / If / End If / Loop”语句?

参考资料: http : //jonhaus.hubpages.com/hub/Excel-VBA-Delete-Blank-Blank-Columns http://www.ozgrid.com/VBA/SpeedingUpVBACode.htm

展开上面我的评论,在循环内创build范围,但只删除一次。

 Dim c As Integer Dim rngDelete As Range c = ActiveSheet.Cells.SpecialCells(xlLastCell).Column Do Until c = 0 If WorksheetFunction.CountA(Columns(c)) = 0 Then 'Combine each empty column: If Not rngDelete Is Nothing Then Set rngDelete = Application.Union(rngDelete, Columns(c)) Else Set rngDelete = Columns(c) End If End If c = c - 1 Loop 'Deletes ALL empty columns at once: rngDelete.EntireColumn.Delete 

其他明显的改进是在运行时禁用Application.ScreenUpdating并设置Application.Calculation = xlManual 。 (记得在子程序结束时恢复它们的正常function。