Excel VBA Encontrar Próximo
Como no Excel, quando pressionamos CTRL + F, uma caixa de assistente aparece que nos permite pesquisar um valor na planilha fornecida e uma vez que o valor é encontrado, clicamos em localizar ao lado para encontrar o outro valor semelhante, pois é um recurso de planilha que nós também pode usá-lo no VBA como método de propriedade de aplicativo como application.findnext para os mesmos fins.
Encontrar o valor específico no intervalo mencionado é bom, mas e se o requisito for encontrar o valor com várias ocorrências. Em um dos artigos anteriores, discutimos o método “Find” no VBA e não é nada complexo, mas encontrar todas as ocorrências repetitivas só é possível com o método “Find Next” no Excel VBA.
Neste artigo, mostraremos como usar este “Find Next” no Excel VBA.
O que é Find Next no Excel VBA?
Como a palavra diz “Find Next” significa que a partir da célula encontrada, continue procurando pelo próximo valor até retornar à célula original onde iniciamos a pesquisa.
Esta é a versão avançada do método “Find” que busca apenas uma vez o valor mencionado na faixa mencionada.
Abaixo está a sintaxe do método FIND NEXT no Excel VBA.
Depois: é a palavra que procuramos.
Exemplos de método Find Next no Excel VBA
Abaixo estão os exemplos de encontrar o próximo método no Excel VBA.
Por exemplo, veja os dados abaixo.
Você pode baixar este modelo do VBA Find Next Excel aqui - VBA Find Next Excel TemplateEtapa # 1 - Nestes dados, precisamos encontrar o nome da cidade “Bangalore”. Vamos iniciar o subprocedimento no editor visual basic.
Código:
Sub RangeNext_Example () End Sub
Passo # 2 - Primeiro, declare a variável como objeto “Range”.
Código:
Sub RangeNext_Example () Dim Rng As Range End Sub
Etapa # 3 - Defina a referência para a variável do objeto como “Range (“ A2: A11 ”).
Código:
Sub RangeNext_Example () Dim Rng As Range Set Rng = Range ("A2: A12") End Sub
Como nossos dados da lista de cidades estão na faixa de células de A2 a A11 nesta faixa, apenas vamos pesquisar a cidade “Bangalore”.
Uma vez que definimos a referência de intervalo para a variável “Rng”, usamos esta variável em vez de usar RANGE (“A2: A11”) todas as vezes.
Etapa 4 - Use a variável RNG e abra o método Find.
Código:
Sub RangeNext_Example () Dim Rng As Range Set Rng = Range ("A2: A12") Rng.Find End Sub
Etapa 5 - O primeiro argumento do método FIND é “O que”, ou seja, o que estamos tentando pesquisar no intervalo mencionado, portanto, o valor que estamos pesquisando é “Bangalore”.
Código:
Sub RangeNext_Example () Dim Rng As Range Set Rng = Range ("A2: A12") Rng.Find What: = "Bangalore" End Sub
Passo # 6 - Para mostrar em qual célula encontramos este valor, declare mais uma variável como uma string.
Código:
Sub RangeNext_Example () Dim Rng As Range Dim CellAdderess As String Set Rng = Range ("A2: A12") Rng.Find What: = "Bangalore" End Sub
Etapa # 7 - Para esta variável, atribua o endereço da célula encontrada.
Código:
Sub RangeNext_Example () Dim Rng As Range Dim CellAdderess As String Set Rng = Range ("A2: A12"). Find (What: = "Bangalore") Rng.Find What: = "Bangalore" CellAddress = Rng.Address End SubNota: RNG.Address porque RNG terá a referência para a célula de valor encontrado.
Etapa # 8 - Agora mostre o resultado da variável de endereço de célula atribuída na caixa de mensagem no VBA.
Sub RangeNext_Example () Dim Rng As Range Dim CellAdderess As String Set Rng = Range ("A2: A12"). Find (What: = "Bangalore") Rng.Find What: = "Bangalore" CellAddress = Rng.Address MsgBox CellAddress End Sub
Etapa # 9 - Execute o código e veja o que temos aqui.
Portanto, encontramos o valor “Bangalore” na célula A5. Com o método Find, podemos encontrar apenas uma célula, portanto, em vez de FIND, precisamos usar FIND NEXT no Excel VBA.
Etapa # 10 - Precisamos fazer referência à variável de objeto de intervalo, mas usando o método FIND NEXT no Excel VBA.
Código:
Sub RangeNext_Example () Dim Rng As Range Dim CellAdderess As String Set Rng = Range ("A2: A12"). Find (What: = "Bangalore") Rng.Find What: = "Bangalore" CellAddress = Rng.Address MsgBox CellAddress Set Rng = Range ("A2: A12"). FindNext (Rng) End Sub
Como você pode ver acima, usamos o método VBA FIND NEXT, mas dentro da função, usamos um nome de variável de objeto de intervalo.
Etapa # 11 - Agora atribua novamente o endereço da célula e mostre o endereço na caixa de mensagem.
Código:
Sub RangeNext_Example() Dim Rng As Range Dim CellAdderess As String Set Rng = Range("A2:A12").Find(What:="Bangalore") Rng.Find What:="Bangalore" CellAddress = Rng.Address MsgBox CellAddress Set Rng = Range("A2:A12").FindNext(Rng) CellAddress = Rng.Address MsgBox CellAddress End Sub
Step#12 – Run the macro and see what we get in the first message box.
Step#13 – The first message box shows the value “Bangalore” found in the cell A5, click on the Ok button to see the next found value.
The second value found in A7 cell, press Ok to continue.
VBA Find Next (Using Loop)
It will exit the VBA subprocedure but we are one more to be found in cell A10. When the values are to be found in more than one cell then it is a better idea to use loops.
In this case, too we have value “Bangalore” in more than one cell, so we need to include loops here.
Step#14 – First, declare two variables as the range.
Code:
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range End Sub
Step#15 – Set the reference for the first variable as shown below.
Code:
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range Set Rng = Range("A2:A11").Find(What:="Bangalore") End Sub
Step#16 – For the second variable set the reference by using the FIND VBA function.
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range Set Rng = Range("A2:A11").Find(What:="Bangalore") Set FindRng = Rng.FindNext("Bangalore") End Sub
Step#17 – Before we start searching for the value we need to identify from which cell we are starting the search, for that declares the variable as a string.
Code:
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range Set Rng = Range("A2:A11").Find(What:="Bangalore") Set FindRng = Rng.FindNext("Bangalore") Dim FirstCell As String FirstCell = Rng.Address End Sub
Step#18 – For this variable assign the first cell address.
Code:
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range Set Rng = Range("A2:A11") Set FindRng = Rng.Find(What:="Bangalore") Dim FirstCell As String FirstCell = Rng.Address End Sub
Step#19 – Now we need to include the “Do While” loop to loop through all the cells and find the searching value.
Code:
Sub RangeNext_Example1() Dim Rng As Range Dim FindRng As Range Set Rng = Range("A2:A11").Find(What:="Bangalore") Set FindRng = Rng.FindNext("Bangalore") Dim FirstCell As String FirstCell = Rng.Address Do Loop While FirstCell Cell.Address End Sub
Inside the loop mention the message box and VBA FIND NEXT method.
Step#20 – Below is the complete code for you.
Code:
Sub FindNext_Example() Dim FindValue As String FindValue = "Bangalore" Dim Rng As Range Set Rng = Range("A2:A11") Dim FindRng As Range Set FindRng = Rng.Find(What:=FindValue) Dim FirstCell As String FirstCell = FindRng.Address Do MsgBox FindRng.Address Set FindRng = Rng.FindNext(FindRng) Loop While FirstCell FindRng.Address MsgBox "Search is over" End Sub
Step#21 – This will keep showing all the matching cell address and in the end, it will show the message as “Search is Over” in the new message box.
Things to Remember
- FIND method can find only one value at a time.
- FIND NEXT in excel VBA can find the next value from the already found value cell.
- Use Do While loop to loop through all the cells in the range.