2012-07-26 548 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 
相關問題