关于功能:日期之间的Excel VBA Countif

Excel VBA Countif between dates

我需要创建一个函数来计算两个日期之间帐号的出现。 第一个日期基于功能输入,第二个日期提前3个月(日期可能不包含在数据集中)。 范围内的日期值格式为" dd / mm / yyyy h:mm"。 由于数据集的大小,我想在代码中执行大约150,000行,而不是在指定的单元格内粘贴或评估COUNTIF公式。

当仅引用AccountNo变量而不添加条件"> ="或" <=" Date变量时,工作表函数才起作用

例如 Application.WorksheetFunction.CountIfs(Range(" L2:L"&Endrow,AccountNo)> 1然后''''(Works

该函数需要根据以下countif结果返回结果。

谢谢,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function LastWrapUp(Date1 As Date, AccountNo)

Dim Date2 As Date
Dim Endrow As Long

Date2 = DateAdd("M", 3, Date1)
Endrow = Range("A" & Rows.Count).End(xlUp).Row

If Application.WorksheetFunction.CountIfs(Range("A2:A17643"),">=" & Date1, Range("A2:A" & Endrow),"<" & Date2, Range("L2:L" & Endrow), AccountNo) > 1 Then
    LastWrapUp ="Not Final Wrap Up"
ElseIf Application.WorksheetFunction.CountIfs(Range("A2:A" & Endrow),">=" & Date1, Range("A2:A" & Endrow),"<" & Date2, Range("L2:L" & Endrow), AccountNo) = 1 Then
    LastWrapUp ="Yes"
Else
    LastWrapUp ="Error"
End If

Debug.Print LastWrapUp

End Function

对于那些可能对此感兴趣的人,解决方案是在Date1和Date 2变量周围添加Cdbl和Cdate函数(为清晰起见,已更改为Newdate和AccountDate变量,如下所示)。 奇迹般有效。 在VBA中使用日期格式可能会很麻烦!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function LastWrapUp(AccountID, AccountType, AccountDate As Date)

'Find if current WrapUp is the last for a given account number within a 3 month period.
'need to include reference to specific sheets

Dim NewDate As Date
Dim LastRow As Long

NewDate = DateAdd("M", 3, AccountDate)

LastRow = Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("A" & Rows.Count).End(xlUp).Row

If AccountType ="Dummy ID" Then
    LastWrapUp ="Dummy ID"
ElseIf Application.WorksheetFunction.CountIfs(Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("A2:A" & LastRow),">=" & CDbl(CDate(AccountDate)), Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("A2:A" & LastRow),"<" & CDbl(CDate(NewDate)), Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("L2:L" & LastRow), AccountID) > 1 Then
    LastWrapUp ="Not Final Wrap Up"
ElseIf Application.WorksheetFunction.CountIfs(Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("A2:A" & LastRow),">=" & CDbl(CDate(AccountDate)), Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("A2:A" & LastRow),"<" & CDbl(CDate(NewDate)), Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range("L2:L" & LastRow), AccountID) = 1 Then
    LastWrapUp = Workbooks("Interim Referrals Report.xlsm").Worksheets("SA Wrap Up Data").Range(AccountID.Address).Offset(0, -4)
Else
    LastWrapUp ="Error"
End If

End Function