【问题标题】:Add unique Id to list of numbers - VBA将唯一 ID 添加到数字列表 - VBA
【发布时间】:2017-01-01 00:20:29
【问题描述】:

我有一个数字列表(50,000+),我需要在每个唯一组的末尾添加一个 ID。 Id 的格式为“-###”。

151022
151022
151020
150922
150715
150911
151014
151021
151020
151019
151019
151019
151020

我需要它像这样打印

151022-001
151022-002
151020-001
150922-001
150715-001
150911-001
151014-001
151021-001
151020-002
151019-001
151019-002
151019-003
151020-002

我目前有这段代码,我发现并稍作修改。如果我能让它在 -002 开始计算唯一值,那么我相信这会解决它。

Option Explicit

Sub test()
    Dim uniqueCounter As New Scripting.Dictionary
    Dim counter As Long
    Dim rowCount As Long
    Dim identifer As String


    rowCount = ActiveCell.CurrentRegion.Rows.Count 'Whatever code you want to put in to calculate the last row

    For counter = 1 To rowCount
        identifer = Sheet1.Cells(counter, 1) 'Put whatever number of combination of cells which the row unique here (maybe it's just the one)
        If uniqueCounter.Exists(identifer) Then
            uniqueCounter(identifer) = CLng(uniqueCounter(CStr(Sheet1.Cells(counter, 1)))) + 1
            Sheet1.Cells(counter, 2) = identifer & "-00" & uniqueCounter(CStr(Sheet1.Cells(counter, 1)))
        Else
            uniqueCounter.Add identifer, "0"
            Sheet1.Cells(counter, 2) = identifer
        End If
    Next counter

End Sub

这是它当前显示的内容:

151022  151022
151022  151022-001
151020  151020
150922  150922
150715  150715
150911  150911
151014  151014
151021  151021
151020  151020-001
151019  151019
151019  151019-001
151019  151019-002
151020  151020-002

谢谢大家!

【问题讨论】:

    标签: vba excel loops excel-formula


    【解决方案1】:

    我知道您要求使用 vba,但一个简单的公式将为您提供所需的输出。

    在B1放:

    =A1& "-" &TEXT(COUNTIF($A$1:A1,A1),"000")
    

    并复制数据的范围。


    如果你想在 vba 中使用它;我会这样做:

    Sub test2()
        Dim rng As Range
        Dim rngcnt As Range
        Dim firstrow As Long
        Dim lastrow As Long
        Dim columnNumber As Long
        Dim ws As Worksheet
    
        Set ws = Worksheets("Sheet15") 'change to your sheet
        firstrow = 1 'change to your first row of data
        columnNumber = 1 'change to the column number
    
        With ws
            lastrow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
            For i = firstrow To lastrow
                .Cells(i, columnNumber + 1) = .Cells(i, columnNumber) & "-" & Format(Application.WorksheetFunction.CountIf(.Range(.Cells(firstrow, columnNumber), .Cells(i, columnNumber)), .Cells(i, columnNumber)), "000")
            Next i
        End With
    
    End Sub
    

    这实际上与上述公式相同。

    【讨论】:

    • ++ 你是否需要编写 VBA。 :)
    • @cyboashu 为什么要重新发明轮子?
    • 太棒了,完美运行。在转向 VBA 之前,我尝试了一个类似的公式,但由于某种原因无法正常工作。干杯!
    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多