Home » excel » Using functions like formulas in Excel

Using functions like formulas in Excel

Posted by: admin May 14, 2020 Leave a comment


I am trying to use a formula to get a letter of the alphabet.




Function KeyTable(seed As Long, position As Long) As String
    Dim i As Long
    Dim calpha(1 To 26) As String
    Dim alpha(1 To 26) As String

    For i = 1 To 26
        alpha(i) = Chr(i + UPPER_CASE - 1)
    Next i

    For i = 1 To 26
        calpha(i) = alpha(seed Mod 27 - i)
    Next i
    KeyTable = calpha(position)
End Function



When I step through the function, it never gets to the second stop. What is wrong?

How to&Answers:

RANDOM is not a function in Excel. RAND() is and it returns a float between 0 and 1. You need an integer to do modulus calculations.

To get a random integer, use:

INT ((upperbound - lowerbound + 1) * RAND() + lowerbound)

Then, once seed Mod 27 - i becomes 0 or less, the function dies because arrays can’t be indexed with 0 or less in VBA (or most languages).

But really all you need to do for a random letter is this:



This code will return random letter of alphabet:

Function GetLetter()
    Dim letters As String
    Dim randomIndex As Byte

    letters = "abcdefghijklmnopqrstuvwxyz"
    randomIndex = Int((26 - 1 + 1) * Rnd() + 1) //Get random number between 1 and 26

    GetLetter = VBA.Mid$(letters, randomIndex, 1)
 End Function