VBA FIND NEXT - Como usar a função FindNext no Excel VBA?

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 ele 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 a partir da célula encontrada, continuar 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 como encontrar o próximo método no Excel VBA.

Por exemplo, observe os dados abaixo.

Etapa 1 - Nestes dados, precisamos encontrar o nome da cidade “Bangalore”. Vamos iniciar o subprocedimento no editor visual básico.

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 quê", 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 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 Sub
Nota: RNG. Endereço porque RNG terá como referência 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

Step#9 - Run the code and see what we get here.

So we have found the value “Bangalore” in the cell A5. With the Find method, we can find only one cell, so instead of FIND, we need to use FIND NEXT in excel VBA.

Step#10 - We need to reference the range object variable but by using the FIND NEXT method in excel VBA.

Code:

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

As you can see above, we have used the VBA FIND NEXT method, but inside the function, we have used a range object variable name.

Step#11 - Now again, assign the cell address and show the address in the message box.

Code:

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 enquanto FirstCell FindRng.Address MsgBox "A pesquisa acabou" End Sub

Etapa # 21 - Isso continuará mostrando todos os endereços de células correspondentes e, no final, mostrará a mensagem “Pesquisa acabou” na nova caixa de mensagem.

Coisas para lembrar

  • O método FIND pode encontrar apenas um valor de cada vez.
  • FIND NEXT no excel VBA pode encontrar o próximo valor da célula de valor já encontrada.
  • Use o loop Do While para percorrer todas as células no intervalo.

Artigos interessantes...