我有一段代码,用于检查计算出的数字“Birthday(i,0)”是否已存在于数组“Birthday”中,是否确实退出For计数器。是否有一种更简单的测试方法,如果“Birthday(i,0)”已经存在而没有使用For Counter来检查数组“Birthday”的每个元素。
非常感谢提前。
代码如下:
For i = 1 To MaxPeople
Birthday(i, 0) = WorksheetFunction.RoundUp(Rnd() * 365, 0)
For j = 1 To i - 1
If Birthday(i, 0) = Birthday(j, 0) Then
NumberofPeople = i
Exit For
End If
Next j
If NumberofPeople > 0 Then Exit For
Next i
答案 0 :(得分:3)
Dim rv
'find the position of a value in the first dimension of an array
rv = Application.Match(yourDate, Application.Index(Birthday, 0, 1), 0)
'if not found, rv will be an error value
If IsError(rv) Then
Debug.Print "Not found"
Else
Debug.Print "Found at pos " & rv
End If
答案 1 :(得分:0)
看看这个例子是否有帮助?它使用分隔符连接数组,然后使用INSTR
查找数组中的值。
Sub Sample()
Dim n As Long
Dim MyArray(5, 0) As Long
Dim Delim As String
n = 4
Delim = Chr$(1)
MyArray(0, 0) = 2
MyArray(1, 0) = 3
MyArray(2, 0) = 4
MyArray(3, 0) = 5
MyArray(4, 0) = 1
If InStr(1, Delim & Join(WorksheetFunction.Transpose(MyArray), Delim) & _
Delim, Delim & n & Delim, 1) Then
Debug.Print "Exists"
Else
Debug.Print "Does Not Exist"
End If
End Sub