如何使用COUNTIFS VBA函数对两个日期之间的值进行计数?

时间:2019-07-20 00:59:43

标签: excel vba

我想使用VBA来计算一个值在两个给定日期之间出现的次数。输出应显示1。

我正在使用以下代码,但似乎无法获取正确的值。

Sub clientIntAnalysis()
Dim r As Integer
Dim startdate As Date, endDate As Date
startdate = "07/01/2019"
endDate = "07/30/2019"
    Dim LastCol As Long, LastRow As Long, rng As Range, rng2 As Range

    LastRow = Sheet3.Range("M" & Sheet3.Rows.Count).End(xlUp).Row
    LastCol = Sheet3.Cells(8, Columns.Count).End(xlToLeft).Column

    With Sheet3
        Set rng = .Range(.Cells(8, 14), .Cells(LastRow, LastCol))
        Set rng2 = .Range(.Cells(8, 13), .Cells(LastRow, LastCol))
    End With

    r = Application.WorksheetFunction.CountIfs(rng, ">=" & startdate, rng, "<=" & endDate, rng, "=" & "Client Interested") 'q3

    MsgBox r


End Sub

enter image description here

2 个答案:

答案 0 :(得分:1)

使用此代码(未经测试)

现在您的范围与您在评论中说的一样:

Sub clientIntAnalysis()

Dim r As Integer
Dim startdate As Date, endDate As Date
startdate = "07/01/2019"
endDate = "07/30/2019"


    Dim LastCol As Long, LastRow As Long, rng As Range, rng2 As Range

    LastRow = Sheet3.Range("M" & Sheet3.Rows.Count).End(xlUp).Row
    'LastCol = Sheet3.Cells(8, Columns.Count).End(xlToLeft).Column

    With Sheet3
        Set rng = .Range(.Cells(8, 13), .Cells(LastRow, 14))
        Set rng2 = .Range(.Cells(8, 14), .Cells(LastRow, 15))
    End With

    r = Application.WorksheetFunction.CountIfs(rng, ">=" & startdate, rng, "<=" & endDate, rng2, "=" & "Client Interested") 'q32

    MsgBox r


End Sub

评论:=COUNTIFS(clientmenu!$M$8:$N$8,">="&"07/01/2019",clientmenu!$M$8:$N$8,"<="&"07/30/2019",clientmenu!$N$8:$O$8,"Client Interested")

答案 1 :(得分:0)

这是我的代码的有效版本,看起来我不得不将最后一列的值增加1。

Sub clientIntAnalysis()

Dim LastCol As Long, LastRow As Long, rng As Range, rang2 As Range, lastcol2 As Long, r as long

startdate = "07/01/2019"
enddate = "07/30/2019"
LastRow = Sheet3.Range("M" & Sheet3.Rows.Count).End(xlUp).Row
LastCol = Sheet3.Cells(8, Columns.Count).End(xlToLeft).Column
lastcol2 = Sheet3.Cells(8, Columns.Count).End(xlToLeft).Column + 1

Set rang2 = Sheet3.Range(Sheet3.Cells(8, 14), Sheet3.Cells(lastrow, lastcol2))
    With Sheet3
        Set rng = .Range(.Cells(8, 13), .Cells(LastRow, LastCol))
End With

r= Application.WorksheetFunction.CountIfs(rng, ">=" & startdate, rng, "<=" & enddate, rang2, "Client Interested") 'q3

    MsgBox r


End Sub