For j = 0 To 20
For i = 0 To 20
ReDim atoms(0 To 20, 0 To 20)
ReDim atomschange(0 To 20, 0 To 20)
atomschange(j, i) = 0
If i Mod 2 = 0 And j Mod 2 = 0 Then
[B2].Offset(j, i).Interior.ColorIndex = 37
atoms(j, i) = 1
Else
[B2].Offset(j, i).Interior.ColorIndex = 36
atoms(j, i) = 0
End If
Next i
Next j
End Sub
我在做什么错了?
答案 0 :(得分:7)
您将在重新初始化的循环内重设数组,然后将所有数据放入数组中。使用PRESERVE
关键字来确保在重新命名数组时ReDim Preserve atoms(0 To 20, 0 To 20)
将数组重新排列为完全相同的大小没有任何意义。它们已经是0 To 20, 0 To 20
,因为您已经设置了。将它们一次重新设置为for循环,然后不理会它们。
确保在代码顶部正确声明atoms
和atomschange
数组。它在抱怨(可能是在重新定义它们时)这两个变量不是数组。
在执行此代码之前,您已经知道了数组的大小,因此请声明它们并在声明中对其进行适当的调暗,然后再使用它们(删除循环中redim
的多余和不正确的用法:
Sub somesumroutine()
Dim atoms(0 to 20, 0 to 20) as Integer
Dim atomschange(0 to 20, 0 to 20) as Integer
For j = 0 To 20
For i = 0 To 20
atomschange(j, i) = 0
If i Mod 2 = 0 And j Mod 2 = 0 Then
[B2].Offset(j, i).Interior.ColorIndex = 37
atoms(j, i) = 1
Else
[B2].Offset(j, i).Interior.ColorIndex = 36
atoms(j, i) = 0
End If
Next i
Next j
End Sub
考虑使用UBound
数组中的LBound
和atoms
来设置循环,这样就不必一遍又一遍地使用0 to 20
。这样,您可以将数组变暗一次,而剩下的代码则不用担心:
Sub somesumroutine()
Dim atoms(0 to 20, 0 to 20) as Integer
Dim atomschange(0 to 20, 0 to 20) as Integer
For j = lBound(atoms, 1) To uBound(atoms, 1)
For i = lBound(atoms, 2) To uBound(atoms, 2)
atomschange(j, i) = 0
If i Mod 2 = 0 And j Mod 2 = 0 Then
[B2].Offset(j, i).Interior.ColorIndex = 37
atoms(j, i) = 1
Else
[B2].Offset(j, i).Interior.ColorIndex = 36
atoms(j, i) = 0
End If
Next i
Next j
End Sub