2016-10-03 100 views
-1

我不知道我在做什麼錯誤,因爲下面的代碼能夠在第一次迭代中得到ReDim Preserve但不是第二次迭代。ReDim保存在For循環

Dim inj0() As Variant 
Dim i As Integer 
Dim c As Integer 
Dim Rng As Range 
Dim pos As Integer 

'Find the last used column in a Row 
Dim LastCol As Integer 
With ActiveSheet 
    LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column 
End With 

c = 0 
For i = 1 To LastCol 
    pos = InStr(Cells(2, i), "80") 
    If pos = 1 Then 
     ReDim Preserve inj0(c, 2) 
     inj0(0, 1) = "80" 
     Set Rng = Cells(2, i) 
     inj0(c, 2) = Rng.Offset(-1, 0).Value 
     inj0(c, 0) = Rng.Offset(3, 0).Value 
     c = c + 1 
    End If 
Next 
+0

你從哪裏得到錯誤? –

+0

在'ReDim保留inj0(c,2)'時,它表示下標超出範圍 – peetman

+6

您只能'ReDim保留'數組的_last_維度。從聯機幫助_如果使用Preserve關鍵字,則只能調整最後一個數組維度,並且無法全部更改維度數_ –

回答

0

嘗試更改代碼如下:

c = 0 
ReDim inj0(2, 0) 
inj0(1, 0) = "80" 
For i = 1 To LastCol 
    pos = InStr(Cells(2, i), "80") 
    If pos = 1 Then 
     ReDim Preserve inj0(2, c) 
     Set Rng = Cells(2, i) 
     inj0(2, c) = Rng.Offset(-1, 0).Value 
     inj0(0, c) = Rng.Offset(3, 0).Value 
     c = c + 1 
    End If 
Next 

如果你需要被交換的尺寸,終於可以apply WorksheetFunction.Transpose method