Come trovare un valore in un array usando vba?

Quando memorizzi valori in un array, potrebbero esserci momenti in cui è necessario eseguire una ricerca nell’array. In questo caso, è necessario conoscere i metodi che è possibile utilizzare. Ora guarda il codice seguente che può aiutarti a capire come cercare un valore in un array.

trova-un-valore-in-un-array-1
  1. Nella prima parte del codice hai delle variabili che dovrai utilizzare più avanti nel codice.
  2. Successivamente, la parte successiva genera numeri casuali utilizzando RND per ottenere i dieci valori dall’array.
  3. Successivamente, una casella di input ti consente di inserire il valore che desideri cercare nella tabella.
  4. Successivamente, hai una riga che utilizza l’ istruzione IF per verificare se il valore inserito nella casella di input è un numero o meno.
  5. In questa parte hai un codice per la stringa da utilizzare nella finestra di messaggio se il valore inserito non viene trovato.
  6. Questa parte del codice utilizza un ciclo For (For Each) per scorrere ogni elemento nell’array e verificare se il valore immesso è nell’array o meno.
  7. L’ultima parte del codice visualizza un messaggio che indica se il valore è stato trovato o meno.
 Option Base 1 Sub vba_array_search() 'this section declares an array and variables 'that you need to search within the array. Dim myArray(10) As Integer Dim i As Integer Dim varUserNumber As Variant Dim strMsg As String 'This part of the code adds 10 random numbers to 'the array and shows the result in the 'immediate window as well. For i = 1 To 10 myArray(i) = Int(Rnd * 10) Debug.Print myArray(i) Next i 'it is an input box that asks 'you the number that you want to find Loopback: varUserNumber = InputBox _ ("Enter a number between 1 and 10 to search for:", _ "Linear Search Demonstrator") 'it's an if statement that checks for the value that you 'have entered in the input box. If varUserNumber = "" Then End If Not IsNumeric(varUserNumber) Then GoTo Loopback If varUserNumber < 1 Or varUserNumber > 10 Then GoTo Loopback 'message to show if the value doesn't found. strMsg = "Your value, " & varUserNumber & _ ", was not found in the array." 'loop through the array and match each value with the 'the value you have entered in the input box. For i = 1 To UBound(myArray) If myArray(i) = varUserNumber Then strMsg = "Your value, " & varUserNumber & _ ", was found at position " & i & " in the array." Exit For End If Next i 'message box in the end MsgBox _ strMsg, vbOKOnly + vbInformation, _ "Linear Search Result" End Sub

Aggiungi un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *