search data between two dates by code

abdelfattah

Well-known Member
Joined
May 3, 2019
Messages
1,429
Office Version
  1. 2019
  2. 2010
Platform
  1. Windows
hello
i do a simple code but it gives me error to search data betwwen dates the sheet1 contains data from a7:d and i would search into sheet2 first date = c2 end date= c3 and gives me data from sheet1 to sheet2 in this range (a2:d7) i hope anybody fixing my code i would the result in image 2
VBA Code:
Sub test()
    Dim i As Long
    Dim Startdate As Date
    Dim Enddate As Date
    LASTROW = Cells(Rows.Count, 1).End(xlUp).Row
    Startdate = SHEET2.Range("c2").Value
    Enddate = SHEET2.Range("c3").Value
    
    For i = 7 To LASTROW
      If sheet1.Range("A7:d" & i).Value >= Startdate And sheet1.Range("A7:d" & i).Value <= Enddate Then
        sheet1.Range("a7:d" & i + 1).Value = sheet1.Range("a7:d" & i).Value
      End If
    Next i
End Sub



d1.JPG


d2.JPG
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).
How about the below code ?

VBA Code:
Sub FilterData()

Dim startDate As Long, endDate As Long
startDate = Sheet2.Range("C2").Value
endDate = Sheet2.Range("C3").Value

With Sheet1.UsedRange
    .AutoFilter 1, ">=" & startDate, xlAnd, "<= " & endDate
    .SpecialCells(xlCellTypeVisible).Copy Sheet2.[A6]
    .AutoFilter
End With

End Sub
 
Upvote 0
I think you need to add one more line before the "with" line to clear any data from previous filters used

Sheet2.Range("A6").CurrentRegion.Clear
 
Upvote 0
your code works meanwhile i was writing about the problem previous data it stays when i search a new data but it reached me your alert and you solve it post #3
thank you so much
 
Upvote 0

Forum statistics

Threads
1,214,651
Messages
6,120,738
Members
448,988
Latest member
BB_Unlv

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top