Excel VBA计算日期范围内的Countif

4
我需要创建一个函数来计算在两个日期之间帐户号出现的次数。第一个日期是基于函数输入的,第二个日期是三个月后(日期可能不包含在数据集中)。范围内的日期值格式为“dd/mm/yyyy h:mm”。由于数据集大小约为150,000行,我想在代码中执行此操作,而不是将COUNTIF公式粘贴或评估到指定单元格中。
当仅引用AccountNo变量时,工作表函数可以正常工作,但是当添加条件“> =”或“< =” Date变量时,则无法正常工作。
例如:Application.WorksheetFunction.CountIfs(Range("L2:L" & Endrow), AccountNo)> 1 Then''''(可行)
该函数需要根据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
1个回答

7

对于那些可能会遇到此问题并感兴趣的人,解决方案是在Date1和Date2变量(按下面的说明更改为Newdate和AccountDate变量以明确)周围添加Cdbl和Cdate函数。效果很棒。在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

如果是 CDbl 起了作用,那么我有一个解释:匹配函数将事物与单元格值的内部表示 Value2 进行比较,而不是 Value - ivan_pozdeev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接