为什么我需要Int函数

时间:2019-07-06 14:37:35

标签: vba range

A。 Int函数在此代码中有何帮助? B.为什么在没有+1的情况下+1可以很好地添加到Rnd中

尝试删除+1

Function DrawOne(Range As Variant, Optional ReCalc As Variant = False)

    'Chooses one cell at Random from a Range and returns range contents
    'make Function volatile if Recalc is True
    Application.Volatile ReCalc

    'Determine a Random cell
    DrawOne = Range(Int(Range.Count) * Rnd + 1)

End Function

1 个答案:

答案 0 :(得分:4)

使用Int()函数的原因是Range.Count * Rnd可以返回超过0.50的十进制值。发生这种情况时,该值将被四舍五入,这将使您的上限比预期的高1。

enter image description here

这是使用OP代码修改后的简单测试:

Sub Test()
    Dim n As Long
    Dim result As Double
    Dim Target As Range
    Set Target = Range("A1:A10")
    For n = 1 To 1000
        If Intersect(Target, DrawOne(Target)) Is Nothing Then
            MsgBox "DrawOne mising Int() function failure"
            End
        End If
    Next

End Sub

Function DrawOne(Range As Range) As Range
    Set DrawOne = Range(Range.Count * Rnd + 1)
End Function