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

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
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,221,510
Messages
6,160,230
Members
451,632
Latest member
purpleflower26

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