2

我有一小段代码检查计算出的数字“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
4

2 回答 2

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
于 2012-07-26T00:55:17.597 回答
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
于 2012-07-26T00:59:18.373 回答