访问vba随机功能不起作用

时间:2015-05-20 21:23:37

标签: vba ms-access access-vba

我有一个应该进行多项任务的子项(此数字每天更改)并将它们分配给7名员工。这有一些条件:

如果赋值#小于7,则将它们全部分配给随机关联。 如果#可被7整除,则为每个赋值相同。 如果它不能被7整除,它会平均分配,然后将剩余部分给予随机关联。

问题是随机部分。我真的不明白vba中的随机效果如何,或者至少看起来它应该非常简单,但它不是(也许)。但是我写了这个并且它不起作用。 (Associates(Int(Rnd() * 7) + 1))。这是我的相关代码:

在子应用程序的前面,我创建了一个联系人数组,我使用了一些dcounts来获取当天的总分配:

Dim Associates(6) As Integer
    Associates(0) = 4687 'Anita
    Associates(1) = 4247 'Alberto
    Associates(2) = 2167 'Jeff
    Associates(3) = 4334 'Lisa
    Associates(4) = 4441 'Carrie
    Associates(5) = 2052 'Bobby
    Associates(6) = 4657 'Simona
'
Dim Person As Variant
'
TotalPop = DCount("LNo", "qry_PT_Assign")
FractionPop = Int(TotalPop / 7)
LeftPop = TotalPop - (FractionPop * 7)
'

然后我尝试实际分配它们。

        'Assign to Associates
        If TotalPop < 7 Then
            DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & (Associates(Int(Rnd() * 7) + 1)) & " WHERE AudTellerID IS NULL"
        ElseIf LeftPop = 0 Then
            For Each Person In Associates
                DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & Person & " WHERE LNo IN (SELECT TOP " & FractionPop & " LNo FROM tbl_Assignments WHERE AudTellerID Is Null)"
            Next
        Else
            For Each Person In Associates
                DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & Person & " WHERE LNo IN (SELECT TOP " & FractionPop & " LNo FROM tbl_Assignments WHERE AudTellerID Is Null)"
            Next
            DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & (Associates(Int(Rnd() * 7) + 1)) & " WHERE AudTellerID IS NULL"
        End If

2 个答案:

答案 0 :(得分:1)

根据我的评论,首先尝试生成随机数,将其分配给变量,然后将变量传递给Associates()

Dim rndInt as Integer

rndInt = Int(Rnd() * 7) + 1

Associates(rndInt)

然后正如@Chips所说,你可以使用

Debug.print rndInt 

或者

Msgbox rndInt 

检查其值

通过这种方式,您可以查看实际生成的号码

答案 1 :(得分:0)

诀窍是使用不断变化的负面种子。

因此,为Rnd添加一个时间依赖的种子,该变量针对每个唯一ID进行更改,如此示例选择查询中所示:

 SELECT 
   Table1.ID, 
   Table1.SomeField, 
   Table1.AnotherField, 
   Rnd(-Timer()*[ID]) AS RandomIndex 
 FROM 
   Table1
 ORDER BY 
   Rnd(-Timer()*[ID]);

在您的代码中,表达式可能是这样的:

.. " & (Associates(Int(Rnd(-Timer()*" & [ID] & ") * 7) + 1)) & " ..