Excel VBA - 在一组日期

时间:2016-03-29 17:36:50

标签: excel vba excel-vba date autofilter

我还在学习Excel VBA,如果有人能帮助我做到这一点,我会很感激。我想基于在名为DateMaster的工作表中指定的startDate和endDate过滤日期列。当我运行宏时,它给我运行时错误13,开始日期= 0.下面是我的代码。

Sub FIlterCopy()

Dim StartDate As Long
Dim EndDate As Long

StartDate = ThisWorkbook.Worksheets("DateMaster").Range("C2").Value
EndDate = ThisWorkbook.Worksheets("DateMaster").Range("D2").Value

Application.ScreenUpdating = False

ThisWorkbook.Worksheets("FilterMaster").Activate

Range("A:BA").Select

Selection.ClearContents

Application.Workbooks.Open ("C:\WRI\Data\Revenue Update.xls")

Windows("Revenue Update.xls").Activate

Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.AutoFilter
Selection.AutoFilter Field:=5, Criteria1:= _
"=Backlog", Operator:=xlOr, Criteria2:="=RMA"
Selection.AutoFilter Field:=29, Criteria1:= _
"=Direct"
Selection.AutoFilter Field:=20, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

如果您将StartDateEndDate设置为Long,则应在autofilter上使用CDate命令

Selection.AutoFilter Field:=20, Criteria1:=">=" & CDate(StartDate), Operator:=xlAnd, Criteria2:="<=" & CDate(EndDate)

否则,将两个变量定义为Date