VBA – Count如果单元格范围的显示值等于期望值
我遇到了运行我的代码的问题,因为Range.Value
不同于Range.NumberFormat
。 例如,我的价值是一个date和时间,我想testing一周中的哪一天。 我能够将数字格式设置为Sun-Sat,但是我不确定如何使用CountIf
进行testing。
Dim rep as Worksheet Dim day As Range Dim time As Range Dim wf As WorksheetFunction Set rep = Worksheets("Report") Set day = rep.Range("H1", rep.Range("H1").End(xlDown)) Set time = rep.Range("I1", rep.Range("I1").End(xlDown)) Set wf = WorksheetFunction With rep .Columns("H").NumberFormat = "dddd" .Columns("I").NumberFormat = "AM/PM" .Range("K1") = "Monday" .Range("K2") = "Tuesday" .Range("K3") = "Wednesday" .Range("K4") = "Thursday" .Range("K5") = "Friday" .Range("K6") = "Saturday" .Range("K7") = "Sunday" .Range("M1") = "AM" .Range("M2") = "PM" .Range("L1") = wf.CountIf(day, "Monday") .Range("L2") = wf.CountIf(day, "Tuesday") .Range("L3") = wf.CountIf(day, "Wednesday") .Range("L4") = wf.CountIf(day, "Thursday") .Range("L5") = wf.CountIf(day, "Friday") .Range("L6") = wf.CountIf(day, "Saturday") .Range("L7") = wf.CountIf(day, "Sunday") .Range("N1") = wf.CountIf(time, "AM") .Range("N2") = wf.CountIf(time, "PM") End With
这是我迄今为止,但它只输出0为解决schemecountif
。 提前致谢。
这是另一种方法来做数量。 注意我做了大部分VBA数组中的“工作”,因为这比重复访问工作表要快得多:
编辑 :包括用AM或PM时间计算列H中的条目数
Option Explicit Sub foo() Dim rep As Worksheet Dim rDts As Range Dim vDts As Variant Dim vCnts As Variant 'for the weekday count Dim vAP As Variant 'for the AM PM count Dim I As Long, J As Long Set rep = Worksheets("sheet1") 'read dates into array -- faster processing With rep vDts = .Range(.Cells(1, 8), .Cells(.Rows.Count, 8).End(xlUp)) End With 'Results array ReDim vCnts(1 To 7, 1 To 2) vCnts(1, 1) = "Sunday" vCnts(2, 1) = "Monday" vCnts(3, 1) = "Tuesday" vCnts(4, 1) = "Wednesday" vCnts(5, 1) = "Thursday" vCnts(6, 1) = "Friday" vCnts(7, 1) = "Saturday" ReDim vAP(1 To 2, 1 To 2) vAP(1, 1) = "AM" vAP(2, 1) = "PM" 'Do the counts For I = 1 To UBound(vDts, 1) J = Weekday(vDts(I, 1)) vCnts(J, 2) = vCnts(J, 2) + 1 'Check for AM or PM If Hour(vDts(I, 1)) < 12 Then vAP(1, 2) = vAP(1, 2) + 1 Else vAP(2, 2) = vAP(2, 2) + 1 End If Next I 'output the results rep.Range("K1:L7").Value = vCnts rep.Range("M1:N2").Value = vAP End Sub