2016-10-03 94 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

你是对的。谢谢。 –