2016-08-24 6 views
1

私は数字のリスト(50,000+)を持っており、各固有のグループの最後にIDを追加する必要があります。 Idは " - ###"の形式です。数字のリストに一意のIDを追加する - VBA

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で一意の値を数えることができれば、それで解決できると思います。

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 

おかげですべてを:それは現在表示されているものを

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 

これ!

答えて

4

私はあなたに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 

これは効果的に上記の式と同じです。

+0

++ VBAを書く必要がありますか? :) – cyboashu

+2

@cyboashuなぜ車を改造するのですか? –

+0

素晴らしいです、完璧に働きました。 VBAに切り替える前に同様の式を試しましたが、何らかの理由で正しく動作しませんでした。乾杯! –

関連する問題