Array() = range().value

后端 未结 3 907
旧时难觅i
旧时难觅i 2021-01-20 15:27

I saw array() = range().value in an example and I\'m trying to understand how it works.

Sub test()
Dim arr() As Variant

arr() = Range(\"E5:E7\         


        
相关标签:
3条回答
  • 2021-01-20 16:06

    It's basically loading the cell values of E5 - E7 into an array. But it is going to be two dimensional. So you will need Debug.Print arr(i, 1)

    Sub test()
    Dim arr() As Variant
    
    arr() = Range("E5:E7").Value
    For i = 1 To UBound(arr)
        Debug.Print arr(i, 1)
    Next i
    
    End Sub
    
    0 讨论(0)
  • 2021-01-20 16:07

    This is a good read for you: http://www.cpearson.com/excel/ArraysAndRanges.aspx

    The reason you're getting "out of range" is because it returns a 2 dimensional array.

    Your line of code For i = 0 To UBound(arr) should be For i = 1 To UBound(arr,1)

    Also, the array starts at 1, so don't use the 0 For i = 1 to UBound(arr, 1)

    Your corrected code would be:

    Sub Test()
    
    Dim arr() as Variant
    arr = Range("E5:E7")
    For i = 1 To UBound(arr, 1)
        MsgBox (arr(i, 1))
    Next i
    
    End Sub
    
    0 讨论(0)
  • 2021-01-20 16:19

    I see two issues with your code. The first is that you start i at 0, but arrays in Excel begin at index 1. Instead of For i = 0 you can use For i = LBound(arr) like you use UBound(arr) or just start it at 1.

    Second, and more importantly, an array of cells has both columns and rows. When you read a range into a variant array, you get a two-dimensional result (rows and columns) and not a one-dimensional result as you seem to be expecting.

    Try this:

    Sub test()
            Dim arr() As Variant
            Dim i As Long, j As Long
    
            arr() = Range("E5:E7").Value
            For i = 1 To UBound(arr, 1)
                    For j = 1 To UBound(arr, 2)
                            Debug.Print arr(i, j)
                    Next j
            Next i
    End Sub
    

    If you want to get just the values of the cells into a one dimensional array, you can do that by using the Transpose function, like this:

    arr() = Application.WorksheetFunction.Transpose(Range("E5:E7").Value)
    

    If you do this, the array is now one-dimensional and you can iterate through it like you were trying to.

    arr() = Application.WorksheetFunction.Transpose(Range("E5:E7").Value)
    
    For i = 1 To UBound(arr)
        Debug.Print arr(i)
    Next i
    
    0 讨论(0)
提交回复
热议问题