autofilter date by VBA

carlrubber

New Member
Joined
Oct 15, 2016
Messages
48
I have a cell G1 storing a date and I would like to filter by changing the date in G1. however the below code not filter the correct answer.
would anyone help please....

VBA Code:
Sub SearchBox()
'PURPOSE: Filter Data on User-Determined Column & Text/Numerical value

Dim myButton As OptionButton
Dim SearchDate As String
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant

  Set sht = ActiveSheet

'Unfilter Data (if necessary)
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0

'Filtered Data Range
  Set DataRange = Range("A30:k1003")

'Retrieve User's Search Input
mySearch = Sheets("Table 1&2").Range("G1")
  mySearch = CLng(DateValue(mySearch))

 
'Determine if user is searching for number or text
If IsNumeric(mySearch) = True Then
SearchDate = "=*" & mySearch
'Else
' SearchString = "=*" & mySearch & "*"
End If

'Loop Through Option Buttons
For Each myButton In ActiveSheet.OptionButtons
If myButton.Value = 1 Then
ButtonName = myButton.Text
Exit For
End If
Next myButton

'Determine Filter Field
myField = WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)

'Filter Data
DataRange.AutoFilter _
Field:=myField, _
Criteria1:=SearchDate, _
Operator:=xlAnd

End Sub
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Nth wrong with the code but the result after sorting is not correct . It always sorts nth

Your code does not contain any instructions to sort
How should it be sorted ?

Will data range always be rows 30 to 1003 ?
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,324
Members
452,635
Latest member
laura12345

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