Modifying VBA Code to generate 4-digit numbers...

hararahm

New Member
Joined
Feb 18, 2013
Messages
10
I'm looking for assistance with modifying the following VBA code; this code auto-generates 4-digit unique numbers, using zero as one of the starting digit as well. I need the 4-digit numbers NOT to begin with a zero, the 4-digit numbers should only begin with numbers 1-9.



Private Sub Worksheet_Change(ByVal Target As Range)
Dim Cell As Range
Dim Test As Integer
If Target.Column <> 1 Then Exit Sub
Application.EnableEvents = False
For Each Cell In Target
With Cell.Offset(0, 1)
If IsEmpty(Cell) Then
.ClearContents
Else
.NumberFormat = "0000"
Do
.Value = Int(9999 * Rnd())
Test = WorksheetFunction.CountIf(.EntireColumn, .Value)
Loop Until Test <= 1
End If
End With
Next Cell
Application.EnableEvents = True
End Sub
 
Last edited:

Excel Facts

Easy bullets in Excel
If you have a numeric keypad, press Alt+7 on numeric keypad to type a bullet in Excel.
I'm not sure what you want the low range of your numbers to be then. If you don't want to start with a leading zero then I assume you want a random number between 100 and 9999? If so, then change

.Value = Int(9999 * Rnd())
to
.Value = Int((9999 - 100 + 1) * Rnd() + 100)

If that is wrong just change 100 to whatever the lowest number should be.
 
Upvote 0

Forum statistics

Threads
1,203,052
Messages
6,053,234
Members
444,648
Latest member
sinkuan85

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