如果在列中找到重复的单元格值,则返回值

时间:2015-05-27 20:20:32

标签: excel if-statement indexing match countif

我需要跟踪数据表中的某个人,以确定该人移动到哪个位置。

如果一个人在J列中出现的次数超过一次,则表示此人已更改位置,且位置值在L列中。为此,我有以下代码:

=IF(J18=J19;IF(COUNTIF(J:J;J18)>1; "From "&L18 &" to "& IF(J18=J19;L19;"");"");"")

问题是如果此人将位置更改两次以上。在第O列到第AA栏我有一年中的几个月决定了这个人的位置。

如何修改此代码以执行上述操作:

=IF(J18=J19;IF(COUNTIF(J:J;J18)>1; "From "&L18 &" to "& IF(J18=J19;L19;"");"");"")

Example

1 个答案:

答案 0 :(得分:3)

这是一个用户定义函数(又名UDF)来完成任务。

Function my_Travels(nm As Range, loc As Range, cal As Range)
    Dim n As Long, cnt As Long, v As Long, vLOCs As Variant, vTMPs As Variant
    Dim iLOC As Long, sTMP As String

    my_Travels = vbNullString   '"no travels"
    cnt = Application.CountIf(nm.EntireColumn, nm(1))

    If Application.CountIf(nm, nm(1)) = cnt And cnt > 1 Then
        Set loc = loc.Rows(1).Resize(nm.Rows.Count, loc.Columns.Count)
        Set cal = cal.Rows(1).Resize(nm.Rows.Count, cal.Columns.Count)

        'seed the array
        ReDim vLOCs(1 To cnt, 1 To cnt)
        For v = LBound(vLOCs, 1) To UBound(vLOCs, 1)
            vLOCs(v, 1) = cal.Columns.Count + 1
            vLOCs(v, 2) = cal.Columns.Count + 1
        Next v

        'collect the values into the array
        For n = 1 To nm.Rows.Count
            If nm.Cells(n, 1).Value2 = nm.Cells(1, 1).Value2 Then
                iLOC = Application.Match(1, Application.Index(cal, n, 0), 0)
                For v = LBound(vLOCs, 1) To UBound(vLOCs, 1)
                    If vLOCs(v, 1) = cal.Columns.Count + 1 Then
                        vLOCs(v, 1) = iLOC
                        vLOCs(v, 2) = n
                        Exit For
                    End If
                Next v
            End If
        Next n

        'sort the values in the array
        For v = LBound(vLOCs, 1) To (UBound(vLOCs, 1) - 1)
            For n = (v + 1) To UBound(vLOCs, 1)
                If vLOCs(v, 1) > vLOCs(n, 1) Then
                    vTMPs = Array(vLOCs(v, 1), vLOCs(v, 2))
                    vLOCs(v, 1) = vLOCs(n, 1)
                    vLOCs(v, 2) = vLOCs(n, 2)
                    vLOCs(n, 1) = vTMPs(0)
                    vLOCs(n, 2) = vTMPs(1)
                    Exit For
                End If
            Next n
        Next v

        'concatenate the locations from the array
        For v = LBound(vLOCs) To (UBound(vLOCs) - 1)
            sTMP = sTMP & "From " & loc.Cells(vLOCs(v, 2), 1) & " to " & loc.Cells(vLOCs(v + 1, 2), 1) & "; "
        Next v

        'truncate the string and return it
        sTMP = Left(sTMP, Len(sTMP) - 2)
        my_Travels = sTMP

    End If

End Function

位置日历单元格只需要由第一行定义。每个都重新定义了它的高度(即),以保持与名称列表的一致性。

Concatenate Locations

在AB2中(如上所述)公式为

=my_Travels(J2:J$8, L2, O2:AA2)

根据需要填写。