VBA macro Runtime Error "9": index out of range - array

I got an error when I try to create a population for GA. I used a 2d array to help generate a population. First, the user enters the size of the population, and then the length of the chromosome, in the user form.

My variables are:

Dim Generation As Integer Dim Chromolength As Integer Dim varchromolength As Integer Dim Poparr() As Integer 

Then I select the values ​​from the user form:

 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 coding where ocurs error:

 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 

Sorry, I'm pretty new to VBA. Any help with this error would be appreciated.

+4
source share
1 answer

Based on your code, you never assign array sizes. To do this, insert this line before the for loop after setting the PopSize and ChromoLength .

 Redim Poparr(1 to PopSize, 1 to ChromoLength) 

Unnecessary details: You can simply run Redim Poparr(PopSize, ChromoLength) , but this will result in arrays that were 0 to Popsize , etc., unless you add Option Base 1 at the beginning of your module. The default database for arrays is 0. I believe that it is better to explicitly specify the lower and upper bounds of your array, since the default can be 0 or 1 depending on the context.

+5
source

Source: https://habr.com/ru/post/1436175/


All Articles