VBA 宏运行时错误“9”:下标超出范围 - 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12585914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA macro Run time error '9': subscript out of range - array
提问by John Hopley
I have been experiencing a error when I try to generate a population for a GA. I used a 2d array to help generate a population. First the user will enter the population size and then the chromosome length, into a userform.
当我尝试为 GA 生成总体时遇到错误。我使用二维数组来帮助生成人口。首先,用户将在用户表单中输入种群大小,然后输入染色体长度。
My variables:
我的变量:
Dim Generation As Integer
Dim Chromolength As Integer
Dim varchromolength As Integer
Dim Poparr() As Integer
Then i fetch the values from the userform:
然后我从用户表单中获取值:
PopSize = PopulationSize.value
aVariables = AOV.value 'assign userform value entered to this variable
varchromolength = Chromolengthentered.value 'assign userform value entered to this variable
Chromolength = varchromolength * aVariables 'Chromosome length equals the length of each varaible chromosome combined
Then the coding where the error ocurs:
然后是发生错误的编码:
For i = 1 To PopSize
For j = 1 To Chromolength
If Rnd < 0.5 Then
Poparr(i, j) = 0 'assign o to gene
Else
Poparr(i, j) = 1 'assign 1 to gene
End If
Next j
Next i
I apologize, I am fairly new to VBA. Any help with this error will be appreciated.
我很抱歉,我对 VBA 相当陌生。任何有关此错误的帮助将不胜感激。
回答by Daniel
Based on your code, you never assign the dimensions of the array. To do so, insert this line before your for loop, after setting the values of PopSize
and ChromoLength
.
根据您的代码,您永远不会分配数组的维度。为此,在设置PopSize
and的值之后,在 for 循环之前插入此行ChromoLength
。
Redim Poparr(1 to PopSize, 1 to ChromoLength)
Unnecessary details:You could just run Redim Poparr(PopSize, ChromoLength)
but that would result in arrays that were 0 to Popsize
etc... unless you add Option Base 1
to the top of your module. The default base for arrays is 0. I feel that it is better to explicitly indicate the lowerbound and upperbound of your array because the default can be 0 or 1 depending on the context.
不必要的细节:您可以直接运行,Redim Poparr(PopSize, ChromoLength)
但这会导致数组0 to Popsize
等......除非您添加Option Base 1
到模块的顶部。数组的默认基数是 0。我觉得最好明确指出数组的下限和上限,因为根据上下文,默认值可以是 0 或 1。