2014-10-29 43 views
3

我想使一個函數將參數放入數組中,然後返回數組的一個隨機索引值。我的代碼在arr.Length處獲得compile error: invalid qualifier。到目前爲止,我有:VBA - 獲取數組長度時無效的限定符

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

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

    myFunction = indx 
End Function 

不知道如果我使用的是陣列權,或返回值正確的 - 請幫助

修訂1

替換。長度與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 
+8

VBA數組沒有一個'Length'屬性:使用'UBound()'和'LBound()' – 2014-10-29 20:43:56

+0

沒關係編輯,這工作(謝謝)。我被困在另一個問題上,單元格不會返回索引值(請參見修訂版) – bsapaka 2014-10-29 20:59:00

+0

將'Dim indx'更改爲'Dim indx As Integer' – Daniel 2014-10-29 21:01:43

回答

0

當您指定一個範圍,以一個數組的值,你得到的尺寸(1 to numberOfRows, 1 to numberOfCols) 2-d陣列,因此該解決方案是改變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