VBA - 获取数组长度时无效的限定符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26640199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:03:33  来源:igfitidea点击:

VBA - invalid qualifier when getting array length

vbaexcel-vbaexcel

提问by bsapaka

I am trying to make a function that puts the param into an array, then returns a random index value of the array. My code gets a compile error: invalid qualifierat arr.Length. So far I have:

我正在尝试制作一个将参数放入数组的函数,然后返回数组的随机索引值。我的代码compile error: invalid qualifierarr.Length. 到目前为止,我有:

Function myFunction(List As Range)
    Dim arr()
    Dim indx

    arr = List
    indx = (Int(Rnd()) * arr.Length)   'error here

    myFunction = indx
End Function

Not sure if I am using the array right, or returning the value right - Please help

不确定我是否正确使用数组,或正确返回值 - 请帮忙

REVISION 1

修订 1

Replaced .length with ubound and lbound - now I am getting a #VALUEerror in the cell when it should be returning the array's index value.

用 ubound 和 lbound 替换了 .length - 现在#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

采纳答案by Jean-Fran?ois Corbett

When you assign the Value of a Range to an array, you get a 2-D array with dimensions (1 to numberOfRows, 1 to numberOfCols), so the solution is to change arr(indx)to

当您将范围的值分配给数组时,您会得到一个维度为 的二维数组(1 to numberOfRows, 1 to numberOfCols),因此解决方案是更改arr(indx)

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,1)
End Function