Search code examples
vbanumbersunique

VBA - generating unique numbers in code


Is there any way in which I can generate a unique number in code ? I had an idea of using system time for that, but eventually could not implement it.


Solution

  • You can use the Now() then format the output to a number:

    Sub unique()    
        Dim t As Date
        t = Now()
        Range("A1").NumberFormat = "@"
        Range("A1") = CStr(Format(t, "yyyymmddhhMMss"))
    End Sub
    

    This would be unique.

    As @Vasily pointed out, without formatting the cell as string and placing the number as a sting the value gets truncated to scientific notation.