Return a random letter

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have the following function which works great for returning a random
number in a range from a specified low to a specified high:

Public Function RandomNumbers(argLow As Long, argHigh As Long) As Long

'RETURN A RANDOM NUMBER BETWEEN 'argLow' AND 'argHigh'
Randomize
RandomNumbers = CLng((argHigh - argLow) * Rnd + argLow)

End Function

Now I need a similar function that would return a random letter between A
and Z. Can anyone suggest a more efficient method than just assigning all the
letters of the alphabet to numbers between 1 and 26 to return a random letter?

Thanks in advance.
 
argHigh = asc("Z")
argLow = asc("A")
RandomNumbers = CLng((argHigh - argLow) * Rnd + argLow)
RandomLetter = chr(RandomNumbers)


Sub GenLetters()
For Each cell In Range("A1:A500")
argHigh = Asc("Z")
argLow = Asc("A")
RandomNumbers = CLng((argHigh - argLow) * Rnd + argLow)
RandomLetter = Chr(RandomNumbers)
cell.Value = RandomLetter
Next
End Sub
 
So you could add another function that uses your existing function:

Public Function RandomLetter()
Dim argLow As Long, argHigh As Long
argLow = Asc("A")
argHigh = Asc("Z")
RandomLetter = Chr(RandomNumbers(argLow, argHigh))
End Function


Public Function RandomNumbers(argLow As Long, argHigh As Long) As Long

'RETURN A RANDOM NUMBER BETWEEN 'argLow' AND 'argHigh'
Randomize
RandomNumbers = CLng((argHigh - argLow) * Rnd + argLow)

End Function


from the immediate window:

? RandomLetter()
T
 
You do not need to "assigning all the letters of the alphabet to numbers
between 1 and 26 "
Each letter already has a number assigned to it - its ASCII code
A-Z are in range 65-90 and a-z in range 97-122
Use you random number function to get a value with in the right range and
use the VBA function CHR(n) to return the character.

best wishes
 
Back
Top