在VBA中删除2D数组的重复项

时间:2015-07-20 17:37:17

标签: arrays vba

我找到了很多方法来删除一维数组的重复但找不到2D示例。 除此之外,我想知道这个功能是否可以"离开"重复项的实例,而不是全部删除它们。

有可能吗?

示例:

Sub Tests()

Dim Example()

Example(0,0) = "Apple"
Example(1,0) = "Apple"
Example(0,1) = "Pear"
Example(1,1) = "Orange"

End Sub 

剩余的项目是:Apple, Pear and Orange

2 个答案:

答案 0 :(得分:0)

要处理2D数组,请使用1D数组,但在'height'循环内部使用'width'循环。

即:

for a = 1 to number_of_elements_in_first_dimension
    for y = 1 to number_of_elements_in_second_dimension
        initial_comparison_string = array(a,b)
        for x = a to number_of_elements_in_first_dimension
            for y = b + 1 to number_of_elements_in_second_dimension
                if Initial_comparison_string = array(x,y) then array(x,y) = ""
            next y
        next x

    next b
next a

对于一个非常大的2D数组,这将运行相当缓慢,但我认为你必须做这样的2个嵌套循环来获取每个值并将其与稍后出现的每个值进行比较。

答案 1 :(得分:0)

我喜欢这样做,使用单独的数组来保存唯一的项目。这可以防止循环在尝试测试时循环遍历非唯一项。

Sub Test()

Dim Example(1, 1) As String
Dim NoDups() As String
Dim I, II, III As Long

ReDim NoDups(UBound(Example, 1) * UBound(Example, 2))

For I = 0 To UBound(Example, 1)
    For II = 0 To UBound(Example, 2)
        For III = 0 To UBound(NoDups)
            If NoDups(III) = Example(I, II) Then
                Exit For
            ElseIf NoDups(III) = "" Then
                NoDups(III) = Example(I, II)
                Exit For
            End If
        Next
    Next
Next


End Sub