Excel格式重复值 - 更改单元格中的文本

时间:2012-03-02 12:03:11

标签: excel duplicate-data

使用“条件格式”格式化具有重复值的单元格(如设置特定背景或其他样式)非常容易,但如何更改其文本?

例如:

  

A1 2332

     

A2 2333

     

A3 2334

     

A4 2334

成为:

  

A1 2332

     

A2 2333

     

A3 2334(1)

     

A4 2334(2)

1 个答案:

答案 0 :(得分:4)

执行此操作的一种方法是在原始数据旁边添加第二列,并填写以下公式:

=IF(COUNTIF($A$1:$A$5000,A1)>1,A1& " (" & COUNTIF(A$1:A1,A1) & ")",A1)

您的原始数据位于A1:A5000中。请注意COUNTIF非常低效,因此如果您有大量数据,这可能需要一段时间来计算并影响您的工作簿性能。

对于大型工作簿,我会考虑使用VBA Worksheet_Change事件来编辑适当的值。此代码应插入相应的Worksheet模块中。在5000个测试记录中,它有几秒滞后。

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

Dim dataRng As Range
Dim dataArr() As Variant, output() As String
Dim y As Long, i As Long, j As Long, tmpcount As Long

'Change "A1" to address of start of column you want to index.
Set dataRng = Range("A1").Resize(Me.UsedRange.Rows.Count, 1)
If Not Intersect(Target, dataRng) Is Nothing Then
    dataArr = dataRng.Value
    ReDim output(1 To UBound(dataArr, 1), 1 To 1)
    'Strip old counts from data once in array.
    For y = 1 To UBound(dataArr, 1)
        If Right(dataArr(y, 1), 1) = ")" Then
            dataArr(y, 1) = Left(dataArr(y, 1), InStr(dataArr(y, 1), " (") - 1)
        End If
    Next y

    For i = 1 To UBound(dataArr, 1)
        tmpcount = 0
        output(i, 1) = dataArr(i, 1)
        For j = 1 To UBound(dataArr, 1)
            If dataArr(i, 1) = dataArr(j, 1) Then
                tmpcount = tmpcount + 1
                If j = i And tmpcount > 1 Then
                    output(i, 1) = dataArr(i, 1) & " (" & tmpcount & ")"
                    Exit For
                End If
                If j > i And tmpcount > 1 Then
                    output(i, 1) = dataArr(i, 1) & " (" & tmpcount - 1 & ")"
                    Exit For
                End If
            End If
        Next j
    Next i
    Call printoutput(output, dataRng)
End If

End Sub


Private Sub printoutput(what As Variant, where As Range)
Application.EnableEvents = False
where.Value = what
Application.EnableEvents = True
End Sub

小心我做了几个很大的假设:

  1. 我假设您要索引的列从A1开始。如果它在另一列中,则需要调整代码的第7行。
  2. 我认为您的数据永远不会以“)”结尾,除非之前已被编入索引。如果情况并非如此,请远离此代码!
相关问题