Função direita do VBA (exemplos) - Guia passo a passo para Excel VBA Right

Função certa no VBA Excel

A função direita é a mesma que na função de planilha e no VBA, o uso desta função é que ela nos fornece a substring de uma determinada string, mas a pesquisa é feita da direita para a esquerda da string, este é um tipo de função de string no VBA usado com o método de função application.worksheet.

A função RIGHT no Excel VBA é usada para extrair caracteres do lado direito dos valores de texto fornecidos. No Excel, temos muitas funções de texto para lidar com dados baseados em texto. Algumas das funções úteis são LEN, LEFT, RIGHT, MID função para extrair caracteres dos valores de texto. O exemplo comum de usar essas funções é extrair o nome e o sobrenome separadamente do nome completo.

A fórmula CERTA também está lá na planilha. No VBA, precisamos contar com a classe de função de planilha para acessar a função VBA RIGHT; em vez disso, temos a função RIGHT embutida no VBA também.

Agora dê uma olhada na sintaxe abaixo da fórmula VBA RIGHT.

  • String: Este é o nosso valor e, a partir desse valor, estamos tentando extrair os caracteres do lado direito da string.
  • Comprimento: da String fornecida , de quantos caracteres precisamos. Se precisarmos de quatro caracteres do lado direito, podemos fornecer o argumento como 4.

Por exemplo, se a string for “Telefone Móvel” e se quisermos extrair apenas a palavra “Telefone”, podemos fornecer o argumento como o abaixo.

DIREITO (“Telefone celular”, 5)

A razão pela qual mencionei 5 é porque a palavra “Telefone” contém 5 letras. Na próxima seção do artigo, veremos como podemos usá-lo no VBA.

Exemplos de função correta do Excel VBA

A seguir estão os exemplos de Right Function VBA Excel.

Exemplo 1

Vou mostrar um exemplo simples para iniciar o processo. Suponha que você tenha a string “New York” e se quiser extrair 3 caracteres da direita, siga as etapas abaixo para escrever o código.

Etapa 1: Declare a variável como String VBA.

Código:

Sub Right_Example1 () Dim k As String End Sub

Passo 2: Agora, para esta variável, atribuiremos o valor aplicando a função RIGHT.

Código:

Sub Right_Example1 () Dim k As String k = Right (End Sub

Etapa 3: o primeiro argumento é String, e nossa string para este exemplo é “New York”.

Código:

Sub Right_Example1 () Dim k As String k = Right ("New York", End Sub

Etapa 4: a seguir, quantos caracteres precisamos da string fornecida. Neste exemplo, precisamos de 3 caracteres.

Código:

Sub Right_Example1 () Dim k As String k = Right ("New York", 3) End Sub

Etapa 5: temos 2 argumentos para lidar, então pronto. Agora atribua o valor desta variável na caixa de mensagem em VBA.

Código:

Sub Right_Example1 () Dim k As String k = Right ("Nova York", 3) MsgBox k End Sub

Execute o código usando a tecla F5 ou manualmente e veja o resultado em uma caixa de mensagem.

Na palavra "Nova York" do lado direito, três caracteres são "ork".

Agora vou alterar o comprimento de 3 para 4 para obter o valor total.

Código:

Sub Right_Example1 () Dim k As String k = Right ("Nova York", 4) MsgBox k End Sub

Execute este código manualmente ou usando a tecla F5. Em seguida, obteremos “York”.

Exemplo # 2

Agora, dê uma olhada em mais um exemplo, desta vez considere o valor da string como “Michael Clarke”.

Se você fornecer o comprimento como 6, obteremos “Clarke” como resultado.

Código:

Sub Right_Example1 () Dim k As String k = Right ("Michael Clarke", 6) MsgBox k End Sub

Execute este código usando a tecla F5 ou manualmente para ver o resultado.

Função Dynamic Right no Excel VBA

If you observe our previous two examples, we have supplied the length argument numbers manually. But this is not the right process to do the job.

In each of the string, right-side characters are different in each case. We cannot refer to the length of the characters manually for each value differently. This where the other string function “Instr” plays a vital role.

Instr function returns the supplied character position in the supplied string value. For example, Instr (1,” Bangalore,” a”) returns the position of the letter “a” in the string “Bangalore” from the first (1) character.

In this case, the result is 2 because from the first character position of the letter “a” is the 2nd position.

If I change the starting position from 1 to 3, it will return 5.

Instr (3,” Bangalore,” a”).

The reason why it returns 5 because I mentioned the starting position to look for the letter “a” only from the 3rd letter. So the position of the second appeared “a” is 5.

So, to find the space character of each string, we can use this. Once we find the space character position, we need to minus that from the total length of the string by using LEN.

For example, in the string “New York,” the total number of characters is 8, including space, and the position of the space character is 4th. So 8-4 = 4 right will extract 4 characters from the right.

Now, look at the below code for your reference.

Code:

Sub Right_Example3() Dim k As String Dim L As String Dim S As String L = Len("Michael Clarke") S = InStr(1, "Michael Clarke", " ") k = Right("Michael Clarke", L - S) MsgBox k End Sub

In the above code variable, “L” will return 14, and the variable “S” will return 8.

In the VBA right formula, I have applied L - S, i.e., 14-8 = 6. So from right side 6 characters, i.e., “Clarke.”

Loops with Right Function in Excel VBA

When we need to apply the VBA RIGHT function with many cells, we need to include this inside the loops. For example, look at the below image.

We cannot apply many lines of the code to extract a string from the right side. So we need to include loops. The below code will do it for the above data.

Code:

Sub Right_Example4 () Dim k As String Dim L As String Dim S As String Dim a As Integer For a = 2 A 5 L = Len (Cells (a, 1) .Value) S = InStr (1, Cells (a, 1) ) .Value, "") Cells (a, 2) .Value = Right (Cells (a, 1), L - S) Next a End Sub

O resultado deste código é o seguinte.

Artigos interessantes...