【问题标题】:Create Custom Function to return random cell value from a range创建自定义函数以从范围内返回随机单元格值
【发布时间】:2020-04-21 00:21:07
【问题描述】:

我是一名 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

【问题讨论】:

  • 知道随机数为什么要循环?
  • 目的是从一个范围内随机选择一个数字。
  • 换句话说,你没有在你的 sn-p 中使用cell.Value 做任何事情。
  • 你是对的。以下是结束循环的适当方式吗?循环直到单元格是随机的
  • 我认为你根本不需要在这里循环。

标签: excel vba function random


【解决方案1】:

很遗憾,您的功能的意图是不可辨别的。因此我修改了这个意图。下面的函数不会返回随机数本身和在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 多得多的单元格。

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

【讨论】: