ExcelGirl1988
New Member
- Joined
- Mar 27, 2017
- Messages
- 44
Hi, I am trying to sort out my search function in VBA where dates are put in on a worksheet and the code will search for data between the two dates and then copy this data and paste it to another worksheet. This doesn't seem to work though and I am not advanced enough in my VBA code to work it out, can anyone help?
Code:
Sub CopyDataBasedonDate()
Dim DbExtract As Variant
Dim Search As Variant
'Disabling screen updates
Application.ScreenUpdating = False
'Declaring two variables of Date data type
Dim StartDate, EndDate As Date
StartDate = Format(CDate(StartDate), "dd/mm/yyyy")
EndDate = Format(CDate(EndDate), "dd/mm/yyyy")
'Declaring variable for worksheet object
Dim MainWorksheet As Worksheet
'Initializing the Date variables with starting date from cell J8
'and end date from cell J9 of "Macro" sheet
StartDate = Sheets("Home").Range("D3").Value
EndDate = Sheets("Home").Range("D4").Value
'Initializing worksheet object with "RawData" worksheet
Set MainWorksheet = Worksheets("Test1")
'Activating the worksheet object
MainWorksheet.Activate
'Sorting the data by date in column B in ascending order
Range("B3").CurrentRegion.Sort _
key1:=Range("A:C"), order1:=xlAscending, _
Header:=xlYes
'Filter the data based on date range between starting date and end date
Search = ActiveSheet.ListObjects("Table1").Range.Autofilter(Field:=2, Operator:= _
xlFilterValues, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate)
'Copy the filter data
MainWorksheet.ListObjects("Table1").Range.Copy
'Pasting the copied data
Selection.Copy
Sheets("Summary").Select
ActiveSheet.Paste
'Auto adjusting the size of selected columns
Selection.Columns.AutoFit
Range("A1").Select
'Removing filter from the worksheet which we applied earlier
If MainWorksheet.AutoFilterMode Then ActiveSheet.ShowAllData
Sheets("Home").Activate
End Sub