日期输入 - 高级过滤器

时间:2021-02-12 06:25:02

标签: excel vba

你能帮我吗?

我有一个电子表格,我在 VBA 中使用了高级过滤器。 单元格“M5”是日期自,“N5”是日期至。 这个想法是用户输入“date from”和“date to”并过滤数据。

我正在使用下面的代码,但它不起作用。数据根本没有被过滤或部分被过滤。有人可以帮我吗?

Sub TableFilt()

Dim ToDate, FrDate        As Date

'Improve the performance of the macro
With Application
    .ScreenUpdating = FALSE
    .DisplayAlerts = FALSE
End With

With Sheet6
    LastRow = .Range("E99999").End(xlUp).Row
    
    'If .Range("M5").Value = "From Date" Then FrDate = "1/1/2015" Else: FrDate = .Range("M5").Value                            
    'If .Range("N5").Value = "To Date" Then ToDate = "31/12/2030" Else: ToDate = Range("N5").Value                              
    
   .Range("E6:AU" & LastRow).Select
    
    Selection.AutoFilter
    With .Range("E6:AU" & LastRow)
        .AutoFilter Field:=9, Criteria1:=">=" & FrDate, Operator:=xlAnd, Criteria2:="<=" & ToDate        
    End With
    
End Sub

2 个答案:

答案 0 :(得分:0)

做了一些改变,对我有用:

Sub TableFilt()

Dim ToDate As Date, FrDate As Date

With Sheet6
    LastRow = .Range("E99999").End(xlUp).Row
    
    If .Range("M5").Value = "From Date" Then FrDate = "1/1/2015" Else: FrDate = .Range("M5").Value
    If .Range("N5").Value = "To Date" Then ToDate = "31/12/2030" Else: ToDate = .Range("N5").Value

    With .Range("E6:AU" & LastRow)
        .AutoFilter Field:=9, Criteria1:=">=" & FrDate, Operator:=xlAnd, Criteria2:="<=" & ToDate
    End With
End With

End Sub
  1. AFAIK Dim ToDate, FrDate As Date 只会将 FrDate 变暗为 date,而将 ToDate 保留为 variant。应该仍然有效,但只是作为一个注释。

  2. 我认为在使用自动筛选时禁用 ScreenUpdatingDisplayAlerts 没有意义,因此已将其删除。无论如何不应该超过一个变化。

  3. 需要两个 If,所以我们不能将它们作为注释。还有一个范围内的缺失点。

  4. 我认为选择任何内容都没有意义,因此已将其删除。无论如何,该区域在下一行中定义。

  5. 缺少 End With 以完成 Sub。

答案 1 :(得分:0)

日期值不是文本,但需要格式化为条件的字符串表达式,所以试试这个:

Sub TableFilt()

    Dim ToDate  As Date
    Dim FrDate  As Date

    ' Improve the performance of the macro
    With Application
        .ScreenUpdating = FALSE
        .DisplayAlerts = FALSE
    End With

    With Sheet6
        LastRow = .Range("E99999").End(xlUp).Row
        
        If .Range("M5").Value = "From Date" Then FrDate = #1/1/2015# Else: FrDate = .Range("M5").Value                            
        If .Range("N5").Value = "To Date" Then ToDate = #12/31/2030# Else: ToDate = .Range("N5").Value                              
        
        .Range("E6:AU" & LastRow).Select
        
        Selection.AutoFilter
        With .Range("E6:AU" & LastRow)
            .AutoFilter Field:=9, Criteria1:=">= #" & Format(FrDate, "yyyy\/mm\/dd") & "#", Operator:=xlAnd, Criteria2:="<= #" & Format(ToDate, "yyyy\/mm\/dd") & "#"
        End With
    End With
    
End Sub