您的想法是在一次操作中刪除所有必要的行是轟動的。此外,避免Select
並避免循環一定範圍的單元格也會加快速度。
這裏是一個應該爲你工作
Sub Demo()
Dim sh As Worksheet
Dim rng As Range
Dim rngBlanks As Range
' Get a reference to the sheet you want to process
Set sh = ActiveSheet
' Get a reference to the range of cells to test
With sh
Set rng = .Range(.Cells(8, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
' if there are no blanks SpecialCells will error, so handle it
On Error Resume Next
' Reduce rng to reference only blank cells
Set rngBlanks = rng.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
' see if there are any blanks
If Not rngBlanks Is Nothing Then
' delete all of them
rngBlanks.EntireRow.Delete
End If
End Sub
更新基礎上提供額外信息的方法:「空白」細胞可能包含公式返回一個空字符串。
下面是使用AutoFilter
Sub Demo()
Dim sh As Worksheet
Dim rng As Range
Dim rngBlanks As Range
Application.ScreenUpdating = False
' Get a reference to the sheet you want to process
Set sh = ActiveSheet
' Get a reference to the range of cells to test, plus header row
With sh
Set rng = .Range(.Cells(7, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
' Apply filr to hide non-empty cells
sh.AutoFilterMode = False
rng.AutoFilter Field:=1, Criteria1:="=", VisibleDropDown:=True
' if there are no blanks SpecialCells will error, so handle it
On Error Resume Next
' Reduce rng to reference only blank cells, exclude header row
Set rngBlanks = rng.Offset(1, 0).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
' see if there are any blanks
If Not rngBlanks Is Nothing Then
' delete all of them
rngBlanks.EntireRow.Delete
End If
sh.AutoFilterMode = False
Application.ScreenUpdating = True
End Sub
我正在從Excel,所以我不選擇任何行宏的方法。我將數據從數據庫插入到sheet1中,Sheet2引用了sheet1中的字段並將其字段設置爲ref。領域。但我有一個100行的網格。如果數據僅在sheet2中有2行,則會有98行爲空。我需要運行這個宏som c#,然後一次刪除98行,而不是一次一行。你的代碼在這種情況下工作嗎? – Lahib 2013-04-10 08:30:35
我建議的代碼是excel代碼。你應該能夠把它放到你的宏中(而不是ActiveCell.EntireRow.Delete),它應該可以工作。不明白爲什麼它被標記下來。 – user1560834 2013-04-10 09:01:20
@ user1560834我不知道爲什麼它被標記下來。它工作正常,但它只選擇一列。我需要定義它必須選擇的列範圍。我怎樣才能做到這一點 ? – Lahib 2013-04-10 09:04:16