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

标签 excel duplicate-data

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

A1 2332

A2 2333

A3 2334

A4 2334


成为:

A1 2332

A2 2333

A3 2334(1)

A4 2334(2)

最佳答案

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

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

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

对于大型工作簿,我会考虑使用 VBA Worksheet_Change 事件来编辑适当的值。此代码应插入适当的工作表模块中。在 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

当心我做了几个重要的假设:
  • 我假设您要索引的列从 A1 开始。如果它在另一列中,则需要调整代码的第 7 行。
  • 我假设您的数据永远不会以“)”结尾,除非它之前已被索引。如果不是这种情况,请远离此代码!
  • 关于Excel 格式化重复值 - 更改单元格中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532973/

    相关文章:

    java - 删除文件中的重复数据

    android - 从搜索结果中复制来自自定义数组适配器的 View

    vba - 如何告诉 Excel/VBA 清除安全凭证?

    excel - VBA - 将 "=>"作为字符串写入单元格

    excel - 我的 Excel 2007 宏 - 参数不可选是什么意思?

    excel - 将选择设置为范围

    excel - 如何使用表中不同行的值运行 Excel 宏?

    mysql - 如果存在,MySQL 中的重复行

    sql - 如何比较两个表并删除SQL中的重复行?

    sql - 使用 Clustered ColumnStore Index 插入唯一值