Subscript out of range error with an array - no idea why?

前端 未结 1 1660
青春惊慌失措
青春惊慌失措 2021-01-05 02:42

I have declared an array as such Dim rArray() As Variantbut when i try and use the values that is stored in it (as shown below) I get a subscript out of range e

相关标签:
1条回答
  • 2021-01-05 03:22

    When you assign worksheet values to a variant array, you always end up with a 2-D array that is 1 based (e.g. 1 to something, 1 to something; never 0 to something, 0 to something). If you are getting values from a single column the second Rank is merely 1 to 1.

    This can be proven with the following.

    Dim x As Long, rArray As Variant, rng As Range
    
    Set rng = Range("D4", Range("D4").End(xlDown))
    rng.NumberFormat = "0" 'don't really understand why this is here
    rArray = rng.Value
    
    Debug.Print LBound(rArray, 1) & ":" & UBound(rArray, 1)
    Debug.Print LBound(rArray, 2) & ":" & UBound(rArray, 2)
    
    For x = UBound(rArray, 1) To LBound(rArray, 1) Step -1
        Debug.Print rArray(x, 1)
    Next x
    

    So you need to ask for the element in the first rank of the array; it is insufficient to just ask for the element.

    0 讨论(0)
提交回复
热议问题