[英]VBA macro Run time error '9': subscript out of range - array
I have been experiencing a error when I try to generate a population for a GA. 尝试为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.
首先,用户将用户数量输入染色体大小,然后输入染色体长度。
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. 抱歉,我是VBA的新手。 Any help with this error will be appreciated.
任何与此错误的帮助将不胜感激。
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
和ChromoLength
的值之后,在for循环之前插入此行。
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. 不必要的详细信息:您可以只运行
Redim Poparr(PopSize, ChromoLength)
但这将导致数组的0 to Popsize
等...除非在模块顶部添加Option Base 1
。 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. 数组的默认基数为0。我认为最好明确指出数组的下限和上限,因为根据上下文,默认值可以为0或1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.