excel - 创建自定义函数以从范围内返回随机单元格值
问题描述
我是 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
解决方案
不幸的是,您的功能的意图是不可辨别的。因此我修改了这个意图。下面的函数不会返回随机数本身和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 多得多的单元格。
当然,该函数也会返回生成的随机数的值。
推荐阅读
- xml - Powershell从文件中删除特定文本
- node.js - NodeJS 在数据库或属性文件中存储 mongo 聚合查询
- swift - 设计使用 Core Data NSManagedObject 的 SwiftUI 预览
- r - 按频率过滤数据
- sql - Oracle 从 Exists 子句的主查询中提取列
- openbmc - 为 webui 添加第一个 opembmc 用户
- firebase - 我会因为覆盖 firebase 的空 onchildadd() 而被收费吗?
- c - 创建启用所有支持的扩展/功能的 Vulkan 实例/设备
- python - 无法从“变形金刚”(未知位置)导入名称“管道”
- c# - 所有项目的 Visual Studio 2019 未处理异常 - 无法调试