根据范围内的空白单元格删除行

时间:2011-08-25 20:10:39

标签: excel vba excel-2003

我正在尝试删除范围内的空白行

我的代码如下所示:

Dim rng As Range
Dim i As Long, counter As Long

i = 1

Range("B1").Select
Selection.End(xlDown).Offset(0, 5).Select

Set rng = Range("G2", ActiveCell)

Range("G2").Select

For counter = 1 To rng.Rows.Count

    If rng.Cells(i) = "" Then
       rng.Cells(i).EntireRow.Delete
    Else
        i = i + 1
    End If

Next

所以,hmqcnoesy帮我解决了错误信息。变量应该变暗为LONG而不是INTEGER,因为整数不能保存所有数据行的数字

另外,Jon49给了我一些代码,这个代码对于这个过程非常有效:

Dim r1 As Range  'Using Tim's range.     
Set r1 = ActiveSheet.Range(Range("G2"),Range("B1").End(xlDown).Offset(0, 5))   
    'Delete blank cell rows. 
r1.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Set r1 = Nothing 

3 个答案:

答案 0 :(得分:4)

您似乎应该尝试将Long用于icounter。使用Integer会导致溢出,至少在较新版本的Excel中,工作表中有超过100万行。

答案 1 :(得分:3)

以下是一些更简单的代码:

Dim r1 As Range

'Using Tim's range.    
Set r1 = ActiveSheet.Range(Range("G2"),Range("B1").End(xlDown).Offset(0, 5)) 

'Delete blank cell rows.
r1.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Set r1 = Nothing

答案 2 :(得分:2)

Dim rng As Range 
Dim counter As Long  

Set rng = Range(Range("G2"),Range("B1").End(xlDown).Offset(0, 5))  
For counter = rng.Rows.Count to 1 Step -1   
   If Len(rng.Cells(counter).Value) = 0 Then rng.Cells(counter).EntireRow.Delete
Next