按月过滤名称仅限

时间:2015-09-15 08:44:54

标签: excel vba excel-vba date

我在单元格A1,A2和A3中有三个日期。我想获取每个日期的月份并过滤包含多个日期的数据集。过滤器应仅包含A1,A2和A3中三个日期中每个日期中存在的日期。

例如:

A1:01/01/2015,
A2:01/02/2015,
A3:01/03/2015

 Dataset:
 20/01/2015
 25/12/2015
 01/09/2015
 14/02/2015
 15/03/2015
 01/06/2015

过滤器应该是:

 20/01/2015
 14/02/2015
 15/03/2015

我目前的语法是:

 Dim mon1 As String
 Dim mon2 As String
 Dim mon3 As String

 Dim a As Date
 Dim b As Date
 Dim c As Date

 a = Range("A1")
 b = Range("A2")
 c = Range("A3")

mon1 = MonthName(Month(a))
mon2 = MonthName(Month(b))
mon3 = MonthName(Month(c))

With ActiveSheet

 .AutoFilterMode = False
 .Range("A5:D5000").AutoFilter Field:=3, Criteria1:=Array(mon1, mon2, mon3), Operator:=xlFilterValues

End With

不幸的是,它似乎不起作用。

1 个答案:

答案 0 :(得分:3)

  1. 在右侧插入一列,并将其命名为Month。

    enter image description here

  2. 将此公式=TEXT(C6,"mmmm")放入D6,然后使用以下代码

  3. 代码

    Sub Sample()
        Dim mon1 As String, mon2 As String, mon3 As String
    
        mon1 = MonthName(Month(Range("A1")))
        mon2 = MonthName(Month(Range("A2")))
        mon3 = MonthName(Month(Range("A3")))
    
        With ActiveSheet
            .AutoFilterMode = False
            .Range("A5:D5000").AutoFilter Field:=4, _
            Criteria1:=Array(mon1, mon2, mon3), _
            Operator:=xlFilterValues
        End With
    End Sub
    

    <强>输出

    enter image description here