Array() = range().value

后端 未结 3 912
旧时难觅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: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
    

提交回复
热议问题