VBA宏运行时错误'9':下标超出范围 - 数组

时间:2021-07-23 16:42:34

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:

然后我从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很新。任何有关此错误的帮助将不胜感激。

1 个解决方案

#1


5  

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. 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到Popsize等...除非您将Option Base 1添加到模块的顶部。数组的默认基数为0.我觉得最好明确指出数组的下限和上限,因为默认值可以是0或1,具体取决于上下文。

#1


5  

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. 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到Popsize等...除非您将Option Base 1添加到模块的顶部。数组的默认基数为0.我觉得最好明确指出数组的下限和上限,因为默认值可以是0或1,具体取决于上下文。