Delete the entire row if next or previous month using a macro in an excel report

When I am doing a monthly report, I need just the data of the current month, next month or previous month so I have to delete the months not in scope. For instance, when I am extracting data, I can have an issue starting during this month but not closed yet, depending of the report, I don’t want to count it because it is still opened.

formula excel formula excel

 

When I use the macro ?

When I need to delete the entire row based on the date for my monthly report.

 

How to create the macro ?

Read How to create, edit, hide and select a macro in an excel report

 

How to create the button to associate it with the macro ?

Read How to create a button and associated it to a macro in an excel report

 

How is the macro ?

Copy the code below and paste it into your macro. You will see my comments in green if exist so follow the help to adapt to your need.

For a column keeping current month:

Sub test()
Dim Rang As Range
Dim Cell As Range
Dim Arr() As Long
Dim Num As Long
Dim i As Long
With ActiveSheet
' change B if your date in other column and for multiple columns put B:C
Set Rang = Intersect(.Columns("B"), .UsedRange)
End With
Num = 0
For Each Cell In Rang
If IsDate(Cell.Value) Then
' add -1 for previous month or +1 for next month ie month(date) - 1
If Cell.Value < Int(DateSerial(Year(Date), Month(Date), 1)) Then
Num = Num + 1
ReDim Preserve Arr(1 To Num)
Arr(Num) = Cell.Row
End If
End If
Next Cell
For i = Num To 1 Step -1
ActiveSheet.Rows(Arr(i)).Delete
Next i
End Sub

Checking cell by cell deleting current month:

Sub test()
Dim i As Integer
i = 2
' change 2 if your date not in column B and change 50 if you have more rows
Do While (Cells(i, 2).Value <> "") And (i< 50)
If VarType(Cells(i, 2)) = vbDate Then
' add -1 for previous month or +1 for next month ie month(date) - 1
If Cells(i, 2) >= Int(DateSerial(Year(Date), Month(Date), 1)) Then
Cells(i, 2).EntireRow.Delete
End If
End If
i = i + 1
Loop
End Sub

Interesting Management