2014-08-29 30 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