Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Generating Random Strings of Characters.

Generating Random Strings of Characters

by Allen Wyatt
(last updated May 12, 2012)

7

Nancy is trying to get Excel to pick 50 "numbers" that each contain eight random characters. The characters can be either digits or letters (uppercase or lowercase).

If your random numbers were to really be numbers (digits only), then generating them would be easy. All you would need to do is use the RANDBETWEEN function (in the Analysis ToolPak) in this manner:

=RANDBETWEEN(10000000,99999999)

This is not what Nancy wants, however. Her random "numbers" can contain upper- and lowercase letters, as well. This becomes a bit stickier. There are, however, several approaches you can use.

One approach is to put all your possible characters into an individual cell, such as B7:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Name this cell something snazzy, such as MySource. You could then use a formula such as the following to return the random string of characters:

=MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)
& MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)

The formula is long; it has been broken into individual lines for clarity, but it is still a single formula. It concatenates eight characters pulled from the source you entered into cell B7.

Another approach is to create a table that contains all the characters you would want in your random text string. Start by placing the numbers 1 through 62 in a column, one number in each row. To the left of these numbers place your characters—A, B, C, D, etc. (This should be the same characters you placed in cell B7 in the previous technique.) Select both columns of the 62 rows and give it a name, such as MyTable. You can then use the following formula to generate the random characters:

=VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)
& VLOOKUP(RANDBETWEEN(1,62),MyTable,2)

Again, remember that this is a single formula, although it is a bit shorter than the previous formula.

Each of the approaches presented so far has one drawback: they are regenerated each time your worksheet is recalculated. Thus, it is hard to have a single generated random string that won't change on a regular basis. The best way around this is to use a macro, but you don't necessarily want to use a user-defined function. Why? Because it, too, would change its result every time the worksheet was recalculated. Instead, you need a macro that will put the random strings into your workbook starting at a specific cell location. The following is an example of such a macro:

Sub MakeRandom()
    Dim J As Integer
    Dim K As Integer
    Dim iTemp As Integer
    Dim sNumber As String
    Dim bOK As Boolean

    Range("D4").Activate
    Randomize
    For J = 1 To 50
        sNumber = ""
        For K = 1 To 8
            Do
                iTemp = Int((122 - 48 + 1) * Rnd + 48)
                Select Case iTemp
                    Case 48 To 57, 65 To 90, 97 To 122
                        bOK = True
                    Case Else
                        bOK = False
                End Select
            Loop Until bOK
            bOK = False
            sNumber = sNumber & Chr(iTemp)
        Next K
        ActiveCell.Value = sNumber
        ActiveCell.Offset(1, 0).Select
    Next J
End Sub

Run the macro, and whatever is in cells D4:D53 is overwritten by the random values. If you want the values written into a different location, change the Range statement near the beginning of the macro.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (3872) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Generating Random Strings of Characters.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Replacing All Building Blocks

Word's Building Blocks can be a great tool to improve your productivity when writing. Depending on the type of writing you ...

Discover More

Converting Units

Using the Analysis ToolPak for the vast conversions the CONVERT function in an Excel worksheet has availabile.

Discover More

Getting a Double-Spaced Printout

When working with printed documents, many people prefer to see the document double-spaced. If you have a single-spaced ...

Discover More

Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!

MORE EXCELTIPS (MENU)

Returning Least-Significant Digits

Do you ever have a need to return just a few digits out of a number? This tip shows different formulas you can use to return ...

Discover More

Totaling Across Worksheets

Want to sum the values in the same cell on a range of worksheets? It's not as easy as summing a range on the same worksheet, ...

Discover More

Evaluating Formulas

Need a bit of help in figuring out how Excel is evaluating a particular formula? It's easy to figure out if you use the ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments for this tip:

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is seven minus 6?

2016-01-15 09:59:00

Willy Vanhaelen

@John Bollier
I don't know if your request is still valid but here is the answer anyhow:

Sub MakeRandom()
Const allow = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%"
Dim cell As Range, X As Integer, Y As String
Randomize
For Each cell In Selection
Y = ""
For X = 1 To 8
Y = Y & Mid(allow, (Len(allow) - 1) * Rnd + 1, 1)
Next X
cell = Y
Next cell
End Sub

This macro is less than half the size of the one proposed in this tip and it is much more easier to use and to adjust to your needs.

You can add or remove characters in the allow constant and the macro will handle it automatically.

Just highlight the range you want to fill and run the macro.


2016-01-09 13:37:09

Vijayakumar

I need to unique string characters with min to maximum limit. Please provide vba code to me.


2014-09-12 07:47:43

Michael (Micky) Avidan

For the second approach (Placing the following 62 Characters - ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
- in range A1:A62 we can use 8 concatenates parts of the following segment:
=OFFSET(A1,INT(RAND()*62),)
There is no need to TYPE those 62 characters as most of them can be placed with the help of:
=CHAR(ROW()+xx)
Michael (Micky) Avidan (MVP - Excel)
“Microsoft® Answers" - Wiki author & Forums Moderator
“Microsoft®” MVP – Excel (2009-2015)
ISRAEL


2014-09-11 13:27:19

John Bollier

Thanks for this macro..
I do love it. I was wondering if it could be modified to included ASCII characters like " ! @ # $ % " ???
I tried adding the char codes for them on Line
"Select Case iTemp
Case 48 To 57, 65 To 90, 97 To 122"
but when running the macro, none of the ASCII character ever show up..
Any help would be greatly appreciated..


2014-07-31 04:04:10

Karl

Thanks for this it really helped.


2012-11-24 15:37:36

MiniAudios

Thanks for sharing this info.
It Really Helped


2012-08-22 15:42:59

Mateus

Thank you very much for this infomartion
It saved me a lot of time in my job cause I needed to generate ID's for table I was going to import with text files
^^


Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.

Links and Sharing
Share