Excel:需要删除大约100万个空白行

时间:2015-01-06 21:26:39

标签: c# excel excel-vba filtering delete-row vba

我有一个来自我们客户的excel文件,该文件有近100万个空白行。

我尝试在C列(称为Items)上对其进行过滤,然后选择所有行并尝试删除。它几乎冻结了将近几个小时,但最后我杀死了excel进程。

我也尝试过以下VBA脚本,但它的实际行是" r.rows(i)。删除"只是冻结这是第一个删除实例本身。

我也将excel文件设置为手动进行公式计算。

我不介意整个工作需要几个小时。我可以在一夜之间离开并在早上办理入住手续。

如果VB.NET或C#中有任何内容也可以。

更新1:我无法在1到1048576行之间进行批量删除,我需要删除列C为空的那些行(这意味着该行为空)。 / p>

更新2:我将下面的删除标记为答案,但我最终通过将GOOD行复制到另一个工作表来解决问题。

请建议处理此方案的最佳选项。

VBA来源

Sub BlankRowDelete()

Dim r As Range, rows As Long, i As Long
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
ActiveSheet.AutoFilterMode = False

Set r = ActiveSheet.Range("A1:A1048576")
rows = r.rows.Count
For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then
        r.rows(i).Delete
        RowDeleted = RowDeleted + 1
    Else
        NotDeleted = NotDeleted + 1
    End If
    totalcnt = totalcnt + 1
    If RowDeleted = 100 Then
       TotalDeleted = TotalDeleted + RowDeleted
       RowDeleted = 0
       Debug.Print "count now is " + totalcnt
    End If
    Application.StatusBar = "Row count is " + totalcnt
Next
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
ActiveSheet.AutoFilterMode = True

End Sub

2 个答案:

答案 0 :(得分:2)

我对您的代码进行了一些更新,例如doevents,打开状态栏,因为oyu正在写入它,并在需要时更新屏幕并在写出数值时添加cstr()。我跑了没问题。如评论中所述,这仅删除单元格A而不是整行

Sub BlankRowDelete()
On Error GoTo myError
Dim r As Range, rows As Long, i As Long
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
ActiveSheet.AutoFilterMode = False

Set r = ActiveSheet.Range("C1:C1048576") 
rows = r.rows.Count
For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then
        r.rows(i).EntireRow.Delete
        RowDeleted = RowDeleted + 1
    Else
        NotDeleted = NotDeleted + 1
    End If
    totalcnt = totalcnt + 1
    If RowDeleted = 100 Then

       Application.ScreenUpdating = True
       TotalDeleted = TotalDeleted + RowDeleted
       RowDeleted = 0
                   'you can uncomment this but since this is a dup since writting to statusbar (imo)
      'Debug.Print "count now is " + CStr(totalcnt)

       Application.ScreenUpdating = False
    End If
    Application.StatusBar = "Row count is " + CStr(totalcnt)
    DoEvents
Next
myError:
If Err.Number <> 0 Then
MsgBox CStr(i) & ": " & Err.Description
End If
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
ActiveSheet.AutoFilterMode = True
End Sub

答案 1 :(得分:0)

按C列的升序对文档进行排序。空行将结束,因此删除它们应该很容易。