Excel VBA For Each skipping cells -


im coding simple macro in excel vba deletes entire row if first cell has specific text. here's code far:

sub mymacro()     each mycell in worksheets("hoja2").range("a1:a20")         if mycell.value = "borrar"             mycell.entirerow.delete         end if     next end sub 

my sheet2 (hoja2) has 2 columns, first column full of "borrar" a1 a20 , second column has numbers, 1 20.

if activate macro, deletes every row except 2,4,6,8,10,12,14,16,18 , 20. if activate macro again, deletes except 4,8,12,16,20 if activate macro again, deletes except 8,16 , on.

why happening? far understand, macro checks 1 one if cell of first column has word "borrar" in it, , if does, deletes entire row. why deleting multiple of 2,4,8...?

it's because you're stepping forward through rows , deleting them.

if delete row 2 row 3 becomes new row 2 , loop goes on @ row 3 row 4 - row 3 has been missed completely.

use:

for x = 20 1 step -1      if worksheets("hoja2").cells(x,1) = "borrar"         worksheets("hoja2").cells(x,1).entirerow.delete      end if next x 

note - haven't tested above code, should work.


Comments