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

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

例如:

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个testinglogging中,它有两秒钟的滞后。

 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. 我假设你的数据永远不会以“)”结尾,除非它已经被索引。 如果情况并非如此,请远离此代码!