简体   繁体   中英

VBA isn't deleting blank cells

I've been using a IF condition to find the blank cells in the spreadsheet, then delete the part of the line I don't want and move the other cells up. It was going well, but when I used this database the code won't delete some lines.

Here is the following part where it find and deletes part of the line:

Dim wb As Workbook
Dim Disciplinas As Worksheet
Set wb = ThisWorkbook
Set Disciplinas = wb.Sheets("Disciplinas")

Dim start_time As range
Dim i As Integer, nLines As Integer

nLines = Disciplinas.Cells(Rows.Count, 2).End(xlUp).Row

Set start_time = Disciplinas.Rows(1).Find(what:="HR_INICIO", LookIn:=xlValues, lookat:=xlWhole)

For i = 2 To nLines
    If Disciplinas.Cells(i, start_time.Column) = "" Then
        Disciplinas.Cells(i, 2).Resize(, 13).Delete Shift:=xlUp
    End If
Next

Here is the file: Spreadsheet (the cells I'm having trouble are E105 to E125. The other ones have already been deleted in the first time I ran the code).

Instead of If Disciplinas.Cells(i, start_time.Column) = "" Then i've tried vbNullString and isEmpty() = TRUE , where all of them did not delete the lines. I've used the formula =ISBLANK() directly in the spreadsheet and the result was true.

I have noticed if I run the code multiple times eventualy it deletes all the lines I want. I ask myself why it don't remove it all in the first run? Thanks.

The solution was indeed quite simple, it was just necessary to run the loop backwards, as paulsm4 suggested.

I've had to change For i = 2 To nLines for For i = nLines to 2 Step -1 .

The explanation is that when VBA deletes the line and moves it up the counter increments and go one line down, "missing" some lines, as Peh explained.

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