I am very new to VBA and macros in Excel. I have a very large excel spreadsheet in which column A holds dates. I am trying to delete the rows which have a value smaller than a certain date and this is what I have come up with till now..
Sub DELETEDATE()
Dim x As Long
For x = 1 To Cells.SpecialCells(xlCellTypeLastCell).Row
Debug.Print Cells(x, "A").Value
If CDate(Cells(x, "A")) < CDate("01/01/2013") Then
Cells(i, "A").EntireRow.Delete
End If
Next x
Next i
End Sub
I am receiving a Next without For error... can somebody help please?
This lends itself well to using the
.AutoFilter
property of aRange
. The script below contains a comment for each step taken:Running this code on a simple example (on "Sheet1" in this picture) that looks like this:
Will delete all rows with a date older than 1/1/2013, giving you this result:
You have an additional
Next i
for some reason in your code as highlighted by the debugger. Try the below:To answer your question
The problem is you are trying to loop on
i
but you haven't opened aFor i
loop. When you indent the code below any code that invokes aLoop
or condition (i.e.If
) it becomes obviousWhen writing code I try to:
If...Then
, hit[ENTER]
, typeEnd If
, hit[HOME]
, hit[ENTER]
, hit[UP ARROW]
then[TAB]
to the right place to write the conditional code so that anyone will be able to read and understand it easily.Option Explicit
at the top of every module to force variable declarations.a tip about deleting rows based on a condition If you start at the top and work down, every time you delete a row your counter will effectively move to the cell two rows below the row you deleted because the row immediately below the deleted row moves up (i.e. it is not tested at all).
The most efficient way is to loop up from the bottom or your rows:
This way, the next row you want to test has been preserved - you've only moved the row below up by 1 and you've tested that row earlier.
Please try with this