错误9下标超出范围
我正在试图用一张表中的数据填充一个dynamic数组。 我得到“错误9下标超出范围”。 为什么?
Sub correct() Dim row As Integer, i As Long Dim constants() As Double 'this declares the dynamic array row = 1 i = 0 ReDim constans(0) 'this resizes the array(rediminsion's the array) Do Until ThisWorkbook.Sheets("Deg 4").Cells(row, 1).Value = "" constants(i) = ThisWorkbook.Sheets("Deg 4").Cells(row, 1).Value i = i + 1 'increments array index ReDim Preserve constants(i) 'resize the array 1 larger and preserves previous data row = row + 1 'increments the worksheet row Loop End Sub
你拼错了你的数组的名字:
ReDim constans(0)
应该:
ReDim constants(0)
所以,错误的是,你使用ReDim
来声明一个名为constans
的新数组,并且constants
仍然constans
分配。 当你到达你的过程中的constants(i) = ...
行时,你会得到这个错误,因为constants
是未分配的。
我以前从来没有遇到过这种特殊的错误。 我真的感到震惊,VBA语言设置允许这个! 微软警告这个 ( 强调我的):
警告 :如果
ReDim
声明的variables在模块级别或过程级别不存在,ReDim
语句将作为声明语句。 如果稍后创build具有相同名称的另一个variables,即使在更广的范围内, 即使Option Explicit
有效 ,ReDim
也会引用后面的variables,并不一定会导致编译错误。 为了避免这种冲突,ReDim
不应该被用作声明性声明,而只是用于重新定义数组。
好的,谢谢你的隐藏警告,但他们应该没有给予ReDim
声明性function。
问题在于你的声明
Dim constants() As Double 'this declares the dynamic array
但是你ReDim
一个不同的未声明的数组
ReDim constans(0) 'this resizes the array(rediminsion's the array)
将缺less的“t”添加到“constans”将解决这个问题。 如果要避免无意中使用未声明的variables,请转到工具..>选项..>编辑器选项卡,并确保“要求variables声明已选中 – 这将在您创build的每个模块的顶部插入Option Explicit
(但不是现有的)。
在声明了Option Explicit
和CamelCasevariables的情况下,当你按下Enter键input你的variables名(小写字母)时,它们将会变成CamelCase
,声明确认input的名字已被声明。 如果它没有改变,那么它是未声明的,当你尝试运行这个过程时,会导致编译错误。
在 运行你的程序之前 ,先进入Debug ..> Compile VBA Project或者按Alt> d> l进行 编译 。 如果你没有看到消息框,那么它可能会运行
PS:你可能会得到意想不到的结果,因为我的testing显示常量(0)= 1等等,直到常量(last i)= 0。可能不是你想要的,但如果是的话,那么…一切都好!