Reputation: 45
I got some help from one, and the code works perfectly fine.
What im looking for, is an explanation of the code, since my basic VBA-knowledge does not provide me with it.
Can someone explain what happens from "Function" and down?
Sub Opgave8()
For i = 2 To 18288
If Left(Worksheets("arab").Cells(i, 12), 6) = "262015" Then
Worksheets("arab").Cells(i, 3) = "18" & UniqueRandDigits(5)
End If
Next i
End Sub
Function UniqueRandDigits(x As Long) As String
Dim i As Long
Dim n As Integer
Dim s As String
Do
n = Int(Rnd() * 10)
If InStr(s, n) = 0 Then
s = s & n
i = i + 1
End If
Loop Until i = x + 1
UniqueRandDigits = s
End Function
Upvotes: 0
Views: 85
Reputation: 2412
The code loops from row 2 to 18288 in Worksheet "arab". If first 6 characters in 12th column are "262015", then in 3rd column macro will fill cell with value "18" followed by result of function UniqueRandDigits(5)
which generates 5 unique digits (0-9).
About the UniqueRandDigits
function, the most important is that Rnd()
returns a value lesser than 1 but greater than or equal to zero.
Int
returns integer value, so Int(Rnd() * 10)
will generate a random integer number from 0 to 9.
If InStr(s, n) = 0 Then
makes sure than generated integer value doesn't exist in already generated digits of this number, because as the function name says, they must be unique.
Upvotes: 1
Reputation: 1156
n = Int(Rnd()*10)
returns a value between 0 and 9, since Rnd
returns a value between 0 and 1 and Int
converts it to an integer, aka, a natural number.
Then If InStr(s, n) = 0
checks if the random number is already in your result: if not, it adds it using the string concatenation operator &
.
This process loops (do
) until i = x + 1
where x
is your input argument, so you get a string of length x
. Then the first part just fills rows with these random strings.
N.B. : I explained using the logical order of the code. Your friend function UniqRandDigits
is defined after the "business logic", but it's the root of the code.
Upvotes: 1