2017-05-09 89 views
0

我试图找到一种方式来获得这个喜欢如何在Excel VBA中设置MyArray动态?

Dim MyArray(1 To 1893) As Integer 

工作动态目前我不能这样做,总是需要输入号码这实际上是最大(TAS_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 
+2

使用'ReDim'? – avb

+0

或'ReDim Preserve' - http://stackoverflow.com/questions/2916009/what-does-redim-preserve-do – Vityata

+0

'ReDim Preserve'可能会很慢。如果你可以一次性调整你的数组,并且需要使用ReDim Preserve在你的循环之后调整它的大小,那么你只需要做一次。 – Tom

回答

1

您需要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 
+0

非常感谢第一次我得到明确的答复, – Michal

0

关于这个事实,你有Integer工作,只需启动该阵列的最大整数并不在乎使其变大或较小的 - 你是不是得到什么:

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中使用整数 - Why Use Integer Instead of Long?

+0

我的整数值是从1到最大2500 – Michal