¿cómo encontrar un valor en una matriz usando vba?

Cuando almacena valores en una matriz, puede haber ocasiones en las que necesite realizar una búsqueda en la matriz. En este caso, necesita conocer los métodos que puede utilizar. Ahora mire el código a continuación que puede ayudarlo a comprender cómo buscar un valor en una matriz.

encontrar-un-valor-en-una-matriz-1
  1. En la primera parte del código tienes variables que necesitarás usar más adelante en el código.
  2. Después de eso, la siguiente parte genera números aleatorios usando RND para obtener los diez valores de la matriz.
  3. A continuación, un cuadro de entrada le permite ingresar el valor que desea buscar en la tabla.
  4. Después de eso, tiene una línea que usa la declaración IF para verificar si el valor que ingresó en el cuadro de entrada es un número o no.
  5. En esta parte tienes un código para la cadena que usarás en el cuadro de mensaje si no se encuentra el valor que ingresaste.
  6. Esta parte del código utiliza un bucle For (For Each) para recorrer cada elemento de la matriz y comprobar si el valor que ingresó está en la matriz o no.
  7. La última parte del código muestra un mensaje que indica si se encuentra el valor o no.
 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

Añadir un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *