2012-09-25 196 views
4

我嘗試爲GA生成總體時遇到了錯誤。我使用了一個2D數組來幫助生成一個人口。首先,用戶將輸入人口大小,然後輸入染色體長度,進入用戶表單。VBA宏運行時錯誤'9':下標超出範圍 - 數組

我的變量:

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

然後我從窗體獲取值:

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 

我很抱歉,我:

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 

然後在錯誤ocurs編碼VBA相當新穎。任何幫助這個錯誤將不勝感激。

回答

5

根據您的代碼,您從不指定數組的維數。爲此,在設置PopSizeChromoLength的值之後,在for循環之前插入此行。

Redim Poparr(1 to PopSize, 1 to ChromoLength) 

不必要的細節:你可以只運行Redim Poparr(PopSize, ChromoLength)但這樣會導致那名0 to Popsize等陣列...除非你添加Option Base 1到您的模塊的頂部。數組的默認基數爲0.我認爲最好明確指出數組的下限和上限,因爲默認值可以是0或1,具體取決於上下文。

相關問題