我想自动重命名具有相同值的单元格。例如,在我选择的区域中,有3个单元格带有"stackoverflow“。所需的输出将是选择这些单元格,然后将文本更改为如下所示
stackoverflow_1 stackoverflow_2 stackoverflor_3
我已经完成了重命名部分,但我遇到的问题是如何在区域中选择相似的单元格。这是我到目前为止所拥有的。希望我能为此创建一个for循环或do while循环。
Sub rename()
num = WorksheetFunction.CountA(Selection)
Do While num <> 0
With Selection
.Cells(num, 1).Value = Selection.Cells(num, 1) & "_" & num
End With
num = num - 1
Loop
End Sub
发布于 2019-12-17 14:52:36
这里有一种方法:
Dim dict As Object, c As Range
Set dict = CreateObject("scripting.dictionary")
For Each c in Selection.Cells
v = c.Value
If Len(v) > 0 Then
'Is count > 1 or was it >1 at some point?
If dict.Exists(v) Or Application.CountIf(Selection, v) > 1 Then
dict(v) = dict(v) + 1
c.Value = v & "_" & dict(v)
End If
End If
Next c
发布于 2019-12-17 14:50:21
除非您特别想使用VBA,否则不需要VBA。使用下面的公式
=IF(AND(COUNTIF($A$1:A1,A1)=1,A1<>A2),A1,A1&COUNTIF($A$1:A1,A1))
确保数据已排序。
无需排序,您可以使用此公式(Courtsey @JvdV)
=IF(COUNTIF($A$1:$A$17,A1)=1,A1,A1&"_"&COUNTIF($A$1:A1,A1))
https://stackoverflow.com/questions/59368645
复制相似问题