Techblog

Technical Blog about all things computer

  • Jan 17

    The function below will enable you to generate Aphabets and Numbers randomly.

    1.) Randomize() initializes the random generator and should be placed when your code starts up to ensure that you are getting a random value every time your program starts up.

            ‘Initialize the random # generator.
            Randomize()

    2.) The function below is the random alpha numeric generator. It’ll take length as an input with option if you want letters capitalized or not.

    Public Function GenerateRandomString(ByRef lenStr As Integer, Optional ByVal upper As Boolean = False) As String
    ‘use
    Dim rand As New Random()
    Dim allowableChars() As Char = _
    “abcdefghighlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”.ToCharArray()
    Dim final As New System.Text.StringBuilder
    Do
    final.Append(allowableChars(Rnd_Numeric(0, allowableChars.Length – 1)))
    Loop Until final.Length = lenStr
    Return If(upper, final.ToString.ToUpper(), final.ToString)
    End Function

    3.) How to use this code:
    This is an example of how to use the Visual Basic Random Generator function if you want letters to be all capitalized.

    Dim Random_String As String = GenerateRandomString(10, true)

    This is an example of how to use the Visual Basic Random Generator function if you don’t need letters capitalized.

    Dim Random_String As String = GenerateRandomString(10)

    Hope this was helpful and happy coding!