计算唯一值和 return 结果在另一列中

Count unique values and return results in another column

我在 B 列中有值(绿色、蓝色、白色....),我想对它们进行计数,结果必须按以下格式出现在 A 列中(green01、green02、green03.... , blue01, blue02, blue03, blue04...., white01, 白色 02...).

结果必须类似于 this photo

我在网上搜索了宏,但没有找到适合我需要的宏。

谢谢

不需要 VBA,在 A1:

=B1&TEXT(COUNTIF(B:B1,B1),"00")

请尝试下一个代码:

Sub testCountSortColors()
 Dim sh As Worksheet, lastRow As Long, i As Long, c As Long
  Set sh = ActiveSheet
  lastRow = sh.Range("B" & Rows.count).End(xlUp).Row
  sh.Range("B1:B" & lastRow).Sort key1:=sh.Range("B1"), order1:=xlAscending, Header:=xlYes

  For i = 2 To lastRow
    If sh.Range("B" & i).value <> sh.Range("B" & i - 1).value Then
        c = 1
    Else
        c = c + 1
    End If
    sh.Range("A" & i).value = sh.Range("B" & i).value & Format(c, "00")
    sh.Range("A" & i).Font.Color = sh.Range("B" & i).Font.Color
  Next
End Sub

我想你可能有专栏 headers...

唯一计数

调整常量部分中的值。

Option Explicit

Sub countUnique()

    Const SourceColumn As Variant = 2   ' e.g. 2 or "B"
    Const TargetColumn As Variant = 1   ' e.g. 1 or "A"
    Const FirstRow As Long = 1

    Dim rng As Range
    Dim dict As Object
    Dim Key As Variant
    Dim Source As Variant, Target As Variant
    Dim i As Long, UB As Long
    Dim CurrString As String

    Set rng = Columns(SourceColumn).Find(What:="*", _
      LookIn:=xlFormulas, SearchDirection:=xlPrevious)
    If rng Is Nothing Then GoTo exitProcedure
    If rng.Row < FirstRow Then GoTo exitProcedure
    Source = Range(Cells(FirstRow, SourceColumn), rng)
    Set rng = Nothing

    UB = UBound(Source)
    Set dict = CreateObject("Scripting.Dictionary")
    For i = 1 To UB
        If Source(i, 1) <> "" Then
            dict(Source(i, 1)) = dict(Source(i, 1)) + 1
        End If
    Next i

    ReDim Target(1 To UB, 1 To 1)
    For i = UB To 1 Step -1
        CurrString = Source(i, 1)
        If CurrString <> "" Then
            Target(i, 1) = CurrString & Format(dict(CurrString), "00")
            dict(CurrString) = dict(CurrString) - 1
        End If
    Next i

    With Cells(FirstRow, TargetColumn)
        .Resize(Rows.Count - FirstRow + 1).ClearContents
        .Resize(UB) = Target
    End With

    MsgBox "Operation finished successfully."

exitProcedure:

End Sub