使随机生成器创建唯一序列

时间:2014-03-31 02:21:11

标签: vba excel-vba excel

这个随机生成器运行良好,但随机序列不是Unique

我需要所有序列unique,有人可以看到如何做到这一点

由于

Sub RanSerialGenerator()
Dim rng As Range
Dim LastRow As Long

With Sheets(')
    LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
End With

Range("A1").FormulaR1C1 = "Header Name"
Range("A2", Range("A2").End(xlDown)).Clear

   For Each rng In Sheets(1).Range("E2:E" & LastRow)

    rng.Value = Pwd(rng.Value)
Next

End Sub


Function Pwd(ByVal strTemp As String) As String

Dim i As Integer, iTemp As Integer, bOK As Boolean, iLength As Integer

'48-57 = 0 To 9, 65-90 = A To Z, 97-122 = a To z
'amend For other characters If required

'Set the # of characters
For i = 1 To 3
    Do
    ' Initialize the seed using Timer.
     Randomize (Timer)

        iTemp = Int((122 - 48 + 1) * Rnd + 48)
        Select Case iTemp
        Case 65 To 90, 97 To 122: bOK = True
        Case Else: bOK = False
        End Select
    Loop Until bOK = True
    bOK = False
    strTemp = strTemp & Chr(iTemp)

Next i
Pwd = strTemp
End Function

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub RanSerialGenerator()
    Dim rng As Range
    Dim LastRow As Long
    Dim p As String
    With Sheets("Sheet1")
        LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    End With

    Range("A1").FormulaR1C1 = "Header Name"
    Range("A2:A" & Rows.Count).Clear

    For Each rng In Sheets(1).Range("E2:E" & LastRow)
        Do
            p = Pwd(rng.Value)
        Loop Until IsError(Application.Match(p, Sheets(1).Range("E1:E" & rng.Row), 0))
        rng.Value = p
    Next

End Sub

还不清楚应该Range("A1")属于哪个表格?也许最好明确使用表格:Sheets("Sheet1").Range("A1")...