Search code examples
randomvb6

vb6 random number no duplicates & no zeros


I am using vb6 and trying to generate a random number or String with this format
S1 = "378125649"

I have three requirements NO Duplicates Values & No Zeros & 9 charcters in length
I have approached This two very different ways the random number generator method is failing the FindAndReplace works but is too much code

The questions are
How to fix the GetNumber method code to meet the three requirement?
OR
How to simplify the FindAndReplace code to reflect a completely new sequence of numbers each time?

GetNumber code Below

Private Sub GetNumber()

Randomize
Dim MyRandomNumber As Long 'The chosen number
Dim RandomMax As Long 'top end of range to pick from
Dim RandomMin As Long 'low end of range to pick from
'Dim Kount As Long 'loop to pick ten random numbers

RandomMin = 1
RandomMax = 999999999

MyRandomNumber = Int(Rnd(1) * RandomMax) + RandomMin
lbOne.AddItem CStr(MyRandomNumber) & vbNewLine
End Sub

The FindAndReplace Code Below

Private Sub FindAndReplace()

    Dim S4 As String
    S4 = "183657429"
    Dim T1 As String
    Dim T2 As String
    Dim J As Integer
    Dim H As Integer
    
    J = InStr(1, S4, 2)
    H = InStr(1, S4, 8)
    T1 = Replace(S4, CStr(J), "X")
    T1 = Replace(T1, CStr(H), "F")


    If Mid(T1, 8, 1) = "F" And Mid(T1, 2, 1) = "X" Then
    T2 = Replace(T1, "F", "8")
    T2 = Replace(T2, "X", "2")
    End If

    tbOne.Text = CStr(J) & " " & CStr(H)
    lbOne.AddItem "Original Value " & S4 & vbNewLine
    lbOne.AddItem "New Value      " & T2 & vbNewLine
End Sub

Solution

  • I don't have a VB6 compiler, so I winged it:

    Function GetNumber(lowerLimit as Integer, upperLimit As Integer) As Integer
        Dim randomNumber As String
        Dim numbers As New Collection
            
        Randomize
    
        For i As Integer = lowerLimit To upperLimit
            Call numbers.Add(i)
        Next
    
        For j As Integer = upperLimit To lowerLimit Step -1
            Dim position As Short = Int(((j - lowerLimit)* Rnd) + 1)
    
            randomNumber = randomNumber & numbers(position)
             
            Call numbers.Remove(position)
        Next
            
        Return(CInt(randomNumber))
    End Function
    

    Use that function by calling for example:

    GetNumber(1, 9)