Reputation: 1
I am trying to get more into VBA as it allows a lot more freedom. What I am trying to figure out is how can I do a VBA to filter a column to show only values that only occur last month, current month and two months in the future.
I know I can use xlFilterLastMonth but right now I am still just recording macros and then changing them to fit my more specific needs. I can find singular filters using xlFilterNextMonth or xlFilterLastMonth. But I can't really find anything for what I am looking for.
Here is my current Macro:
Sub BASICPQS()
'
' BASICPQS Macro
'
'
Sheets("PRODUCTION").Range("$A$1:$AA$146").AutoFilter Field:=9, Operator:= _
xlFilterValues, Criteria2:=Array(1, "3/31/2016", 1, "4/27/2016")
ActiveWindow.SmallScroll Down:=-18
End Sub
Any help would be appreciated. Thanks.
Upvotes: 0
Views: 3140
Reputation: 96753
Say we have data like:
Dates
2/27/2016
5/28/2016
1/30/2016
5/3/2016
2/13/2016
4/29/2016
2/3/2016
7/5/2016
5/23/2016
3/11/2016
7/3/2016
2/5/2016
5/4/2016
6/20/2016
6/26/2016
7/14/2016
5/9/2016
1/26/2016
2/14/2016
3/9/2016
4/1/2016
2/18/2016
3/7/2016
In column A and we want to display dates in:
These are dates greater than or equal to 3/1/2016 and less than or equal to 6/30/2016 if today is 4/20/2016.
Consider:
Sub Macro1()
Dim d1 As Date, d2 As Date
Dim cr1 As String, cr2 As String
d1 = DateSerial(Year(Now), Month(Now) - 1, 1)
d2 = DateSerial(Year(Now), Month(Now) + 3, 0)
MsgBox d1 & vbCrLf & d2
MsgBox CLng(d1) & vbCrLf & CLng(d2)
cr1 = ">=" & CStr(CLng(d1))
cr2 = "<=" & CStr(CLng(d2))
ActiveSheet.Range("$A$1:$A$24").AutoFilter Field:=1, Criteria1:=cr1, _
Operator:=xlAnd, Criteria2:=cr2
End Sub
The result:
You must test this further to see if it works if today is in January or December. That is, can the code look ahead to next year or back to the previous year.
Upvotes: 1