2016-11-18 29 views
0

VBA動態數組我有兩個數組:在第一個的名字,並在第二個有國家代碼這樣的例子:沒有空的空間

array1(0)="Peter"  array2(0)="EN" 
array1(1)="John"  array2(1)="US" 
array1(2)="Sandra" array2(2)="FR" 
array1(3)="Margot" array2(3)="DE" 

現在,我想從一個入口檢查在文本框1中,如果它的「FR」在我的數組中可用,如果是,則將這些位置保存在第三個新數組中。

我的代碼看起來像這樣,但它非常糟糕,它不能按我想要的方式工作。現在

Dim name(0 To 9) As String 

array1(0) = "Peter" 
array1(1) = "John" 
array1(2) = "Sandra" 
array1(3) = "Margot" 

Dim county(0 To 9) 

county(0) = "EN" 
county(1) = "US" 
county(2) = "FR" 
county(3) = "DE" 

'Dim ArrayCounter 
ArrayCounter = 0 

Dim VarArray(9999) 

For i = 0 To 9 
    If county(i) = "DE" Then 
     'ArrayCounter = ArrayCounter + 1 
     'MsgBox (array1(i)) 

     VarArray(ArrayCounter) = i 
     ArrayCounter = ArrayCounter + 1 

    End If 
Next i 

MsgBox (UBound(VarArray)) 

,如果我檢查的第三陣列,該陣列必須是這樣的:

array3(0)=2 'position of FR in my second array 
+0

「它不工作就像我想要的」不是很有幫助。究竟是什麼問題?你說你想'array3(0)= 2',但在你的代碼中你使用'varArray'並搜索''de「'所以它應該是'varArray(0)= 3'? – arcadeprecinct

+0

@arcadeprecinct,我在描述中改變了它。我得到一個陣列白空扇區,我只想要不空的扇區。 – ManInTheMiddle

+0

你是什麼意思的「空白部門」?由於你的代碼現在,'varArray'應該保持爲空,因爲'「de」'不同於'「DE」' – arcadeprecinct

回答

0

您可以在0 To 9999陣列擺脫空值由redimming它:

If ArrayCounter > 0 Then 
    ReDim Preserve varArray(0 to ArrayCounter - 1) 'Preserve is important because otherwise it will delete the values 
Else 
    'do what you want to do if no match was found 
End If 
0

你可能是以下後:

Sub main() 

    Dim names(0 To 9) As String 
    names(0) = "Peter" 
    names(1) = "John" 
    names(2) = "Sandra" 
    names(3) = "Margot" 

    Dim county(0 To 9) As String 
    county(0) = "EN" 
    county(1) = "US" 
    county(2) = "FR" 
    county(3) = "DE" 

    Dim ArrayCounter As Long 
    ArrayCounter = 0 

    Dim foundArray As Variant 
    foundArray = county '<--| "copy" the 'county' array into 'foundArray', since this latter won't be bigger than the former 

    Dim iFound As Long, iCounty As Long 
    iFound = -1 
    For iCounty = LBound(county) To UBound(county) 
     If county(iCounty) = "DE" Then 
      iFound = iFound + 1 '<-- update the 'foundArray' current counter 
      foundArray(iFound) = iCounty '<-- update the 'foundArray' current counter content 
     End If 
    Next iCounty 
    If iFound >= 0 Then 
     ReDim Preserve foundArray(0 To iFound) '<--| if any values have been found, resize 'foundArray' up to the found items counter 
    Else 
     Erase foundArray '<--| otherwise erase it 
    End If 
End Sub