【问题标题】:Using CountIf function in VBA to count number of entries with a specific Month and Year (ignoring Day)在 VBA 中使用 CountIf 函数计算具有特定月份和年份的条目数(忽略日期)
【发布时间】:2015-07-23 07:01:50
【问题描述】:

我是 VBA 的新手。使用 Excel 2007 VBA,我正在尝试计算“WOMade”工作表的“H”列中具有特定月份和年份的日期(忽略日期)的条目数,但我有的所有方法试过了还是不行。

在其他想法中,我尝试过:

WorksheetFunction.CountIf(Sheets("WOMade").Columns("H:H"), "June-15")

WorksheetFunction.CountIf(Format(Sheets("WOMade").Columns("H:H"), "mmyyyy"), "062015")

WorksheetFunction.CountIf(Sheets("WOMade").Columns("H:H"), "June/" & "/2015)

WorksheetFunction.CountIfs(Sheets("WOMade").Columns("H:H"), ">=" 6/1/2015, Sheets("WOMade").Columns("H:H"), < 7/1/2015)

有什么想法吗?

【问题讨论】:

    标签: vba excel countif


    【解决方案1】:

    我认为最后一个例子是最接近的。

    dim i as long
    with Sheets("WOMade")
        i = WorksheetFunction.CountIfs(.Columns("H:H"), ">="  & dateserial(2015, 6, 1), .Columns("H:H"), "<" & dateserial(2015, 7, 1))
        'or,
        i = WorksheetFunction.CountIfs(.Columns("H:H"), ">="  & datevalue("6/1/2015"), .Columns("H:H"), "<" & datevalue("7/1/2015"))
        'or,
        i = WorksheetFunction.CountIfs(.Columns("H:H"), ">=6/1/2015", .Columns("H:H"), "<7/1/2015")
    end with
    

    【讨论】:

    • 看起来有效!感谢您的迅速、有效的回应。出于好奇,使用 With/End With 而不是仅将 Sheets("WOMade") 放在 .Columns 之前有什么特别的优势吗?
    • 使用With ... End With statement 可以减少代码。您的公式必须在一个公式中至少使用两次Sheets("WOMade"),并且可能在其他时间用于涉及使用工作表函数返回的值的命令。这也使得忘记明确定义亲子关系变得更加困难。
    【解决方案2】:

    子测试() Sheets("WOMade").选择

        SetYear = 2015
        SetMonth = 1
        Count = 0
    
        i = 1
        Do While Cells(i, 8) <> ""
            ' Subtract for TRUE as it is stored as -1
            Count = Count - (Year(Cells(i, 8)) = SetYear And Month(Cells(i, 8)) = SetMonth)
    
            i = i + 1
        Loop
    
        MsgBox Count
    

    结束子

    【讨论】:

    • 这不是计算 2015 年 7 月的所有日期以及 2015 年 6 月的日期吗? OP 表示他想返回一个计数'具有特定月份和年份的日期'
    • 只需删除 ">=" 并替换为 "="
    【解决方案3】:
    Public Function CountOfYearMonth(r As Range, y As Integer, m As Integer) As Long
    
        Set r = Intersect(r, r.Parent.UsedRange) 'Don't iterate over more than you have to
    
        'Technically n is not necessary, you can just use CountOfYearMonth
        Dim n As Long, _
            c As Range, _
            d As Date
    
        For Each c In r.Cells        
            If IsDate(c.Value) Then 'Does the cell contain a date?
                d = CDate(c.Value) 'Convert, if so
                If month(d) = m And year(d) = y Then 'Check year and month
                    n = n + 1 'If match, increment total
                End If
            End If
        Next c
    
        CountOfYearMonth = n 'Assign return value
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-04
      • 2014-11-07
      • 2015-06-20
      • 1970-01-01
      • 2013-02-15
      • 2022-01-19
      • 2017-01-19
      • 1970-01-01
      相关资源
      最近更新 更多