MS Access中的静态随机数

时间:2019-02-27 15:52:02

标签: ms-access access-vba

我正在使用以下公式来尝试创建静态随机数。

Random Number: Format(Int((99999999-11111111+1)*Rnd([Numbers]+11111111)))

但是,它返回一个不同的非静态随机数。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以否定提供给Rnd函数的数字参数,以使Rnd函数为给定的种子值返回相同的随机数(即,将一对一随机数和种子值之间的一种映射):

  

语法

     

Rnd[(number)]

     

返回值

     

如果 number

     
      
  • 小于零:每次使用相同的数字,使用数字作为种子。

  •   
  • 大于零:序列中的下一个随机数。

  •   
  • 等于零:最近生成的数字。

  •   
  • 未提供:序列中的下一个随机数。

  •   
?rnd(-2)
 0.7133257 
?rnd(-2)
 0.7133257 
?rnd(-3)
 0.9633257 
?rnd(-3)
 0.9633257 

但是,更好的方法可能是用静态随机数填充源表中的其他字段,或者构造一个单独的表,其中包含名称与随机数之间的映射。

对于您的特殊情况,由于要生成8位随机数,请使用:

10000000 + Int(90000000 * Rnd(-[Names]))

这将产生1000000099999999范围内的随机数。

答案 1 :(得分:0)

您可以从我的文章中使用函数RandomRowNumber:

Random Rows in Microsoft Access

' Builds random row numbers in a select, append, or create query
' with the option of a initial automatic reset.
'
' 2018-09-11. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RandomRowNumber( _
    ByVal Key As String, _
    Optional Reset As Boolean) _
    As Single

    ' Error codes.
    ' This key is already associated with an element of this collection.
    Const KeyIsInUse        As Long = 457

    Static Keys             As New Collection

    On Error GoTo Err_RandomRowNumber

    If Reset = True Then
        Set Keys = Nothing
    Else
        Keys.Add Rnd(-Timer * Keys.Count), Key
    End If

    RandomRowNumber = Keys(Key)

Exit_RandomRowNumber:
    Exit Function

Err_RandomRowNumber:
    Select Case Err
        Case KeyIsInUse
            ' Key is present.
            Resume Next
        Case Else
            ' Some other error.
            Resume Exit_RandomRowNumber
    End Select

End Function

其中包含一个演示供下载。

代码也可以在 GitHub 上找到:VBA.RowNumbers