Como encontrar um valor em um array usando vba?

Ao armazenar valores em um array, pode haver momentos em que você precise fazer uma pesquisa no array. Nesse caso, você precisa conhecer os métodos que pode usar. Agora observe o código abaixo, que pode ajudá-lo a entender como pesquisar um valor em um array.

encontre um valor em uma matriz-1
  1. Na primeira parte do código você tem variáveis que você precisa usar posteriormente no código.
  2. Depois disso, a próxima parte gera números aleatórios usando RND para obter os dez valores do array.
  3. A seguir, uma caixa de entrada permite inserir o valor que deseja pesquisar na tabela.
  4. Depois disso, você tem uma linha que usa a instrução IF para verificar se o valor inserido na caixa de entrada é um número ou não.
  5. Nesta parte você tem um código para a string usar na caixa de mensagem caso o valor que você digitou não for encontrado.
  6. Esta parte do código usa um loop For (For Each) para percorrer cada elemento da matriz e verificar se o valor inserido está na matriz ou não.
  7. A última parte do código exibe uma mensagem indicando se o valor foi encontrado ou não.
 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

Adicione um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *