如何在Excel VBA中设置MyArray动态?
我正试图找到一种方法让它像如何在Excel VBA中设置MyArray动态?,vba,excel,Vba,Excel,我正试图找到一种方法让它像 Dim MyArray(1 To 1893) As Integer 工作动态目前我无法这样做,始终需要键入事实上是max(tasu ID)的数字 任何帮助都将不胜感激, 我找不到从1到n定义数组的方法。。或者找到其他方法来达到同样的效果 Sub Moving_Data() Dim i, j, LastRow, tempID As Integer Dim TAS_ID As Integer Dim k As Boolean LastRow = Cells(Rows
Dim MyArray(1 To 1893) As Integer
工作动态目前我无法这样做,始终需要键入事实上是max(tasu ID)的数字
任何帮助都将不胜感激,
我找不到从1到n定义数组的方法。。或者找到其他方法来达到同样的效果
Sub Moving_Data()
Dim i, j, LastRow, tempID As Integer
Dim TAS_ID As Integer
Dim k As Boolean
LastRow = Cells(Rows.Count, 4).End(xlUp).Row 'last row
For i = 1 To LastRow
Cells(i, 1) = i
Next i
TAS_ID = 1
i = 2
k = True
Dim MyArray(1 To 1893) As Integer ' add max zone number!
'Dim MyArray(1 To max(TAS_ID)) As Integer ??????
Do While k = True
Do While Cells(i + 1, 2) = ""
If i > LastRow Then
Exit Do
End If
Cells(i, 2) = TAS_ID
i = i + 1
Loop
j = i
MyArray(TAS_ID) = j - 1
Cells(2, 14) = j
TAS_ID = Cells(i + 1, 2)
If i > LastRow Then
k = False
Exit Do
End If
j = i + 2
i = j
Loop
For i = 1 To UBound(MyArray)
Cells(1 + i, 11).Value = MyArray(i)
Cells(1 + i, "J") = i
Next i
End Sub
您需要根据需要对阵列进行
ReDim
Sub Moving_Data()
Dim i, j, LastRow, tempID As Integer
Dim TAS_ID As Integer
Dim k As Boolean
LastRow = Cells(Rows.Count, 4).End(xlUp).Row 'last row
For i = 1 To LastRow
Cells(i, 1) = i
Next i
TAS_ID = 1
i = 2
k = True
Dim MyArray() As Integer
ReDim MyArray(1 To 1)
Do While k = True
Do While Cells(i + 1, 2) = ""
If i > LastRow Then
Exit Do
End If
Cells(i, 2) = TAS_ID
i = i + 1
Loop
j = i
'ReDim the array if necessary
If TAS_ID > UBound(MyArray) Then
ReDim Preserve MyArray(1 To TAS_ID)
End If
MyArray(TAS_ID) = j - 1
Cells(2, 14) = j
TAS_ID = Cells(i + 1, 2)
If i > LastRow Then
k = False
Exit Do
End If
j = i + 2
i = j
Loop
For i = 1 To UBound(MyArray)
Cells(1 + i, 11).Value = MyArray(i)
Cells(1 + i, "J") = i
Next i
End Sub
考虑到这样一个事实,即您使用的是
整数
,只需将数组初始化为最大整数,而不必将其变大或变小-您不会获得任何好处:
Option Explicit
Public Sub TestMe()
Dim myArray(1 To 2 ^ 15 - 1) As Integer
Dim lngCounter As Long
For lngCounter = UBound(myArray) To LBound(myArray) Step -100
Debug.Print lngCounter
Next lngCounter
End Sub
(希望你能理解我的幽默感——^)
长话短说,在VBA中根本不要使用整数-使用
ReDim
?或ReDim-Preserve
-ReDim-Preserve
可能非常慢。如果可以一次对数组进行Dim
调整,如果需要,请在循环后使用ReDim Preserve
调整数组大小,以便只需调整一次。我的整数是从1到最大2500的值