VBA - CountIf单元格范围显示值等于所需值

时间:2017-12-01 21:02:07

标签: excel vba excel-vba countif

我在运行代码时遇到问题,因为Range.ValueRange.NumberFormat不同。例如,我的值是一个日期和时间,我想测试一周中的哪一天。我能够将数字格式设置为Sun-Sat,但是,我不确定如何使用CountIf进行测试。

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

这是我到目前为止所做的,但它只为countif的解决方案输出0。提前谢谢。

1 个答案:

答案 0 :(得分:2)

这是另一种计算方法。 注意我在VBA数组中完成了大部分“工作”,因为这比重复访问工作表快得多:

编辑:包括计算H列中有AM或PM次数的条目数

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