首页 > 解决方案 > 创建自定义函数以从范围内返回随机单元格值

问题描述

我是 VBA 业余爱好者,正在尝试创建一个自定义函数,该函数从已知范围返回随机值。我一定对以下代码做错了,因为它会导致程序崩溃。

您是否知道如何进行更正以允许函数循环遍历范围的每个单元格,直到单元格值等于随机数,该随机数已被 1 和 1000 任意限制?

非常感谢您的任何想法!

Function RandinList(InRange As Range) As Long

Dim random As Long
Dim cell As Range

Do

    random = Int((1000 - 1 + 1) * Rnd + 1)

    For Each cell In InRange
        If Not random = cell Then Exit For
    Next cell

Loop Until cell.Value = random

RandinList = random

End Function

标签: excelvbafunctionrandom

解决方案


不幸的是,您的功能的意图是不可辨别的。因此我修改了这个意图。下面的函数不会返回随机数本身和InRange找到它的位置。这是功能。

Function RandInList(InRange As Range) As Long

    Dim Random As Long
    Dim Fnd As Range

    Random = Int((1000 - 1 + 1) * Rnd + 1)
    Set Fnd = InRange.Find(Random, , xlValues, xlWhole)
    If Fnd Is Nothing Then
        MsgBox "The generated random number " & Random & vbCr & _
               "wasn't found in the given range.", _
               vbInformation, "Number not found"
    Else
        Set InRange = Fnd
    End If
    RandInList = Random
End Function

如您所见,我没有接受您循环遍历单元格的想法。查看 1000 个单元格会导致明显的延迟。Find是瞬时的。

我使用以下代码来测试我的功能。

Private Sub TestRandInList()

    Dim Rng As Range
    Set Rng = Range("A2:G20")
    Debug.Print RandInList(Rng), Rng.Address
End Sub

如您所见,它首先设置,然后在函数调用Set Rng = Range("A2:G20")之后请求。Rng.Address实际上,地址可能已经在函数中改变了,这里:Set InRange = Fnd. 因此,如果Random发现它包含单元格地址。另一方面,如果没有找到,地址Rng保持不变。在您的调用过程中,您可以像这样测试是否成功:If Rng.Cells.Count = 1 Then找到了单元格。这是因为如果范围没有改变,它将有比 1 多得多的单元格。

当然,该函数也会返回生成的随机数的值。


推荐阅读