【发布时间】:2014-10-30 17:02:42
【问题描述】:
我正在尝试创建一个将参数放入数组的函数,然后返回数组的随机索引值。我的代码在arr.Length 获得compile error: invalid qualifier。到目前为止,我有:
Function myFunction(List As Range)
Dim arr()
Dim indx
arr = List
indx = (Int(Rnd()) * arr.Length) 'error here
myFunction = indx
End Function
不确定我是正确使用数组还是正确返回值 - 请帮助
修订版 1
将 .length 替换为 ubound 和 lbound - 现在我在单元格中收到 #VALUE 错误,而它应该返回数组的索引值。
Function myFunction(List as Range)
Dim arr()
Dim indx as Integer
arr = List
indx = Int(Rnd() * (UBound(arr) - LBound(arr) + 1)) 'indx
myFunction = arr(indx)
End Function
【问题讨论】:
-
VBA 数组没有
Length属性:使用UBound()和LBound() -
好的,编辑成功了(谢谢)。我遇到了另一个问题,单元格不会返回索引值(请参阅修订版)
-
将
Dim indx更改为Dim indx As Integer -
@Daniel 这似乎不起作用
-
当您将范围的值分配给数组时,您会得到一个具有维度(1 到 numberOfRows,1 到 numberOfCols)的二维数组。您需要调整代码,以便正确索引到该数组。目前还不清楚输入范围的形状是什么,因此很难提出具体的建议。