我一直在使用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,它变得有点臃肿和缓慢......我试图通过消除循环,复制/粘贴等来优化和简化我的代码
是否所有人都对代码做了相同的建议(删除整个emtpy列)而不需要循环" Do Until / If / End If / Loop"语句?
参考文献: http://jonhaus.hubpages.com/hub/Excel-VBA-Delete-Blank-Blank-Columns http://www.ozgrid.com/VBA/SpeedingUpVBACode.htm
答案 0 :(得分:1)
扩展我上面的评论,在循环内创建范围,但只删除一次。
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
。 (记得在子程序结束时恢复它们的正常功能。