如何自动筛选表格内容并计算结果行数?

我正在用VBA来计算一周中的某一天和一天中的小时(分别绘制)的事件的实例。 date/时间戳记的格式如下:“2/28/2014 20:32”

例:
AppID = 14329
DateCreated = 2/28/14 20:55
日=星期五
小时= 20:55

我现在正在将数据复制到一个新的列,并将date格式设置为“dddd”,所以它会显示为“星期天”等。从那里我是自动过滤一周的每一天,并计数产生的可见细胞。 这是用这个代码:

With Range("C2:C" & LR) .AutoFilter .AutoFilter Field:=3, Criteria1:="Sunday" cCnt = ActiveSheet.AutoFilter.Range.Columns(3) _ .SpecialCells(xlCellTypeVisible).Cells.Count For Each cell In Range("C2:C" & cCnt) Sun = Sun + 1 Next .AutoFilter Field:=3, Criteria1:="Monday" cCnt = ActiveSheet.AutoFilter.Range.Columns(3) _ .SpecialCells(xlCellTypeVisible).Cells.Count For Each cell In Range("C2:C" & cCnt) Mon = Mon + 1 Next 

…等等。

不过,我的问题是按小时计算事件。 我试图通过将date/时间复制到新列并将格式设置为“h:mm; @”并使用此代码按小时自动过滤来执行此操作:

 With Range("D2:D" & LR) .AutoFilter .AutoFilter Field:=4, Criteria1:="10:??" cCnt = ActiveSheet.AutoFilter.Range.Columns(4) _ .SpecialCells(xlCellTypeVisible).Cells.Count For Each cell In Range("D2:D" & cCnt) time(10) = time(10) + 1 Next 

…等等。

这不工作,我不明白为什么。 我已经尝试将criteria1更改为各种语法,添加第二个条件参数,并难以理解为什么此方法适用于第一次使用,而不是第二次时,这两个列是从相同的原始数据派生。 我也尝试将数据更改为不同的时间格式(只是“呃”等)。

Excel如何存储date和时间:

Excel使用“序列号”系统来存储date(第一天是1900年1月1日):

01/01/1900 = 1

01/02/1900 = 2

时间由十进制后的任何东西表示(中午是0.5,因为它是一天的一半):

01/01/1900 12:00 = 1.5

01/02/1900 15:00 = 2.625

如果您根据数值进行过滤,请务必了解这一点。

将此代码包含在您的模块中:

  Public Function GetDay(ByVal inputDate As String) As String GetDay = WeekdayName(Weekday(inputDate)) End Function Public Function GetHour(ByVal inputDate As Range) As String GetHour = Format(inputDate.Value, "Medium Time") End Function 

现在在工作表和自动填写中使用这些函数:

原始数据表表步骤1表步骤2决赛桌

在您现有的代码中修改以下内容:

  With Range("D2") .AutoFilter Field:=4, Criteria1:="10:?? PM" 'If criteria didn't match anything, cCnt is equal to 1 (because header rows are visible and counted) cCnt = ActiveSheet.AutoFilter.Range.Columns(4).SpecialCells(xlCellTypeVisible).Cells.Count If cCnt > 1 Then For Each cell In Range("D2:D" & cCnt) Hour10PM = Hour10PM + 1 Next End If MsgBox (Hour10PM & " matches for 10:00PM to 10:59PM") .AutoFilter Field:=4, Criteria1:="11:?? PM" cCnt = ActiveSheet.AutoFilter.Range.Columns(4).SpecialCells(xlCellTypeVisible).Cells.Count If cCnt > 1 Then For Each cell In Range("D2:D" & cCnt) Hour11PM = Hour11PM + 1 Next End If MsgBox (Hour11PM & " matches for 11:00PM to 11:59PM") End With 

补充笔记:

很明显,我只是给了一小段代码,但是这个想法是,你可以分裂并保持每小时的计数。 然后来图表应该是简单的。