如何在Excel VBA中设置MyArraydynamic?

我正试图find一个方法来得到这个样子

Dim MyArray(1 To 1893) As Integer 

工作dynamic目前我无法这样做,总是需要input数字,其实是最大的(TAS_ID)任何帮助将不胜感激,我无法find一种方法来定义数组从1到N ..或find其他方法来实现同样的效果。

 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 

关于这个事实,你使用Integer ,只需将数组初始化为Max整数,而不必考虑使其变大或变小 – 你没有获得任何东西:

 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中完全不使用整数 – 为什么使用整数而不是长整数?