下面的代码是我这个项目的完整代码的片段,但这是它失败的地方。用户在单元格C3中键入日期,自动过滤器将设置为该日期。但是,当我这样做时,自动过滤器不返回任何数据(即使它确实存在)。我已经在论坛上看到了查询,并尝试了从这些问题中提供的众多建议,但仍无法获得蚂蚁数据显示。任何人都可以提供一些方向。 excel中的日期是“dd / mm / yyyy”
Option Explicit
Sub autofilter_by_date()
Dim wks As Worksheet
Set wks = ActiveSheet
Sheets("Log").Select
Dim dDate As Date
dDate = Worksheets("Sheet1").Range("C3")
dDate = DateSerial(Year(dDate), Month(dDate), Day(dDate))
With wks
If Not .AutoFilterMode Then
Range("Table2[[#Headers],[Date Requested]]").AutoFilter
End If
If .FilterMode Then .ShowAllData
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=1, Operator:= _
xlFilterValues, Criteria1:=dDate
Range("Table2[[#Headers],[H Name]]").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
End With
Sheets("Sheet3").Select
Range("A1").Select
ActiveSheet.Paste
Columns("A:A").EntireColumn.AutoFit
Application.CutCopyMode = False
ActiveSheet.Range(Selection, Selection.End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
答案 0 :(得分:2)
尝试改变:
<强> 1 强>
这
Dim dDate As Date
dDate = CDate(Format(Worksheets("Controls").Range("C3"), "dd/mm/yyyy"))
到
Dim dDate As String
dDate = Format(Worksheets("Sheet1").Range("C3"), "dd/mm/yyyy")
2。
这
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=1, Operator:= _
xlFilterValues, Criteria1:=dDate
到
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=1, Criteria1:=">=" & CLng(dDate), Operator:=xlAnd, Criteria2:="<" & CLng(dDate) + 1
答案 1 :(得分:0)
下面的完整代码,经过测试和测试。 (excel表格中的单元格C4是显示为数字的日期)
Option Explicit
Sub autofilter_by_date()
Dim wks As Worksheet
Set wks = ActiveSheet
Sheets("Log").Select
Dim dDate As String
dDate = Format(Worksheets("Controls").Range("C4"))
With wks
If Not .AutoFilterMode Then
Range("Table2[[#Headers],[Header Name]]").AutoFilter
End If
If .FilterMode Then .ShowAllData
ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=1, Criteria1:=">=" & CLng(dDate), _
Operator:=xlAnd, Criteria2:="<" & CLng(dDate) + 1
Range("Table2[[#Headers],[Haulier Name]]").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
End With
Sheets("Sheet3").Select
Range("A1").Select
ActiveSheet.Paste
Columns("A:A").EntireColumn.AutoFit
Application.CutCopyMode = False
ActiveSheet.Range(Selection, Selection.End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub