Forum Discussion

sebring1983's avatar
sebring1983
Copper Contributor
May 15, 2023
Solved

automate a workbook to move rows with a date older the 3 years

I am trying to automate a workbook to move rows with a date older the 3 years from sheet3 ( dates are in column G ) to sheet4. I can get it to work with If mydate only if I specify the date range of ...
  • NikolinoDE's avatar
    May 16, 2023

    sebring1983 

    May be, you can use the TODAY() function in Excel to get the current date and then subtract 3 years from it to get the date range you need.

    Here’s an example of how you can do this using VBA:

    Sub MoveRows()
        Dim mydate As Date
        mydate = DateAdd("yyyy", -3, Date) 'Get the date 3 years ago from today
        Dim lastrow As Long
        lastrow = Sheets("Sheet3").Cells(Rows.Count, "G").End(xlUp).Row 'Find the last row with data in column G of Sheet3
        Dim i As Long
        For i = lastrow To 1 Step -1 'Loop through rows from bottom to top
            If Sheets("Sheet3").Cells(i, "G").Value < mydate Then 'If the date in column G is older than 3 years
                Sheets("Sheet3").Rows(i).Cut 'Cut the row
                Sheets("Sheet4").Rows(Sheets("Sheet4").Cells(Rows.Count, "G").End(xlUp).Row + 1).Insert Shift:=xlDown 'Insert the row into Sheet4
            End If
        Next i
    End Sub

    Code is untested.

    Hope it helps you!

Resources