2015-08-17 76 views
0

嗨,我有這個代碼運行成功,但只有一段時間後。有時它甚至會停止響應,然後再次正常運行。需要幫助它更快地運行而不會崩潰。這裏是代碼代碼運行時間太長,最終崩潰時間

Sub DeleteCells() 

    Dim R As Range 
    'Set rng = Nothing 
    On Error Resume Next 
    Set R = Application.InputBox("Select cells To be deleted", Type:=8) 
    Dim rng As Range 
    Dim rngError As Range 
    Set rng = Sheets("Sheet3").Range("A1:G100") 
    Set rngError = rng.Cells.SpecialCells(xlCellTypeFormulas, xlErrors) 

    If TypeName(R) <> "Range" Then 
     Exit Sub 
    Else 
    R.delete 
    End If 



For Each cell In rng 
If cell.Text = "#REF!" Then 
    cell.EntireColumn.delete 
End If 
    'delete means cells will move up after deleting that entire row 
    'rngError.EntireRow.ClearContents means that the contents will clear, leaving a blank cell for that entire row 
Next 




End Sub 
+0

注意,「停止響應,並再次正常運行」是_not_一樣崩潰。請說明你的程序是否崩潰,或者只是凍結。 – paddy

+0

好了!有什麼方法可以防止它發生? @paddy – Niva

+0

也許您在刪除單元格時發生級聯更新。如果有一種方法可以暫時禁用配方/參考更新,我會把我的錢放在那裏。 – paddy

回答

1

您正在刪除一個循環中的單元格,使其變得非常慢。這是你正在嘗試的嗎?這應該是非常快的...(未測試

Sub DeleteCells() 
    Dim rng As Range, rngError As Range, delRange As Range 
    Dim i As Long, j As Long 

    On Error Resume Next 
    Set rng = Application.InputBox("Select cells To be deleted", Type:=8) 
    On Error GoTo 0 

    If rng Is Nothing Then Exit Sub Else rng.Delete 

    With Sheets("Sheet3") 
     For i = 1 To 7 '<~~ Loop trough columns A to G 
      '~~> Check if that column has any errors 
      On Error Resume Next 
      Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors) 
      On Error GoTo 0 

      If Not rngError Is Nothing Then 
       For j = 1 To 100 '<~~ Loop Through rows 1 to 100 
        If .Cells(j, i).Text = "#REF!" Then 
         '~~> Store The range to be deleted 
         If delRange Is Nothing Then 
          Set delRange = .Columns(i) 
          Exit For 
         Else 
          Set delRange = Union(delRange, .Columns(i)) 
         End If 
        End If 
       Next 
      End If 
     Next 
    End With 

    '~~> Delete the range in one go 
    If Not delRange Is Nothing Then delRange.Delete 
End Sub 
+0

它的工作原理但如果我想將列更改爲單元格?並且通過刪除在另一張紙上而不是在同一張紙上的參考數據使其變得靈活? @Siddharth Rout – Niva

+0

我使用列而不是單元格的原因是因爲你爲什麼要遍歷已標記爲刪除的同一列中的單元格?)?注意'退出For'? –

+0

好吧,我明白了。得到它了!我如何合併除了表3之外的其他表,因爲我只用一張表來測試程序,但實際上,我的參考數據是在幾張表中,而不僅僅是表3。 @Siddharth Rout – Niva