2014-09-22 159 views
0

我一直在使用下面的代碼從jonhaus.hubpages.com刪除我有空列。優化/精簡Excel VBA刪除空列

'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,它得到有點臃腫和緩慢......我試圖優化,並通過消除環路,複製/粘貼簡化我的代碼等

你們是否對代碼做了相同的建議(刪除整個靜態列)而不需要循環「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

只是一個想法,而不是在循環內部執行迭代的'.Delete',你可以創建一列要刪除的列,然後將它們全部刪除'.Delete'聲明,在循環之外,其他明顯的改進是在*運行期間禁用'Application.ScreenUpdating'並設置'Application.Calculation = xlManual' *(記得在子例程結束時恢復它們的正常功能。 – 2014-09-22 17:46:58

回答

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。 (記住要在子程序結束時恢復它們的正常功能