数组下标超出范围错误-不知道为什么? [英] Subscript out of range error with an array - no idea why?

查看:370
本文介绍了数组下标超出范围错误-不知道为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了这样的数组Dim rArray() As Variant,但是当我尝试使用存储在其中的值(如下所示)时,出现下标超出范围错误. UBound(rArray)LBound(rArray)都返回值14和1,但错误发生在Debug.Print行.

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 error. The UBound(rArray)and LBound(rArray) both returns values 14 and 1, but the error occurs at the Debug.Print line.

如果我使用如下的for语句

If I use the for statement as below

For Each rArr in rArray

然后它可以正常工作,但是出于我要创建此数组的目的,我需要灵活选择以该顺序存储的每个项目-这意味着我需要使用下标来引用它们.

then it works without issues, but for the purposes I am creating this array I need the flexibility to select each item stored in that order- meaning I need to refer to them using subscripts.

我尝试了多种方法来尝试解决这一问题,但没有一帆风顺,我花了将近一半的时间来解决这一问题.谁能指出我需要进行哪些更改才能使其正常工作.

I have tried multiple ways to try and solve this with no luck and spend almost half my day on this one issue. Could anyone point out what I need to change to get this to work.

Set rng = Range("D4", Range("D4").End(xlDown))
rng.NumberFormat = "0"
rArray = rng.Value

For x = UBound(rArray) To LBound(rArray) Step -1
    Debug.Print rArray(x)
Next x

Edit:另一个值得一提的事实是,他的数组是在Function中声明和使用的,但不会从该函数传递或传递给该函数.不能在函数中声明和使用数组吗?

another fact worth mentioning is that he array is declared and used within a Function but it is not passed from or to the function. Can't arrays be declared and used in Functions?

推荐答案

将工作表值分配给变量数组时,您总是最终得到的是 1的二维数组(例如1表示某物,1表示某物; 从不 0表示某物,0表示某物).如果您要从单个列中获取值,则第二个Rank仅为1:1.

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.

这可以通过以下证明.

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.

这篇关于数组下标超出范围错误-不知道为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆