Random String generator throwing out duplicates issue

JumboCactuar

Well-known Member
Joined
Nov 16, 2016
Messages
788
Office Version
  1. 365
Platform
  1. Windows
Hi,
i'm using this code to generate a unique 4 character string, but hours later i'm seeing it generate the same 4 character strings again

Am i doing something wrong?

VBA Code:
Function GenerateRandomString() As String
    Dim i As Integer
    Dim strResult As String
    Dim strChars As String
    strChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"

    ' Initialize the random-number generator.
    Randomize

    For i = 1 To 4
        strResult = strResult & Mid(strChars, Int((Len(strChars) * Rnd) + 1), 1)
    Next i

    GenerateRandomString = strResult
End Function
 
This raises the question of how the function is called. Is OP calling it as a UDF from a cell, or calling it from other code?
 
Upvote 0

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
Hi
Thanks for all the info

I am calling the function from a button which basically uses

VBA Code:
Private Sub CommandButton1_Click()

    Dim randomString As String
    
    randomString = GenerateRandomString()
    
    aFilename  = Format(Date, "YYYYMMDD") & randomString
    
    'Code to save file below
    
End Sub
So as per suggestions above, i shoam better calling Ramdomize under a Workbook_Open sub ?
 
Upvote 0
Yes. Call Randomize under Workbook_Open. Its duration will be the entire VBA session, until you close the workbook, or reset VBA (such as ending execution after an error is raised, or pressing the "Reset" button on the VBA IDE toolbar).
 
Upvote 0

Forum statistics

Threads
1,224,885
Messages
6,181,586
Members
453,055
Latest member
cope7895

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top