2015-07-20 171 views
0

我發現了很多刪除一維數組重複的方法,但找不到二維的例子。 除此之外,我想知道功能是否可以「離開」重複項目的一個實例,而不是全部刪除它們。刪除VBA中的二維數組的副本

是否可以做到這一點?

實施例:

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

+0

當你說重複的時候,你的意思是整行是相同的還是隻是重複的?如果行或列不一定相同,那麼爲什麼你使用2d數組作爲這個數據? – Evan

+0

因爲它們相互對應,就像Array(Apple,redcolor) – AndroidDev

回答

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 
0

要通過2D陣列工作,做,你會與一維數組,但與內部的「寬度」環中的'高度'循環。

即:

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 

這將具有非常大的二維數組,運行很慢,但我認爲你必須做2個嵌套循環像這樣把每個值並將其與每個值稍後出現。