嵌套For / Next循环和填充数组的问题

时间:2016-10-03 02:13:17

标签: vba excel-vba excel

我正在进行VBA分配,需要创建一个以相反顺序自动填充值16到9的数组。这是我目前的代码:

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

1 个答案:

答案 0 :(得分:0)

您不需要为此设置嵌套循环。你只能用内部循环来做到这一点。你走了。

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