Array() = range().value

僤鯓⒐⒋嵵緔 提交于 2019-12-31 02:35:04

问题


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").Value
For i = 0 To UBound(arr)
    Debug.Print arr(i)
Next i

End Sub

First, above code is giving me subscript out of range error. How come ? Second, what part of the documentation would let me know how array() = range().value would play out without testing it ? My hypothesis is that it will go through the cells from the top left to the bottom right and add them to the array. How can I confirm that though ?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/32185325/array-range-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!