VBA根据条件计算不同的日期

时间:2018-07-10 13:45:42

标签: excel-vba

我目前正在使用此公式来计算R列中每个用户的唯一日期数

=SUM(IF(Q1=$J$2:$J$39115, 1/(COUNTIFS($J$2:$J$39115, Q1, $H$2:$H$39115, $H$2:$H$39115)), 0))

此公式有效,但由于必须处理大量的行,因此需要花费很多时间来计算。我确信必须使用宏或vba更快。

J列包含用户列表(用户出现多次),H列包含日期。

我需要计算Q列中每个用户的工作天数。(Q列包含唯一的用户列表。

1 个答案:

答案 0 :(得分:0)

将以下内容添加到VBA模块中:

Public Function count_distinct(user As Range, userlist As Range, datelist As Range) As Long
    Dim i As Long, j As Long, dates() As Variant, found As Boolean, this_date As Variant
    Dim varUL As Variant, varDL As Variant, unique_count As Long

    varUL = userlist.Value
    varDL = datelist.Value
    ReDim dates(0 To 0)

    For i = 1 To UBound(varUL, 1)
        If varUL(i, 1) = user Then
            found = False
            this_date = varDL(i, 1)
            For j = 1 To unique_count
                If this_date = dates(j) Then
                    found = True
                    Exit For
                End If
            Next j
            If Not found Then
                unique_count = unique_count + 1
                ReDim Preserve dates(0 To unique_count)
                dates(unique_count) = this_date
            End If
        End If
    Next i
    count_distinct = unique_count
End Function

然后将R列中的公式替换为:=count_distinct(Q1,$J$2:$J$39115,$H$2:$H$39115)

这不是最快的方法,我相信它可以改进,但是可能会给您几分钟的时间!