Função VBA MID

Função Excel VBA MID

A função VBA MID extrai os valores do meio da frase ou palavra fornecida. A função MID é categorizada na função String e Texto e é uma função de planilha, o que significa que para usar essa função no VBA, precisamos usar o método application.worksheet.

Existem situações em que queremos extrair o nome, o sobrenome ou o nome do meio. Nessas situações, as fórmulas da categoria TEXT são úteis para atender aos nossos requisitos. O uso desta função é igual ao da referência da planilha e a sintaxe também é a mesma.

Sintaxe

Como nossa função MID do Excel, também no VBA ela tem um conjunto semelhante de valores de sintaxe. Abaixo está a sintaxe.

  • String a Pesquisar: Isso nada mais é do que a sentença da string, ou seja, de qual string ou palavra você gostaria de extrair os valores.
  • Posição inicial: de qual posição da frase você deseja extrair. Este deve ser um valor numérico.
  • Número de caracteres a extrair: da posição inicial, quantos caracteres você deseja extrair? Este também deve ser um valor numérico.

Como usar a função VBA MID?

Você pode baixar este modelo de função VBA MID aqui - Modelo de função VBA MID

Exemplo 1

Suponha que você tenha a palavra “Hello Good Morning” e deseja extrair “Good” dessa frase. Siga as etapas abaixo para extrair o valor.

Etapa 1: primeiro crie um nome de macro.

Código:

 Sub MID_VBA_Example1 () End Sub 

Passo 2: Declare uma variável como “STRING”.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String End Sub 

Passo 3: Agora atribua um valor a esta variável por meio da função MID.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String MiddleValue = Mid (End Sub 

Etapa 4: o primeiro argumento é String, ou seja, de qual valor queremos extrair. Portanto, nosso valor é “Olá, bom dia”.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String MiddleValue = Mid ("Hello Good Morning", End Sub 

Passo 5: O próximo passo é qual é a posição inicial do personagem que você deseja extrair. Nesse caso, Bom dia começa com um 7º caractere.

Nota: O espaço também é um personagem.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String MiddleValue = Mid ("Hello Good Morning", 7 End Sub 

Etapa 6: o comprimento nada mais é do que quantos caracteres você deseja extrair. Precisamos extrair 4 caracteres aqui porque o comprimento da palavra “Bom” é de 4 caracteres.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String MiddleValue = Mid ("Hello Good Morning", 7, 4) End Sub 

Etapa 7: Concluímos a fórmula. Vamos mostrar o resultado da variável na caixa de mensagem.

Código:

 Sub MID_VBA_Example1 () Dim MiddleValue As String MiddleValue = Mid ("Olá, bom dia", 7, 4) MsgBox MiddleValue End Sub 

Passo 8: Agora execute este código manualmente ou pressione a tecla F5, a caixa de mensagem deverá mostrar a palavra “Good”.

Resultado:

Exemplo # 2

Suponha que você tenha um nome e um sobrenome juntos e a palavra seja “Ramesh, Tendulkar”. Entre o nome e o sobrenome, o caractere de separação é uma vírgula (,). Agora precisamos extrair apenas o primeiro nome.

Etapa 1: Crie uma macro e defina uma variável.

Código:

 Sub MID_VBA_Example2 () Dim FirstName As String End Sub 

Passo 2: Agora atribua um valor a esta variável por meio da função MID.

Código:

 Sub MID_VBA_Example2 () Dim FirstName As String FirstName = Mid (End Sub 

Etapa 3: Nossa string é “Ramesh.Tendulkar”, então digite esta palavra.

Código:

 Sub MID_VBA_Example2 () Dim FirstName As String FirstName = Mid ("Ramesh, Tendulkar", End Sub 

Etapa 4: como estamos extraindo, a posição inicial do nome é 1.

Código:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar",1, End Sub 

Step 5: Length of the character you can directly enter as 6 but this is not the best way. In order to determine the length lets apply one more formula called Instr.

Code:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar",1,InStr( End Sub 

Step 6: For this starting position is 1.

Code:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar",1,InStr(1, End Sub 

Step 7: String 1 is our name i.e. “Ramesh, Tendulkar”.

Code:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar",1,InStr(1,"Ramesh,Tendulkar", End Sub 

Step 8: String 2 what is the separator of first name & last name i.e. comma (,).

Code:

 Sub MID_VBA_Example2()     Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar",1,InStr(1,"Ramesh,Tendulkar",",") End Sub 

Note: Instr function will return how many characters are there in the word “Ramesh, Tendulkar” from the string 1 position to the string 2 positions i.e. until comma (,). So Instr will return 7 as the result including comma (,).

Step 9: Since Instr function returns no., of characters including comma (,) we need to minus 1 character here. So enter -1 after the close of Instr function.

Code:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar", 1, InStr(1, "Ramesh,Tendulkar", ",") - 1) End Sub 

Step 10: Now show the value of the variable in the message box.

Code:

 Sub MID_VBA_Example2() Dim FirstName As String FirstName = Mid("Ramesh,Tendulkar", 1, InStr(1, "Ramesh,Tendulkar", ",") - 1) MsgBox FirstName End Sub 

Step 11: Run this code using F5 key or you can run this code manually, we would get the first name in the message box.

Output:

Example #3

Now I will give you one assignment to solve. I have a list of First Name & Last Name.

From this list I want you to extract the first name only. All the best!!!!.

Ok, If you have tried and not able to get the result then below code would help you in this.

Code:

 Sub MID_VBA_Example3()     Dim   i   As Long For i = 2   To  15 Cells(i, 2).Value = Mid(Cells(i, 1).Value, 1, InStr(1, Cells(i, 1).Value, ",") - 1)     Next i End Sub 

Copy & Paste the above code in your module. After copying the code, run this code using the F5 key or you can run manually.

It should give the result like the below.

Things to Remember

  • Length argument in MID function is optional. If you ignore this it will take 1 as the default value.
  • In order to determine the length or starting position use Instr function along with MID function.