2012-07-26 2 views
2

J'ai un court morceau de code qui vérifie si le nombre calculé "Birthday (i, 0)" existe déjà dans le tableau "Birthday" et s'il le fait pour quitter le Pour le compteur. Existe-t-il un moyen plus simple de tester si "Birthday (i, 0)" existe déjà sans utiliser un compteur For pour vérifier chaque élément du tableau "Birthday".Vérifier si un nombre existe déjà dans un tableau VBA

Un grand merci à l'avance.

Le code est ci-dessous:

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 

Répondre

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

Publication de BlackBerry. J'ai déjà tapé la réponse. Au moment où j'ai pressé soumettre, j'ai été horrifié de remarquer que la connexion est morte sur moi lol ... Ma réponse est légèrement différente cependant :) –

+0

Ah! Retour en affaires ... LOL –

+0

Je suis partial à la méthode Match. +1 –

0

Voir si cet exemple aide? Il utilise un délimiteur pour rejoindre le tableau, puis utilise le INSTR pour trouver la valeur dans le tableau.

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 
Questions connexes