本文介绍了生成随机数和字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时在 mid 为零时不断收到此错误:

Keep getting this error sometimes when mid is ZERO:

无效的过程调用或参数:'Mid'

我该如何解决这个问题?

How would I fix this?

Function CreateRandomString(iSize)
    Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    Dim sNewSearchTag
    Dim I

    For I = 0 To iSize
        Randomize
        sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT,Round(Rnd * Len(VALID_TEXT)),1)
    Next

    CreateRandomString = sNewSearchTag
End Function

推荐答案

要使随机范围正确,您需要确保生成的随机值介于 1 和 VALID_TEXT 字符串的长度之间价值.

For the random range to be correct you need to make sure the random value generated is between 1 and the length of the VALID_TEXT string value.

使用 Rnd() 执行此操作的简单公式是

The simple formula to do this using Rnd() is

(Rnd() * Len(VALID_TEXT)) + 1

还将 Randomize() 移到循环之外,因为这样只会在每次循环迭代时重置种子时降低随机性.

also move Randomize() outside the loop, as it is you'll just make it less random as you're resetting the seed with every iteration of the loop.

错误的原因是Mid() 需要一个有效的开始和大小,零值不是.有关详细信息,请参阅此问题.

可以在另一个问题的此答案中找到有关随机数范围的更多信息.

More information about random number ranges can be found in this answer to another question.

这篇关于生成随机数和字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 19:24
查看更多