2012-07-26 53 views
2

我有一小段代码检查数组“Birthday(i,0)”中是否已经存在数字“Birthday(i,0)”,如果它确实退出为了计数器。如果没有使用For Counter检查数组“生日”中的每个元素,“生日(i,0)”是否已存在,是否有更简单的测试方法?检查数组是否已经存在于一个VBA数组中

非常感谢提前。

的代码如下:

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 

回答

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 
+0

从黑莓发布。我已经有了答案。当我按下提交的那一刻,我惊恐地发现连接在我身上死了......我的回答虽然略有不同:) – 2012-07-26 00:57:44

+0

啊!回到商业中...... LOL – 2012-07-26 00:59:30

+0

我对偏好方法有所偏爱。 +1 – 2012-07-26 01:50:39

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 
相关问题