Redimension是VBA Excel中多维数组的第一个值

时间:2014-08-29 03:04:20

标签: arrays excel vba

必须有一种更简单的方法来做到这一点。我在这个论坛上接受了一张海报的建议,他说我必须将我的多维数组设置为较高的数字,然后将其重新设置为较低的数字。但是为了使它达到正确的数字,我必须通过两个循环运行它,似乎必须有一个更简单的方法来做事情。所以我有阵列祖先,其中有几个空白,我试图摆脱它。第二个维度将始终为2.我首先通过循环运行它以确定它的无效。我称之为祖先3。然后我通过循环运行ancestors3数组并填充ancestors2数组。

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

1 个答案:

答案 0 :(得分:0)

阅读你的问题我想你想要这个:

  1. 您有一个2D数组ancestors,可能在第一维中有一些空白条目
  2. 您需要ancestors的副本,而不包含名为ancestors2
  3. 的空白行

    这是一种方法。请参阅内联注释以获取解释

    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