简体   繁体   中英

Delete rows based off blank cells in a range

I am trying to delete blank rows in a range

My code looks like this :

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

So, hmqcnoesy has kindly helped me solve the error message. The variables should be Dimmed as LONG not INTEGER because integer can not hold as big a number for all my rows of data

Also, Jon49 gave me some code that was much mroe efficient for this process:

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 

It looks like you should try using type Long for i and counter . Using Integer causes an overflow, at least in newer versions of Excel, where there are over 1 million rows in a worksheet.

Here's some simpler code for you:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM