Nguồn: http://www.dailydoseofexcel.com/archives/2008/11/26/autofiltering-on-months/
Đôi khi chúng ta cần lọc số liệu theo tháng. Lúc ấy, chúng ta dùng Autofilter tương tự như hình sau:
Phức tạp nhỉ, mắc công xem ngày cuối tháng là ngày nào, ngày đầu tháng là ngày nào. Nếu tạo ra cột phụ cũng không thích. Vậy nên chúng ta có thể dựa vào giá trị ngày tại ô hiện hành (ActiveCell), và sau đây là đoạn mã để chúng ta áp dụng:
Vbavn
Đôi khi chúng ta cần lọc số liệu theo tháng. Lúc ấy, chúng ta dùng Autofilter tương tự như hình sau:
![autofiltermonth.gif](http://i2.photobucket.com/albums/y4/levanduyet/autofiltermonth.gif)
Phức tạp nhỉ, mắc công xem ngày cuối tháng là ngày nào, ngày đầu tháng là ngày nào. Nếu tạo ra cột phụ cũng không thích. Vậy nên chúng ta có thể dựa vào giá trị ngày tại ô hiện hành (ActiveCell), và sau đây là đoạn mã để chúng ta áp dụng:
Mã:
[COLOR=#0000dd]Sub[/COLOR] FilterOnMonth[COLOR=#008800]([/COLOR][COLOR=#008800])[/COLOR]
[COLOR=#007f00]'Create a filter in the active column within a sheet's autofilter[/COLOR]
[COLOR=#007f00]'Use the month of the activecell to filter the range[/COLOR]
[COLOR=#0000dd]Dim[/COLOR] lMonth [COLOR=#0000dd]As[/COLOR] [COLOR=#0000dd]Long[/COLOR]
[COLOR=#0000dd]Dim[/COLOR] lYear [COLOR=#0000dd]As[/COLOR] [COLOR=#0000dd]Long[/COLOR]
[COLOR=#0000dd]If[/COLOR] [COLOR=#0000dd]IsDate[/COLOR][COLOR=#008800]([/COLOR]ActiveCell.Value[COLOR=#008800])[/COLOR] [COLOR=#0000dd]Then[/COLOR]
lMonth = [COLOR=#0000dd]Month[/COLOR][COLOR=#008800]([/COLOR]ActiveCell.Value[COLOR=#008800])[/COLOR]
lYear = Year[COLOR=#008800]([/COLOR]ActiveCell.Value[COLOR=#008800])[/COLOR]
[COLOR=#007f00]'Check if there is an autofilter[/COLOR]
[COLOR=#0000dd]If[/COLOR] ActiveCell.Parent.AutoFilterMode [COLOR=#0000dd]Then[/COLOR]
[COLOR=#007f00]'Make sure activecell is within autofilter range[/COLOR]
[COLOR=#0000dd]If[/COLOR] [COLOR=#0000dd]Not[/COLOR] Intersect[COLOR=#008800]([/COLOR]ActiveCell, _
ActiveCell.Parent.AutoFilter.Range[COLOR=#008800])[/COLOR] [COLOR=#0000dd]Is[/COLOR] [COLOR=#0000dd]Nothing[/COLOR] [COLOR=#0000dd]Then[/COLOR]
[COLOR=#007f00]'Create filter[/COLOR]
[COLOR=#0000dd]With[/COLOR] ActiveCell.Parent.AutoFilter
.Range.AutoFilter ActiveCell.Column - .Range[COLOR=#008800]([/COLOR][COLOR=#cc66cc]1[/COLOR][COLOR=#008800])[/COLOR].Column + [COLOR=#cc66cc]1[/COLOR], _
[COLOR=#ff0000]">="[/COLOR] & [COLOR=#0000dd]DateSerial[/COLOR][COLOR=#008800]([/COLOR]lYear, lMonth, [COLOR=#cc66cc]1[/COLOR][COLOR=#008800])[/COLOR], _
xlAnd, _
[COLOR=#ff0000]"<="[/COLOR] & [COLOR=#0000dd]DateSerial[/COLOR][COLOR=#008800]([/COLOR]lYear, lMonth + [COLOR=#cc66cc]1[/COLOR], [COLOR=#cc66cc]0[/COLOR][COLOR=#008800])[/COLOR]
[COLOR=#0000dd]End[/COLOR] [COLOR=#0000dd]With[/COLOR]
[COLOR=#0000dd]End[/COLOR] [COLOR=#0000dd]If[/COLOR]
[COLOR=#0000dd]End[/COLOR] [COLOR=#0000dd]If[/COLOR]
[COLOR=#0000dd]End[/COLOR] [COLOR=#0000dd]If[/COLOR]
[COLOR=#0000dd]End[/COLOR] [COLOR=#0000dd]Sub
[/COLOR]
Vbavn