mardi 27 juillet 2021

Trying to generate random numbers in VBA, code returning only values that already exist in the table

I cannot get what this is doing.

For a data entry work, I need to generate a transaction number for each entry.

I have a simple function that returns a string created from a random number:

Public Function GetNewTnum() As String

    Randomize 10
    GetNewTnum = "SL-" & Int(Rnd * 1000000)

End Function

When I call the function in the sub, not only is it generating the same number everytime it runs, the number can already be found in the data set, which only has 577 entries at the moment!

In the sub, after generating the string, it checks to see if has already been used and another function returns true/false. A loop keeps testing until the generated string has not been found and uses this in the entry:

Public Function finddupTnum(ByRef num As String) As Boolean
    
    Dim f As Range
    Set f = inputws.Range("tblDataMaster[Tnum]").Find(num, , xlValues, xlWhole)
    If f Is Nothing Then
        finddupTnum = False
    ElseIf Not f Is Nothing Then
        finddupTnum = True
    End If

End Function

Loop structure works fine. And even before the code reaches the loop, the first random number that gets generated is as described above:

Dim i As Integer
    For i = 1 To 7
        If Not Me.Controls("Product" & i) = "" Then
            With newrow
                newtnum = GetNewTnum()
                MsgBox "First tnum: " & newtnum
                valb = finddupTnum(newtnum)
                MsgBox "Found? " & valb
                Do While valb = True
                    newtnum = GetNewTnum()
                    valb = finddupTnum(newtnum)
                    MsgBox "New tnum: " & newtnum
                    MsgBox "New tnum dound? " & valb
                Loop

The loop can't end because all the values generated already exist.

Thank you for your help!




Aucun commentaire:

Enregistrer un commentaire