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

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

问题描述

我已经声明了一个这样的数组 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

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

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 对某事).如果您从单个列中获取值,则第二个排名仅为 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天全站免登陆