2014-08-29 118 views
0

必須有更簡單的方法來完成此操作。我在這個論壇上接受了一個海報的建議,他說我必須將我的多維數組設置爲較高的數字,然後將其重新設置爲較小的數字。但爲了讓它達到正確的數字,我必須通過兩個循環來運行它,似乎必須有一個更簡單的方法來完成任務。所以我有陣列的祖先,其中有幾個空白,我試圖擺脫。第二個維度總是2.我首先通過一個循環來確定它的ubound。我稱之爲祖先3。然後我通過循環運行ancestors3數組並填充ancestors2數組。Redimension VBA中多維數組的第一個值Excel

For s = 1 To UBound(ancestors, 1) 
temp_ancest = ancestors(s, 1) 
If temp_ancest <> "" Then 
    uu = uu + 1 
    ReDim Preserve ancestors3(uu) 
    ancestors3(uu) = temp_ancest 
End If 
Next 

Dim ancestors2() 
ReDim ancestors2(UBound(ancestors3), 2) 

For s = 1 To UBound(ancestors3, 1) 
temp_ancest = ancestors(s, 1) 
temp_ancest2 = ancestors(s, 2) 
If temp_ancest <> "" Then 
    y = y + 1 
    ancestors2(y, 1) = temp_ancest 
    ancestors2(y, 2) = temp_ancest2 
End If 
Next 
+0

是否確定此代碼是給你所需的輸出。第二個循環沒有多大意義......也有太多'Redim Preserve'執行(這些效率非常低)。你能否展示一個非常簡單的例子,比如'ancestors(1,1)=「a1」,祖先(1,2)=「b1」'等等 - >以及你想在祖先中看到的結果2 (1,1)'等。 – hnk 2014-08-29 03:47:26

+0

不明白你的意思。 – user147178 2014-08-29 03:50:19

+1

請舉例說明樣本輸入和期望輸出。你可以在你的問題結尾添加。 – hnk 2014-08-29 03:51:39

回答

0

讀你的問題,我想你想的:

  1. 你有一個二維數組ancestors可在第一維
  2. 你想要的ancestors副本沒有那些空白的一些空白項行,稱爲ancestors2

這裏有一種方法可以做到這一點。請參閱行內意見解釋

Sub Demo() 
    Dim ancestors As Variant 
    Dim ancestors2 As Variant 
    Dim i As Long, j As Long 
    Dim LB as long 

    ' Populate ancestors as you see fit 
    '... 


    ' crate array ancestors2, same size as ancestors, but with dimensions flipped 
    ' so we can redim it later 
    ReDim ancestors2(LBound(ancestors, 2) To UBound(ancestors, 2), _ 
     LBound(ancestors, 1) To UBound(ancestors, 1)) 

    ' Loop ancestors array, copy non-blank items to ancestors2 
    j = LBound(ancestors, 1) 
    LB = LBound(ancestors, 1) 
    For i = LBound(ancestors, 1) To UBound(ancestors, 1) 
     If ancestors(i, 1) <> vbNullString Then 
      ancestors2(LB, j) = ancestors(i, LB) 
      ancestors2(LB + 1, j) = ancestors(i, LB + 1) 
      j = j + 1 
     End If 
    Next 

    ' Redim ancestors2 to match number of copied items 
    ReDim Preserve ancestors2(LBound(ancestors2, 1) To UBound(ancestors2, 1), _ 
     LBound(ancestors2, 2) To j - 1) 

    ' Transpose ancestors2 to restore flipped dimensions 
    ancestors2 = Application.Transpose(ancestors2) 
End Sub