SubString VBA

Excel VBA SubString

SubString é uma parte da string ou parte ou o caractere da string é chamado de “SubString”. Existem três tipos de função substring no VBA LEFT, RIGHT e MID; eles são semelhantes às substrings da planilha no Excel.

Uma string nada mais é do que uma série de caracteres e os caracteres podem ser alfabetos, números, caracteres especiais e também combinar todos eles.

Freqüentemente, no Excel, quando trabalhamos com dados que são a string, precisamos obter apenas a parte da string para facilitar nosso propósito. Podemos não precisar que a string inteira seja usada, mas precisamos apenas da parte da string para nosso uso. Por exemplo, se você tem o nome “Sachin Tendulkar”, pode precisar apenas da primeira parte do nome, ou seja, apenas “Sachin”. Isso é chamado de SubString da string no Excel VBA. Para lidar com essas strings, temos funções embutidas na função TEXT na categoria Excel.

Neste artigo, discutiremos como obter a substring da string completa no VBA.

Como usar funções SubString no VBA?

Para extrair a substring da string, temos algumas das funções de texto embutidas e algumas das funções importantes são LEFT, RIGHT, INSTR e MID no Excel. A função Instr servirá como função de suporte para as outras três funções.

Veremos como usar essas funções para extrair as substrings de forma prática. Leia os exemplos abaixo para entendê-los.

Você pode baixar este modelo VBA SubString Excel aqui - VBA SubString Excel Template

Exemplo # 1 - Usando a função esquerda

Se você tiver o nome completo como “Sachin Tendulkar” e precisar apenas do primeiro nome a ser extraído como substring, use o código a seguir para obter o mesmo.

Etapa 1: Crie um nome de macro e defina duas variáveis ​​como String.

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String End Sub 

Passo 2: Agora atribua o nome “Sachin Tendulkar” à variável FullName .

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String FullName = "Sachin Tendulkar" End Sub 

Passo 3: Agora a variável FullName contém o valor de “Sachin Tendulkar”. Agora, precisamos extrair a substring VBA do Excel do primeiro nome do nome completo. Portanto, atribua o valor para a variável FirstName por meio da função LEFT.

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String FullName = "Sachin Tendulkar" FirstName = Left (End Sub 

Passo 4: O primeiro argumento da função VBA LEFT é String, que é o valor completo ou string completa. Neste exemplo, nosso valor completo ou string é “Sachin Tendulkar”, que é atribuído à variável FullName.

Portanto, forneça a variável FullName como argumento.

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String FullName = "Sachin Tendulkar" FirstName = Left End Sub 

Etapa 5: O próximo  argumento é quantos caracteres precisamos da string que fornecemos, então, neste caso, precisamos do primeiro nome “ Sachin ”, então precisamos de 6 caracteres do lado esquerdo.

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String FullName = "Sachin Tendulkar" FirstName = Left (FullName, 6) End Sub 

Etapa 6: Agora mostre o resultado em uma caixa de mensagem em VBA.

Código:

 Sub SubString_Example1 () Dim FullName As String Dim FirstName As String FullName = "Sachin Tendulkar" FirstName = Left (FullName, 6) MsgBox FirstName End Sub 

Etapa 7: execute a macro para ver o primeiro nome como uma substring na caixa de mensagem.

Exemplo 2 - Obter SubString da direita

Assim como extraímos a substring da esquerda, podemos extrair da direita também. Pegue o mesmo nome como exemplo.

Etapa 1: Defina duas variáveis ​​como String.

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String End Sub 

Etapa 2: Como de costume, atribua o valor à variável FullName como “Sachin Tendulkar”

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String FullName = "Sachin Tendulkar" End Sub 

Passo 3: Agora para a variável LastName atribua o valor por meio da função excel RIGHT.

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String FullName = "Sachin Tendulkar" LastName = Right (End Sub 

Etapa 4: String é nosso FullName, portanto, forneça a variável.

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String FullName = "Sachin Tendulkar" LastName = Right (FullName, End Sub 

Etapa 5: Comprimento é quantos caracteres precisamos do lado direito, precisamos de 9 caracteres do lado direito.

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String FullName = "Sachin Tendulkar" LastName = Right (FullName, 9) End Sub 

Etapa 6: Mostrar este valor na caixa de mensagem .

Código:

 Sub SubString_Example2 () Dim FullName As String Dim LastName As String FullName = "Sachin Tendulkar" LastName = Right (FullName, 9) MsgBox LastName End Sub 

Etapa 7: Execute a macro e veremos o sobrenome na caixa de mensagem.

Exemplo # 3 - Usando a função Instr

In the above examples, we had only one name and we have directly supplied how many characters we need from the left & right. But in case of many names first name & last name characters are not the same, it will differ from name to name. In those cases, we cannot supply the number of characters directly so we can use the function Instr.

Instr function will return the supplied character position in the string. For an example look at the below code.

Code:

 Sub SubString_Example3() Dim Position As String Position = InStr(1, "Sachin", "a") MsgBox Position End Sub 

InStr(1, “Sachin”, “a”) this will identify the position of the letter “a” as the first appearance in the string “Sachin”. In this case letter “a” is in the second position. So we will get 2 as the result in the message box.

Like this, we can use the Instr function to find the space character between the first name and last name.

For an example look at the below name I have in excel sheet.

Using LEFT, RIGHT, and Instr function we can extract the substrings. Below is the code to extract the First Name.

Code:

 Sub FirstName() Dim K As Long Dim LR As Long LR = Cells(Rows.Count, 1).End(xIUp).Row For K = 2 To LR Cells(K, 2).Value = Left(Cells(K, 1).Value, InStr(1, Cells(K, 1).Value, "") - 1) Next K End Sub 

Run the macro and see the first name as a substring in the message box.

Use below code to extract the last name as a substring.

Code:

 Sub LastName() Dim K As Long Dim LR As Long LR = Cells(Rows.Count, 1).End(xIUp).Row For K = 2 To LR Cells(K, 3).Value = Right(Cells(K, 1).Value, Len(Cells(K, 1)) - InStr(1, Cells(K, 1).Value, "")) Next K End Sub 

Run the macro and we will see the last name in the message box.

I have assigned the macro button to the worksheet, download the workbook, and use them.