2016-10-03 99 views
0

我正在VBA分配中工作,需要創建一個數組,以相反的順序自動填充值16到9。這是我的當前代碼:嵌套的For/Next循環和填充數組的問題

nTeams = 16      ' variable to enable other size brackets 

ReDim arrBracket(nTeams/2) '<< ReDim array to appropriate size 


'***** Fill the array where element 1 of the array holds the value of the 
'  lowest seed (e.g. if 16 teams, element 1 has a value of 16) 

' vvv your For/Next loop below 
Dim nTeams2 As Integer ' Place holder for For/Next loop 

For i = 1 To (nTeams/2) 
    For nTeams2 = nTeams To (nTeams/2) Step -1 
     arrBracket(i) = nTeams2 
    Next nTeams2 
Next i 

的問題是,它現在只填充數8陣列的每個8個元素,而不是16,15,14,13等

這裏是循環包括我的教授來檢查工作:

For i = LBound(arrBracket()) To UBound(arrBracket()) ' loops through the array 
    Debug.Print i & " vs " & arrBracket(i)    ' sends array info to immediate window 
Next i 
+0

您不需要使用內部循環。發生的事情是您將多個不同的值分配給陣列中相同的位置。最後一個總是8. – mathiasfk

回答

0

你並不需要設置爲嵌套循環。你只能用inner for loop來做到這一點。幹得好。

nTeams = 16      ' variable to enable other size brackets 

ReDim arrBracket(nTeams/2) '<< ReDim array to appropriate size 

Dim i As Integer 
Dim nTeams2 As Long 

i = 0 
For nTeams2 = nTeams To (nTeams/2) Step -1 
    arrBracket(i) = nTeams2 
    i = i + 1 
Next nTeams2 
+1

修改'i = 1'到'i = 0'的行,否則你的代碼將會得到「下標超出範圍」,因爲你正在進入不存在的arrBracket(9) –

+0

你是對的。謝謝。 –