我需要创建一个函数来计算两个日期之间帐号的出现次数。第一个日期基于功能输入,第二个日期是提前3个月(日期可能不包含在数据集中)。范围中的日期值的格式为“dd / mm / yyyy h:mm”。由于数据集的大小约150,000行,我想在代码中执行此操作,而不是粘贴或评估指定单元格中的COUNTIF公式。
当仅引用AccountNo变量时,工作表函数有效,但当添加条件“> =”或“< =”Date变量时,工作表函数不起作用
e.g。 Application.WorksheetFunction.CountIfs(Range(“L2:L”& Endrow),AccountNo)> 1然后''''(作品)
该函数需要根据countif结果返回结果,如下所示。
谢谢,
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
答案 0 :(得分:4)
对于那些可能遇到此问题且感兴趣的人,解决方案是在Date1和Date 2变量周围添加Cdbl和Cdate函数(为了清楚起见,更改为Newdate和AccountDate变量,如下所示)。奇迹般有效。在VBA中使用日期格式可能很痛苦!
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