拆分多维数组,然后对其进行切片

时间:2014-12-11 16:04:49

标签: excel vba multidimensional-array split slice

我有一列路径:

C:\Series1\Season1\Ep1
C:\Series1\Season2\Ep1
C:\Series2\Season1\Ep1
C:\Series2\Season2\Ep1
C:\Series3\Season1\Ep1

我现在想将数组拆分成多维数组,所以最终看起来像这样:

+---+----+---------+---------+-----+
|   | 1  |    2    |    3    |  4  |
+---+----+---------+---------+-----+
| 1 | C: | Series1 | Season1 | Ep1 |
| 2 | C: | Series1 | Season2 | Ep1 |
| 3 | C: | Series2 | Season1 | Ep1 |
| 4 | C: | Series2 | Season2 | Ep1 |
| 5 | C: | Series3 | Season1 | Ep1 |
+---+----+---------+---------+-----+

然后我有一个名为unique(checkArray)的函数来检查数组中唯一值的数量。我想让这个函数逐一检查每一列。

Debug.Print uniqueValues(Column1)
Debug.Print uniqueValues(Column2)
Debug.Print uniqueValues(Column3)
Debug.Print uniqueValues(Column4)

如何将阵列放入该阵型然后检查?

3 个答案:

答案 0 :(得分:2)

enter image description here

Sub SplitMe()
    Dim values As Variant
    values = ActiveSheet.Range("A1:A5")

    If Not IsArray(values) Then _
        Exit Sub

    Dim r As Integer
    Dim parts As Variant
    Dim partsMaxLenght As Integer
    Dim splitted As Variant
    ReDim splitted(LBound(values) To UBound(values))

    For r = LBound(values) To UBound(values)
        parts = VBA.Split(values(r, 1), "\")
        ' Split always returns zero based array so parts is zero based array
        If UBound(parts) + 1 > partsMaxLenght Then _
            partsMaxLenght = UBound(parts) + 1
        splitted(r) = parts
    Next r

    Dim matrix As Variant
    Dim c As Integer
    ReDim matrix(LBound(splitted) To partsMaxLenght, LBound(splitted) To UBound(splitted))

    For r = LBound(splitted) To UBound(splitted)
        parts = splitted(r)
        For c = 0 To UBound(parts)
            matrix(c + 1, r) = parts(c)
        Next c
    Next r

    uniqueValues matrix

End Sub

Private Sub uniqueValues(matrix As Variant)
    Dim r, c
    For r = LBound(matrix, 1) To UBound(matrix, 1)
        For c = LBound(matrix, 2) To UBound(matrix, 2)
            Debug.Print matrix(r, c)
        Next c
    Next r
End Sub

Output:
C:
D:
E:
F:
H:
etc.

enter image description here

答案 1 :(得分:0)

您将以引用表格中的字段的方式引用数组。与表一样,数组也是从零开始的(意思是,第一列被引用为0而不是1)。因此,如果您的数组名为MyArray,那么您将执行以下操作:

Debug.Print MyArray(0) 
Debug.Print MyArray(1) 
Debug.Print MyArray(2)
Debug.Print MyArray(3)

别忘了你首先要把你的阵列变暗。如果您知道它有多少列,您可以像这样明确地调暗它:

Dim MyArray(0 to 3) As String

如果没有,你可以保持开放式:

Dim MyArray() As String

您必须遍历数组以获取特定行号的数据,我认为您不能以任何其他方式引用它。

答案 2 :(得分:0)

使用拆分功能拆分条目,例如

Dim episodes() As Variant
ReDim episodes(numEntries - 1) As Variant

For i = 0 to numEntries - 1
    episodes(i) = Split(paths(i), "/")
Next i

Debug.Print episodes(1)(1) ' = Series1
Debug.Print episodes(1)(2) ' = Season2

之后,确保重复应该像循环数组中的每个项目一样简单。


或者,如果您只是想查找整个路径的重复项,只需创建一个集合对象,并使用路径作为键将项目加载到集合中。如果该项已被加载,则该集合将引发错误。

On Error Goto Catch

Dim episodes as Collection
Set episodes = New Collection

For i = 0 to numEntries - 1
    episodes.add paths(i), paths(i)
Next i

Exit Sub
Catch:
    'duplicate found