我有两个数组:第一个是名字,第二个是国家代码,如下例所示:
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 :(得分:0)
您可以通过重新调整它来清除0 To 9999
数组中的空值:
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
答案 1 :(得分: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