我正在尝试使用公式来获取字母表。
公式:
=Keytable(RANDOM,ROW())
功能:
Function KeyTable(seed As Long, position As Long) As String
Dim i As Long
Stop
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
Stop
KeyTable = calpha(position)
End Function
结果:
#Value!
当我单步执行该功能时,它永远不会到达第二站。有什么问题?
答案 0 :(得分:3)
RANDOM
不是Excel中的函数。 RAND()
是,它返回0到1之间的float
。您需要integer
来进行模数计算。
要获得随机整数,请使用:
INT ((upperbound - lowerbound + 1) * RAND() + lowerbound)
然后,一旦seed Mod 27 - i
变为0或更小,该函数就会死亡,因为在VBA(或大多数语言)中,数组不能被索引为0或更少。
但实际上你需要为随机字母做的就是:
=CHAR(RANDBETWEEN(65,90))
答案 1 :(得分:0)
此代码将返回随机字母:
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