使用“条件格式”很容易格式化具有重复值的单元格(例如在它们上设置特定背景或其他样式),但是如何更改它们的文本?
例如:
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
当心我做了几个重要的假设:
关于Excel 格式化重复值 - 更改单元格中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532973/