vba Worksheetfunction.countifs - 不识别日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25349909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:15:56  来源:igfitidea点击:

Worksheetfunction.countifs - doesn't recognise dates?

excelvbaexcel-vbaworksheet-functioncountif

提问by Harley B

As part of a larger project I'm trying to get a count of the instances of dates between a search range.

作为一个更大项目的一部分,我试图计算搜索范围之间的日期实例数。

So for example my date range is 02/01/2014to 04/01/2014and in my search range the date 02/01/2014appears 4 times, 03/01/2014appears 3 times and 04/01/2014appears 3 times then the count would return a value of 10.

例如,我的日期范围是02/01/201404/01/2014并且在我的搜索范围内,日期02/01/2014出现了 4 次,03/01/2014出现了 3 次,04/01/2014出现了 3 次,然后计数将返回 10 的值。

I can get this to work with numbers - so similarly assuming my search range is 2 to 4 and in my search range 2 appears 4 times, 3 appears 3 times and 4 appears 3 times then the count does return 10. But when I do exactly the same with dates then the count returns 0.

我可以让它与数字一起工作 - 所以同样假设我的搜索范围是 2 到 4 并且在我的搜索范围内 2 出现 4 次,3 出现 3 次,4 出现 3 次然后计数确实返回 10。但是当我完全这样做时与日期相同,则计数返回 0。

So here's the 2 test codes - I have numbers in column A and dates in column B

所以这是 2 个测试代码 - 我在 A 列中有数字,在 B 列中有日期

Sub testnumbers()
Dim Val As Double
    Val = Application.WorksheetFunction.CountIfs(Range("A:A"), ">=2", Range("A:A"), "<=4")
MsgBox Val

End Sub

Returns the correct count in Val. While

返回 中的正确计数Val。尽管

Sub testdates()
Dim Val As Double
    Val = Application.WorksheetFunction.CountIfs(Range("B:B"), ">=02/01/2014", Range("B:B"), "<=04/01/2014")
MsgBox Val

End Sub

returns a value of 0 to Valas if it hasn't found any instances of any dates in the range.

返回 0 值,就Val好像它没有找到范围内任何日期的任何实例一样。

Can anyone see where I'm going wrong? It just doesn't seem to see the dates properly...

谁能看到我哪里出错了?它似乎没有正确地看到日期......

Any help much appreciated.

非常感谢任何帮助。

采纳答案by Gary's Student

Try this:

尝试这个:

Sub testdates()
    Dim Val As Double, wf As WorksheetFunction, r As Range, _
        d1 As Date, d2 As Date

    Set wf = Application.WorksheetFunction
    Set r = Range("B:B")
    d1 = DateValue("2/1/2014")
    d2 = DateValue("4/1/2014")

    Val = wf.CountIfs(r, ">=" & d1, r, "<=" & d2)
    MsgBox Val
End Sub