Vba excel срезы строк

Извлечение (вырезание) части строки с помощью кода VBA Excel из значения ячейки или переменной. Функции Left, Mid и Right, их синтаксис и аргументы. Пример.

Эта функция извлекает левую часть строки с заданным количеством символов.

Синтаксис функции Left:

Left(строка, длина)

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается левая часть;
  • длина — обязательный аргумент: числовое выражение, указывающее количество извлекаемых символов.

Если аргумент «длина» равен нулю, возвращается пустая строка. Если аргумент «длина» равен или больше длины строки, возвращается строка полностью.

Функция Mid

Эта функция извлекает часть строки с заданным количеством символов, начиная с указанного символа (по номеру).

Синтаксис функции Mid:

Mid(строка, начало, [длина])

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается часть строки;
  • начало — обязательный аргумент: числовое выражение, указывающее положение символа в строке, с которого начинается извлекаемая часть;
  • длина — необязательный аргумент: числовое выражение, указывающее количество вырезаемых символов.

Если аргумент «начало» больше, чем количество символов в строке, функция Mid возвращает пустую строку. Если аргумент «длина» опущен или его значение превышает количество символов в строке, начиная с начального, возвращаются все символы от начальной позиции до конца строки.

Функция Right

Эта функция извлекает правую часть строки с заданным количеством символов.

Синтаксис функции Right:

Right(строка, длина)

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается правая часть;
  • длина — обязательный аргумент: числовое выражение, указывающее количество извлекаемых символов.

Если аргумент «длина» равен нулю, возвращается пустая строка. Если аргумент «длина» равен или больше длины строки, возвращается строка полностью.

Пример

В этом примере будем использовать все три представленные выше функции для извлечения из ФИО его составных частей. Для этого запишем в ячейку «A1» строку «Иванов Сидор Петрович», из которой вырежем отдельные компоненты и запишем их в ячейки «A2:A4».

Sub Primer()

Dim n1 As Long, n2 As Long

Range(«A1») = «Иванов Сидор Петрович»

‘Определяем позицию первого пробела

n1 = InStr(1, Range(«A1»), » «)

‘Определяем позицию второго пробела

n2 = InStr(n1 + 1, Range(«A1»), » «)

‘Извлекаем фамилию

Range(«A2») = Left(Range(«A1»), n1 1)

‘Извлекаем имя

Range(«A3») = Mid(Range(«A1»), n1 + 1, n2 n1 1)

‘Извлекаем отчество

Range(«A4») = Right(Range(«A1»), Len(Range(«A1»)) n2)

End Sub

На практике часто встречаются строки с лишними пробелами, которые необходимо удалить перед извлечением отдельных слов.

Welcome to this article on the VBA Left, Right and Mid string functions. In this post, I will show you when to use these functions and equally importantly when to avoid using them. If you use them for the wrong type of tasks(i.e. extracting from variable strings), you can waste a considerable amount of time.

I will also cover a little-known feature of the Mid function where you can update the original string using Mid.

Syntax of Left, Right and Mid functions

These three functions all have a very similar purpose and that is to extract text from a text string. You can see the syntax of these functions in this table:

Function Parameters Description Example
Left string, length Return chars from left side Left(«John Smith»,4)
Right string, length Return chars from right side Right(«John Smith»,5)
Mid string, start, length Return chars from middle Mid(«John Smith»,3,2)

Introduction

First of all, what is a string? A string is a piece of text. You can see examples below:

text = "Mary had a little lamb"
text = "John Smith"
text = "Customer 234-AA=56"

We call the variable type String in VBA and it is equivalent to text in a cell on a spreadsheet.

So let’s get started by setting up a simple piece of code so that we can use to show the results of these string functions. First of all, we create the text variable, and then we assign some text to it:

Dim text As string
text = "Mary had a little lamb"

Then we create a variable and this variable will store the result of the Left, Right or Mid function. We start by assigning the text string to the variable without making any changes:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' set result to have the same text
    result = text
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code by clicking in the sub and pressing F5(this is the same as selecting Run->Run Sub/UserForm from the menu.)

You can see that both strings were shown in the Immediate window:

(Note: If the Immediate window is not visible then select View->Immediate Window from the menu or Ctrl + G)

So now that we have our basic code in place. Let’s go ahead and use it to show how these functions work.

Left Function

The Left function is possibly the simplest function in VBA. It returns a given number of characters from the left of a string. All you have to do it to tell it the number of characters that you want to get.
Syntax
Left(String, Length)

Example
Left(“abcdef”, 3)

Result
“abc”

The key thing to remember is that the original string is not changed. We get the result of the Left function and we store it in a different string. The original string remains the same.

In the following example, we’re going to return the first four characters of the string, which are Mary:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 4)
    
    ' Print the result to the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

If we change 4 to 8, you will see that the function now returns the first eight characters of the string:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 8)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

If we use a value greater than the length of the string, then the entire string is returned. For example, in the next example, we use 100 with the Left function and you can see that the entire string has been returned:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 100)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

That is the Left function and you can see that it is pretty straightforward to use.

Right Function

The Right function is also very straightforward and it is very similar to the Left function. The difference is that it extracts characters from the right side of the string rather than from the left side. Right takes the same parameters as Left. It takes the string to extract from and the number of characters that you wish to extract:

Syntax
Right(String, Length)

Example
Right(“abcdef”, 3)

Result
“def”

Let’s change the code that we were using with Left. We replace the Left function with the Right function and set the length to 4:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Right function in the result variable
    result = Right(text, 4)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run this code and you can see that it has returned the last four characters of the string:
VBA Right

Let’s try another example, this time we’re changing the length to 11:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
     ' store the result of the Right function in the result variable
    result = Right(text, 11)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code, now you can see that it returns the characters little lamb which are the last 11 characters:

VBA Right

Let’s try one more thing. This time we’re changing the length to 100 which is a number greater than the length of the entire string:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
     ' store the result of the Right function in the result variable
    result = Right(text, 100)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code, now you can see that it returns the entire string:

That means that anytime we supply a length that is greater than the length of the string, it will return the entire string.

That is how we use the Right function. As you can see it is very similar to the Left function and quite simple to use.

Mid Function

Now we are going to take a look at the Mid function. The Mid function extracts text from the middle of the string, just as the name implies:

Syntax
Mid(String, Start, Length)

Example
Mid(“abcdef”, 2, 3)

Result
“bcd”

The Mid function is very similar to the Left function. The main difference between Mid and Left is that Mid has one extra parameter – Start. The Start parameter is used to specify where the starting position is in the string:

Syntax
Mid(String, Start, Length)

If we set the Start position to 1, then Mid works exactly the same as Left. If we want to extract text from the string, then we set the Start parameter to the position from where we want to start extracting characters.

Let’s look at some examples so that we can understand it better. In the first example, we use 1 as the start position and 4 as the length. This will produce the same result as using the Left function with 4 as the length:

Let’s try some code with Start as 1 and Length as 4:

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 1, 4)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

You can see the result is the same as using Left with 3 as the length:

VBA Mid

To extract the word “had”, we set the start position to 6 and the length to 3.

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 6, 3)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run the code, you can see what the result is.

VBA Mid

Now we’re going to extract “little” from this string. We set the start position to 12 and the length to 6:

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 12, 6)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run the code, you can see the result:

vba mid

Just like in the other two functions, if we use a length value greater than the length of the text remaining, then the entire string is returned after the start position.

In the next example, we use 5 of the start position and we’re going to use 100 as the length which is obviously longer than the length of the string:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 12, 100)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When you run the code you will see that you got back all the text from the start position:

VBA Mid

One difference with Mid and the other two functions is that we don’t actually need to specify the length. This parameter is actually optional. If we don’t include the length parameter, it will return the rest of the string from the starting position that we provided. If we remove length from the previous example, so instead of having 100, we just don’t have the parameter, you will see that it also returns the rest of the string from the starting position:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 12)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Updating the Original String with Mid

At the beginning of this article, I mentioned that Mid has a little-known feature and here I’m going to show you what this feature is. We can update the string using Mid. With the LeftRight functions, we just get back what we’ve extracted from the string. We cannot update the original string with these functions.

The following shows an example of what I mean:

The original string is NOT changed

New string = Left(Original String, Length)
New string = Right(Original String, Length)
New string = Mid(Original String, Start, Length)

The original string is changed
Mid(String, Start, Length) = text

Let’s have a look at some examples to explain how this works. Let’s look at a simple example of Mid first. The following code will return “Mary”:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 1, 4)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

vba mid

Now we will take Mid and put it on the left-hand side of the equals sign. Then we assign it to the string “Jack”. When we run the code, “Jack” will replace “Mary” in the original string:

Sub UpdateUsingMid()

    Dim text As String
    text = "Mary had a little lamb"
    
     Mid(text, 1, 4) = "Jack"
    
    Debug.Print "Original: " & text

End Sub

One thing to keep in mind is how the length works. If we use a length the only the number of characters are replaced. So if we use 4 in the following example then only only 4 characters are replaced:

Mid(text, 1, 4) = "Andrew"

The result is: Andr had a little lamb

But if we don’t use any length then all the letters in the string on the right are used as we can see in this example:

Mid(text, 1) = "Andrew"

The result is: Andrewad a little lamb

If you just want to replace “Mary” with “Andrew” then the easiest thing to do is to use the Replace function:

text = Replace(text, "Mary", "Andrew")

The result is: Andrew had a little lamb

Reading through each character in a string

One useful feature of the Mid function is that it allows us to read through each individual character in a string. We can do it like this:

Sub MidLoop()

    Dim text As String
    text = "abcdef"
    
    Dim i As Long, character As String
    For i = 1 To Len(text)
        character = Mid(text, i, 1)
        Debug.Print i & ":  " & character
    Next i
    
End Sub

When we run this code we get the following result:
1: a
2: b
3: c
4: d
5: e
6: f

Reading through each character in reverse

If we want to read the text in the reverse direction we can do it like this:

Sub MidLoopReverse()

    Dim text As String
    text = "abcdef"
    
    Dim i As Long, character As String
    For i = Len(text) To 1 Step -1
        character = Mid(text, i, 1)
        Debug.Print i & ":  " & character
    Next i
    
End Sub

You will get the following when you run the code:
6: f
5: e
4: d
3: c
2: b
1: a

When to Use/Not Use These Functions

We have seen how to use these functions. The next question is when should we use these functions and when should we avoid using them. These functions work best with fixed strings, but they don’t work so well with variable strings.

Fixed Strings

Fixed strings are where each field in a string is always the same size and in the same position.

For example, you might have records where the first characters are the customer id, the next 4 characters are the year, the next two the transaction type and so on e.g.

1234AB2019XX
4567AB2019YY
1245AB2018ZY

When dealing with strings like this Left, Right and Mid are very useful. But for Variable size strings(i.e. typically a CSV style file), they are not suitable.

Variable sized (delimited) Strings

Variable size strings are ones where the fields may be of different sizes. The end of a field is marked by a delimiter like a comma. These types of strings are very common and you will see them in CSV files.

For example, imagine we have a file with a person’s name and their company name:
Jack Smith, United Block Company,36 High Street
Jenny Cathy Walton, Good Plumbers, Paradise Plaza
Helen McDonald, High-quality Software Providers, 16 Main Avenue

You can see that each field can be a different size. We use the delimiter (the comma in this case) to show us where the field ends.

Many people make the mistake of using our 3 functions with the Instr function to extract the data. For example:

Sub ReadVariableStrings()

    ' Create the test string
    Dim text As String
    text = "Jack Smith,United Block Company,36 High Street"
    
    ' Declare the variables
    Dim person As String, company As String
    Dim startPostion As Long, endPosition As Long
    
    ' Get the persons name
    endPosition = InStr(text, ",")
    person = Left(text, endPosition - 1)
    
    ' Get the company name
    startPostion = endPosition + 1
    endPosition = InStr(startPostion, text, ",") - 1
    company = Mid(text, startPostion, endPosition - startPostion + 1)
    
    ' Print the results
    Debug.Print person
    Debug.Print company

End Sub

You can see that the above code is very longwinded. We actually do this much easier using the Split function which I cover in this article. It has plenty of examples of using split with variable strings.

Here is the code above, rewritten to use the Split function:

Sub ReadVariableStringsSplit()

    ' Create the test string
    Dim text As String
    text = "Jack Smith,United Block Company,36 High Street"
    
    ' Declare the array
    Dim arr As Variant
    
    ' Split the string to an array
    arr = Split(text, ",")
   
    ' Print the results
    Debug.Print arr(0) ' Person
    Debug.Print arr(1) ' Company

End Sub

You can see that this code is much simpler.

Conclusion

In this post, we covered using the Left; Right and Mid functions. These are very useful for extracting text from a fixed-size string. We saw that the Mid function has the added feature which allows us to replace text in a string. We also saw that the Mid function can be used to read through the individual characters in a string.

Related Reading

Excel VBA Split Function – A Complete Guide
The Ultimate Guide to VBA String Functions
The Complete Guide to Using Arrays in Excel VBA

Содержание

  1. Функция Mid
  2. Синтаксис
  3. Примечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Функции строк и подстрок VBA
  8. Извлечение подстроки
  9. Функция левой строки VBA
  10. Функция правой строки VBA
  11. Функция средней строки VBA
  12. Поиск позиции подстроки
  13. Строковая функция VBA Instr
  14. Строковая функция VBA InstrRev
  15. Удаление пробелов из строки
  16. Строковая функция VBA LTrim
  17. Строковая функция VBA RTrim
  18. Функция строки обрезки VBA
  19. Функции регистра VBA
  20. Строковая функция VBA LCase
  21. Строковая функция VBA UCase
  22. Функция VBA StrConv
  23. Сравнение строк
  24. Функция VBA StrComp
  25. Оператор Like VBA
  26. Другие полезные строковые функции VBA
  27. Функция замены строки VBA
  28. Функция VBA StrReverse
  29. Строковая функция VBA Len

Функция Mid

Возвращает значение типа Variant (String), содержащее указанное число символов строки.

Синтаксис

Синтаксис функции Mid состоит из следующих именованных аргументов:

Часть Описание
строка Обязательный аргумент. Строковое выражение, из которого возвращаются символы. Если строка содержит значение NULL, возвращается NULL.
начало Обязательный аргумент. Long. Позиция символа в строке, с которой начинается забираемая часть. Если значение аргумента начало больше, чем число символов в строке, функция Mid возвращает строку нулевой длины («»).
длина Необязательный аргумент. Variant (Long). Число возвращаемых символов. Если не указано или если меньше, чем символов длины в тексте (включая символ в начале), возвращаются все символы от начальной позиции до конца строки.

Примечания

Чтобы определить число символов в строке, используйте функцию Len.

Используйте функцию MidB для работы с содержащимися в строке байтами, например в языках с двухбайтовыми кодировками (DBCS). Вместо указания числа символов аргументы задают число байтов. Образец кода с использованием функции MidB приведен во втором примере.

Пример

В первом примере с помощью функции Mid возвращается указанное количество знаков строки.

Во втором примере с использованием функции MidB и определяемой пользователем функции (MidMbcs) также возвращаются знаки из строки. Отличие от первого примера состоит в том, что исходная строка представляет собой строку ANSI и ее длина выражена в байтах.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Функции строк и подстрок VBA

VBA имеет множество строковых функций, которые позволят вам управлять текстом и строками в вашем коде и работать с ними. В этом руководстве мы рассмотрим функции, которые позволят вам извлекать подстроки из строк, удалять пробелы из строк, преобразовывать регистр текста или строки, сравнивать строки и другие полезные строковые функции.

Извлечение подстроки

Функция левой строки VBA

Функция VBA Left позволяет извлекать подстроку из текста или строки, начиная с левой стороны. Синтаксис функции левой строки VBA:

Left (String, Num_of_characters), где:

  • Строка — исходный текст.
  • Num_of_characters Целое число, указывающее количество символов, извлекаемых из исходного текста, начиная с начала.

В следующем коде показано, как использовать функцию левой строки для извлечения первых четырех символов данной строки:

1234567891011 Sub UsingTheLeftStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «AutomateExcel»valueTwo = Left (значениеOne, 4)MsgBox valueTwoКонец подписки

Функция Left извлекла первые четыре буквы AutomateExcel, которые являются Auto.

Функция правой строки VBA

Правая функция VBA позволяет извлекать подстроку из текста или строки, начиная с правой стороны. Синтаксис функции правой строки VBA:

Справа (String, Num_of_characters), где:

  • Строка — исходный текст.
  • Num_of_characters Целое число, указывающее количество символов, извлекаемых из исходного текста, начиная с конца.

В следующем коде показано, как использовать функцию правой строки для извлечения последних четырех символов строки:

1234567891011 Подложка UsingTheRightStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «AutomateExcel»valueTwo = Right (значениеOne, 4)MsgBox valueTwoКонец подписки

Функция Right извлекла последние четыре буквы AutomateExcel, которые являются xcel.

Функция средней строки VBA

Функция VBA Mid позволяет извлекать подстроку из текста или строки, начиная с любой позиции в указанной вами строке. Синтаксис функции средней строки VBA:

Mid (String, Starting_position, [Num_of_characters]), где:

  • Строка — исходный текст.
  • Начальная_позиция — позиция в исходном тексте, из которой функция начнет извлекать.
  • Num_of_characters (По желанию) Целое число, указывающее количество символов, извлекаемых из исходного текста, начиная с начального_позиции. Если пусто, функция MID вернет все символы из начального_позиции.

В следующем коде показано, как использовать функцию Mid String для извлечения четырех символов, начиная со второй позиции или символа в строке:

1234567891011 Sub UsingTheMidStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «AutomateExcel»valueTwo = Mid (значениеOne; 2; 4)MsgBox valueTwoКонец подписки

Результат выводится в msgbox:

Функция Mid извлекла четыре буквы AutomateExcel, начиная со второго символа / позиции / буквы, которые являются utom.

Поиск позиции подстроки

Строковая функция VBA Instr

Функция VBA Instr возвращает начальную позицию подстроки в другой строке. Эта функция чувствительна к регистру. Синтаксис строковой функции VBA Instr:

Instr ([Начало], Строка, Подстрока, [Сравнить]), где:

  • Начинать (По желанию) — указывает начальную позицию для функции для поиска. Если пусто, используется значение по умолчанию 1.
  • Строка — исходный текст.
  • Подстрока Подстрока в исходном тексте, положение которой вы хотите найти.
  • Сравнивать (По желанию)— Определяет тип сравнения, которое нужно сделать. Если пусто, используется двоичное сравнение.

-vbBinaryCompare — двоичное сравнение (верхний и нижний регистры считаются разными)
-vbTextCompare — Сравнение текста (верхний и нижний регистр считаются одинаковыми)
-vbDatabaseCompare — сравнение базы данных (этот параметр используется только в Microsoft Access и представляет собой сравнение на основе базы данных)

В следующем коде показано, как использовать функцию Instr String для определения первого вхождения подстроки «Th» в основной строке:

123456789101112 Sub UsingTheInstrStringFunction ()Тусклое значение: одно как строкаУменьшить положение подстроки как целое числоvalueOne = «Это текст»positionofSubstring = InStr (1, valueOne, «Th»)Отладка. Печать позиции подстрокиКонец подписки

Результат (выводится в окно Immediate Window):

Функция Instr вернула позицию первого вхождения подстроки «Th», которая равна 1. Обратите внимание, что эта функция включает пробелы в счетчике.

Строковая функция VBA InstrRev

Функция VBA InstrRev возвращает начальную позицию подстроки в другой строке, но начинает отсчет позиции с конца строки. Эта функция чувствительна к регистру. Синтаксис строковой функции VBA InstrRev:

InstrRev (String, Substring, [Start], [Compare]), где:

  • Строка — исходный текст.
  • Подстрока Подстрока в исходном тексте, положение которой вы хотите найти.
  • Начинать (По желанию) — указывает позицию для начала поиска. Если пусто, функция начинает поиск с последнего символа.
  • Сравнивать (По желанию)— Определяет тип сравнения, которое нужно сделать. Если пусто, используется двоичное сравнение.

-vbBinaryCompare — двоичное сравнение (верхний и нижний регистры считаются разными)
-vbTextCompare — Сравнение текста (верхний и нижний регистр считаются одинаковыми)
-vbDatabaseCompare — сравнение базы данных (этот параметр используется только в Microsoft Access и представляет собой сравнение на основе базы данных)

В следующем коде показано, как использовать функцию InstrRev String для определения первого вхождения подстроки «Th» в основной строке, начиная с конца строки:

1234567891011 Sub UsingTheInstrRevStringFunction ()Тусклое значение: одно как строкаУменьшить положение подстроки как целое числоvalueOne = «Это текст»positionofSubstring = InStrRev (valueOne, «Th»)Отладка. Печать позиции подстрокиКонец подписки

Результат выводится в Немедленное окно:

Функция InstrRev вернула позицию первого вхождения подстроки «Th», но отсчет начинается с конца, равного 9. Обратите внимание, что эта функция включает пробелы в счетчике.

Удаление пробелов из строки

Строковая функция VBA LTrim

Функция VBA LTrim удаляет все начальные пробелы из текста или строки. Синтаксис строковой функции VBA LTrim:

LTrim (String) где:

В следующем коде показано, как использовать функцию VBA LTrim для удаления начальных пробелов в данной строке:

123456789101112 Sub UsingTheLTrimStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «Это адрес веб-сайта https://easyexcel.net/excel/»valueTwo = LTrim (значениеOne)MsgBox valueOneMsgBox valueTwoКонец подписки

Функция LTrim удалила начальные пробелы для valuetwo, которое показано во втором окне сообщения.

Строковая функция VBA RTrim

Функция VBA RTrim удаляет все конечные пробелы из текста или строки. Синтаксис строковой функции VBA RTrim:

RTrim (String) где:

В следующем коде показано, как использовать функцию VBA RTrim для удаления конечных пробелов в данной строке:

123456789101112 Sub UsingTheRTrimStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «Это адрес веб-сайта https://easyexcel.net/excel/»valueTwo = RTrim (значениеOne)MsgBox valueOneMsgBox valueTwoКонец подписки

Полученные результаты:

Функция RTrim удалила конечные пробелы для valuetwo, которое показано во втором окне сообщения.

Функция строки обрезки VBA

Функция обрезки VBA удаляет все начальные и конечные пробелы из текста или строки. Синтаксис функции строки обрезки VBA:

Обрезать (Строка), где:

В следующем коде показано, как использовать функцию обрезки VBA для удаления начальных и конечных пробелов в данной строке:

123456789101112 Подпрограмма UsingTheTrimStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «Это адрес веб-сайта https://easyexcel.net/excel/»valueTwo = Обрезать (значениеOne)MsgBox valueOneMsgBox valueTwoКонец подписки

Результат:

Функция обрезки удалила начальные и конечные пробелы для valuetwo, которое показано во втором окне сообщения.

Функции регистра VBA

Строковая функция VBA LCase

Функция VBA LCase преобразует буквы в тексте или строке в нижний регистр. Синтаксис строковой функции VBA LCase:

LCase (String) где:

В следующем коде показано, как использовать строковую функцию LCase для преобразования всех букв в данной строке в нижний регистр:

1234567891011 Sub UsingTheLCaseStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «ЭТО ПРОДУКТ»valueTwo = LCase (значениеOne)MsgBox valueTwoКонец подписки

Функция LCase преобразовала все буквы в строке в нижний регистр.

Строковая функция VBA UCase

Функция VBA UCase преобразует буквы в тексте или строке в верхний регистр. Синтаксис строковой функции VBA UCase:

UCase (String) где:

В следующем коде показано, как использовать функцию строки UCase для преобразования всех букв в данной строке в верхний регистр:

1234567891011 Sub UsingTheUCaseStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «это продукт»valueTwo = UCase (значениеOne)MsgBox valueTwoКонец подписки

Функция UCase преобразовала все буквы в строке в верхний регистр.

Функция VBA StrConv

Функция VBA StrConv может преобразовывать буквы в тексте или строке в верхний регистр, нижний регистр, правильный регистр или Unicode в зависимости от указанного вами типа преобразования. Синтаксис строковой функции VBA StrConv:

StrConv (String, Conversion, [LCID]) где:

  • Строка — исходный текст.
  • Конверсия — желаемый тип конверсии.
  • [LCID] (По желанию) —Необязательный параметр, указывающий LocaleID. Если пусто, используется системный LocaleID.

В следующем коде показано, как использовать функцию StrConv String для преобразования строки в соответствующий регистр:

1234567891011 Подпрограмма UsingTheStrConvStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «это продукт»valueTwo = StrConv (значениеOne, vbProperCase)MsgBox valueTwoКонец подписки

Вы указываете тип преобразования, которое хотите выполнить, используя параметр преобразования:

  • vbLowerCase преобразует все буквы в тексте в нижний регистр.
  • vbUpperCase преобразует все буквы в тексте в верхний регистр.
  • vbProperCase преобразует первую букву каждого слова в тексте в верхний регистр, а все остальные буквы остаются в нижнем регистре.
  • vbUnicode преобразует строку в Unicode.
  • vbFromUnicode преобразует строку из юникода в кодовую страницу системы по умолчанию.

Сравнение строк

Функция VBA StrComp

Строковая функция VBA StrComp позволяет сравнивать две строки. Функция возвращает:

  • 0, если две строки совпадают
  • -1, если строка1 меньше строки2
  • 1, если строка1 больше строки2
  • Нулевое значение, если одна из строк была Null

В следующем коде показано, как использовать функцию StrComp для сравнения двух строк:

123456789101112 Sub UsingTheStrCompStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаУменьшить результат сравнения как целое числоvalueOne = «AutomateExcel»valueTwo = «AutomateExcel»resultofComparison = StrComp (значениеOne, значениеTwo)Отладка. Распечатать результат сравненияКонец подписки

Функция StrComp нашла точное совпадение между двумя строками и вернула 0.

Оператор Like VBA

Оператор Like VBA позволяет сравнить текст или строку с шаблоном и посмотреть, есть ли совпадение. Обычно оператор Like используется вместе с подстановочными знаками. В следующем коде показано, как использовать оператор Like:

123456789101112 Sub UsingTheLikeOperatorInVBA ()Тусклое значение: одно как строкаvalueOne = «Давайте посмотрим на результат»Если valueOne Like «* view *» ТогдаMsgBox «Есть совпадение, эта строка содержит слово view»ЕщеMsgBox «Совпадений не найдено»Конец, еслиКонец подписки

Подстановочные знаки, которые вы можете использовать с оператором Like для поиска совпадений с образцом, включают:

  • ? что соответствует одиночному символу
  • # что соответствует одной цифре
  • * что соответствует нулю или более символов

В следующем коде показано, как использовать оператор Like и оператор? подстановочный знак, соответствующий шаблону в вашем коде:

123456789101112 Sub UsingTheLikeOperatorWithAWildcardInVBA ()Тусклое значение: одно как строкаvalueOne = «The»Если valueOne Like «?? e» ТогдаMsgBox «Есть совпадение, найден соответствующий шаблон»ЕщеMsgBox «Совпадений не найдено»Конец, еслиКонец подписки

Полученный результат:

Другие полезные строковые функции VBA

Функция замены строки VBA

Функция замены VBA заменяет набор символов в строке другим набором символов. Синтаксис функции замены строки VBA:

Заменить (Строка, Найти, Заменить, [Начало], [Счетчик], [Сравнить]), где:

  • Строка — исходный текст.
  • Найти — подстрока для поиска в исходном тексте.
  • Заменить — подстрока, на которую нужно заменить подстроку поиска.
  • Начинать (По желанию)— Позиция для начала поиска из исходного текста. Если пусто, используется значение 1, и функция начинается с позиции первого символа.
  • Считать (По желанию)— Количество появлений заменяемой подстроки «Найти» в исходном тексте. Если пусто, заменяются все вхождения подстроки «Найти».
  • Сравнивать (По желанию)— Определяет тип сравнения, которое нужно сделать. Если пусто, используется двоичное сравнение.

-vbBinaryCompare — двоичное сравнение
-vbTextCompare — Сравнение текста
-vbDatabaseCompare — сравнение базы данных (этот параметр используется только в Microsoft Access и представляет собой сравнение на основе базы данных).

В следующем коде показано, как использовать функцию замены строки:

1234567891011 Подпрограмма UsingTheReplaceStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «ProductABC»valueTwo = Replace (valueOne, «ABC», «XYZ»)MsgBox valueTwoКонец подписки

Функция замены нашла подстроку ABC в ProductABC и заменила ее подстрокой XYZ.

Функция VBA StrReverse

Функция VBA StrReverse меняет местами символы в заданном тексте или строке. Синтаксис строковой функции VBA StrReverse:

StrReverse (String) где:

В следующем коде показано, как использовать функцию VBA StrReverse для изменения символов в строке Product:

1234567891011 Подпрограмма UsingTheStrReverseStringFunction ()Тусклое значение: одно как строкаТусклое значение Два как строкаvalueOne = «Продукт»valueTwo = StrReverse (значениеOne)MsgBox valueTwoКонец подписки

Строковая функция VBA Len

Функция VBA Len возвращает количество символов в текстовой строке. Синтаксис строковой функции VBA Len String:

В следующем коде показано, как использовать функцию Len String для определения длины строки AutomateExcel:

1234567891011 Sub UsingTheLenFunction ()Тусклое значение: одно как строкаDim stringLength As IntegervalueOne = «AutomateExcel»stringLength = Len (значениеOne)Debug.Print stringLengthКонец подписки

Функция Len подсчитала все символы в тексте AutomateExcel, который состоит из 13 букв.

Источник

Substring is one of the most popular functions in any programming language. It eases your tasks while dealing with strings. As the name suggests a substring function divides a string into different parts based on particular criteria.

There are multiple VBA Substring functions. In practical situations, these substring functions can be quite useful in extracting a portion of a string.

Today in this post I am going to explain all the VBA substring functions that you can use in Excel macros:

Substring Function in Excel VBA

LEFT Substring function:

The LEFT function in Excel VBA is used for fetching a specified number of characters from the start of the string. The syntax of the LEFT function is as follows:

Left (text_string, length)
  • Here ‘text_string’ refers to an input string that is to be separated.
  • And ‘length’ refers to the number of characters to be extracted.

Examples:

Left ("Exceltrick", 5) 'gives an output "Excel"
Left ("SomeText", 4) 'gives the result "Some"

Note: Instead of using a hardcoded string in the first argument you can also fetch ‘text_string’ from your excel sheet like ActiveSheet.Range(«A1»).

Right Substring function:

The RIGHT Function in Excel VBA is just opposite to the LEFT function. It returns a specified number of characters from the end of the text string. The syntax of the RIGHT function is as follows:

Right (text_string, length)
  • Here ‘text_string’ refers to an input string that is to be separated.
  • And ‘length’ refers to the number of characters to be extracted but extraction begins from the right side.

Example:

Right ("Exceltrick", 5) 'gives an output "trick"
Right ("SomeText", 4) 'gives the result "Text"

Note: Instead of using a hardcoded string in the first argument you can also fetch ‘text_string’ from your excel sheet as ActiveSheet.Range(«A1»).

MID Substring function:

MID is a much better function than the first two, it gives you the ability to specify the start and end positions of the extracted string. The syntax of the MID VBA Substring function is as under:

Mid(text_string, start_position, Length)
  • Here ‘text_string’ refers to an input string that is to be separated.
  • ‘start_position’ refers to the numeric position from where extraction is to be started.
  • And ‘length’ refers to the number of characters to be extracted.

Example:

MID ("Exceltrick", 2,4) 'gives an output "celt"
MID ("SomeText", 4,4) 'gives the result "Text"

Note: Instead of using a hardcoded string in the first argument you can also fetch ‘text_string’ from your excel sheet as ActiveSheet.Range(«A1»).

SPLIT Substring function:

The SPLIT function is another VBA function that can be used for sub-stringing or splitting a string. The SPLIT function can come very handy when you are dividing a text string into more than one parts based on a delimiter. The syntax of a split function is as under:

Split (text_string, Delimiter, limit, Compare)
  • Here, ‘text_string’ refers to an input string that is to be separated.
  • ‘Delimiter’ refers to the delimiter character which separates the string into parts. This is an optional argument, if it is left blank then, the space character » » is assumed to be the default delimiter.
  • ‘limit’ refers to the maximum number of substring parts into which the string should be divided. It is also an optional argument, the default value is (-1) which means that substring should happen at every position where the delimiter is encountered.
  • ‘compare’ is an optional numerical value that specifies the comparison to use when evaluating substrings.

Example:

For instance, you have a text string as «This is a text string» and now you have to break this string into individual words, so in this case, you will use space » » as a delimiter. The split function will be used as:

Split ("This is a text string", " ")

The result of this split function is an array of words: «This» «is» «a» «text» «string».

Recommended Reading: VBA Split Function

VBA Substring Macro Example:

Below I have created a macro that illustrates all the substring techniques available in VBA programming. This is a simple and self-explanatory macro, in this, I have simply divided a text string with the 4 methods that I have described above.

VBA Substring Macro

Below is the code that I have used for this macro:

Sub BreakStrings()
'Left function
a = Left("Excel Trick Text", 5)
'Right function
b = Right("Excel Trick Text", 11)
'Mid function
c = Mid("Excel Trick Text", 1, 11)
'Split function
d = Split("Excel Trick Text", " ")
For Each wrd In d
strg = strg & wrd & ", "
Next
'Displaying the results in a mesage box
MsgBox "Left: " & a & vbNewLine & "Right: " & b & vbNewLine & "Mid: " & c & vbNewLine & "Split: " & strg
End Sub

So, this was all about VBA substring functions. Do share your view related to the topic.

In this Article

  • Extracting a Substring
    • The VBA Left String Function
    • The VBA Right String Function
    • The VBA Mid String Function
  • Finding the Position of a Substring
    • The VBA Instr String Function
    • The VBA InstrRev String Function
  • Removing Spaces from a String
    • The VBA LTrim String Function
    • The VBA RTrim String Function
    • The VBA Trim String Function
  • VBA Case Functions
    • The VBA LCase String Function
    • The VBA UCase String Function
    • The VBA StrConv Function
  • Comparing Strings
    • The VBA StrComp Function
    • The VBA Like Operator
  • Other Useful VBA String Functions
    • The VBA Replace String Function
    • The VBA StrReverse Function
    • The VBA Len String Function

VBA has many string functions that will allow you to manipulate and work with text and strings in your code. In this tutorial, we are going to cover functions that will allow you to extract substrings from strings, remove spaces from strings, convert the case of a text or string, compare strings and other useful string functions.

The VBA Left String Function

The VBA Left Function allows you to extract a substring from a text or string starting from the left side. The syntax of the VBA Left String Function is:

Left(String, Num_of_characters) where:

  • String – The original text.
  • Num_of_characters  – An integer that specifies the number of characters to extract from the original text starting from the beginning.

The following code shows you how to use the Left String Function to extract the first four characters of the given string:

Sub UsingTheLeftStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Left(valueOne, 4)

MsgBox valueTwo

End Sub

The result is:

How to Use the Left String Function in VBA

The Left Function has extracted the first four letters of AutomateExcel, which are Auto.

The VBA Right String Function

The VBA Right Function allows you to extract a substring from a text or string starting from the right side. The syntax of the VBA Right String Function is:

Right(String, Num_of_characters) where:

  • String – The original text.
  • Num_of_characters  – An integer that specifies the number of characters to extract from the original text starting from the ending.

The following code shows you how to use the Right String Function to extract the last four characters of the string:

Sub UsingTheRightStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Right(valueOne, 4)

MsgBox valueTwo

End Sub

The result is:

Using the Right String Function in VBA

The Right Function has extracted the last four letters of AutomateExcel, which are xcel.

The VBA Mid String Function

The VBA Mid Function allows you to extract a substring from a text or string, starting from any position within the string that you specify. The syntax of the VBA Mid String Function is:

Mid(String, Starting_position, [Num_of_characters]) where:

  • String – The original text.
  • Starting_position – The position in the original text, where the function will begin to extract from.
  • Num_of_characters (Optional) – An integer that specifies the number of characters to extract from the original text beginning from the Starting_position. If blank, the MID Function will return all the characters from the Starting_position.

The following code shows you how to use the Mid String Function to extract four characters, starting from the second position or character in the string:

Sub UsingTheMidStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Mid(valueOne, 2, 4)

MsgBox valueTwo

End Sub

The result is outputted to a msgbox:

Using the Mid String Function in VBA

The Mid Function has extracted the four letters of AutomateExcel starting from the second character/position/letter which are utom.

Finding the Position of a Substring

The VBA Instr String Function

The VBA Instr Function returns the starting position of a substring within another string. This function is case-sensitive. The syntax of the VBA Instr String Function is:

Instr([Start], String, Substring, [Compare]) where:

  • Start (Optional) – This specifies the starting position for the function to search from. If blank, the default value of 1 is used.
  • String – The original text.
  • Substring– The substring within the original text that you want to find the position of.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

-vbBinaryCompare – Binary comparison (Upper and lower case are regarded as different)
-vbTextCompare – Text comparison (Upper and lower case are regarded as the same)
-vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database)

The following code shows you how to use the Instr String Function to determine the first occurrence of the substring “Th” within the main string:

Sub UsingTheInstrStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

valueOne = "This is The Text "
positionofSubstring = InStr(1, valueOne, "Th")

Debug.Print positionofSubstring


End Sub

The result (outputted to the Immediate Window) is:

Using the Instr Function in VBA

The Instr Function has returned the position of the first occurrence of the substring “Th” which is 1. Note this function includes the spaces in the count.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

The VBA InstrRev String Function

The VBA InstrRev Function returns the starting position of a substring within another string but it starts counting the position, from the end of the string. This function is case-sensitive. The syntax of the VBA InstrRev String Function is:

InstrRev(String, Substring, [Start], [Compare]) where:

  • String – The original text.
  • Substring – The substring within the original text that you want to find the position of.
  • Start (Optional) – This specifies the position to start searching from. If blank, the function starts searching from the last character.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

-vbBinaryCompare – Binary comparison (Upper and lower case are regarded as different)
-vbTextCompare – Text comparison (Upper and lower case are regarded as the same)
-vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database)

The following code shows you how to use the InstrRev String Function to determine the first occurrence of the substring “Th” within the main string, starting from the end of the string:

Sub UsingTheInstrRevStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

valueOne = "This is The Text "
positionofSubstring = InStrRev(valueOne, "Th")

Debug.Print positionofSubstring

End Sub

The result is outputted to the Immediate Window:

Using The InstrRev Function in VBA

The InstrRev Function has returned the position of the first occurrence of the substring “Th”, but starting the counting from the end which is 9. Note this function includes the spaces in the count.

Removing Spaces from a String

The VBA LTrim String Function

The VBA LTrim Function removes all the leading spaces from a text or string. The syntax of the VBA LTrim String Function is:

LTrim(String) where:

  • String – The original text.

The following code shows you how to use the VBA LTrim Function to remove the leading spaces in the given string:

Sub UsingTheLTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "         This is the website adddress https://www.automateexcel.com/excel/"
valueTwo = LTrim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:

String With Leading Spaces

Using the LTrim String Function To Remove Leading Spaces

The LTrim Function has removed the leading spaces for valuetwo, which is shown in the second Message Box.

VBA Programming | Code Generator does work for you!

The VBA RTrim String Function

The VBA RTrim Function removes all the trailing spaces from a text or string. The syntax of the VBA RTrim String Function is:

RTrim(String) where:

  • String – The original text.

The following code shows you how to use the VBA RTrim Function to remove the trailing spaces in the given string:

Sub UsingTheRTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "This is the website adddress https://www.automateexcel.com/excel/               "
valueTwo = RTrim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results delivered are:
Message box With Trailing Spaces

Using The RTrim String Function

The RTrim Function has removed the trailing spaces for valuetwo, which is shown in the second Message Box.

The VBA Trim String Function

The VBA Trim Function removes all leading and trailing spaces from a text or string. The syntax of the VBA Trim String Function is:

Trim(String) where:

  • String – The original text.

The following code shows you how to use the VBA Trim Function to remove the leading and trailing spaces in the given string:

Sub UsingTheTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "           This is the website adddress https://www.automateexcel.com/excel/             "
valueTwo = Trim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:
Message box With Leading And Trailing Spaces

Using The Trim Function in VBA

The Trim Function has removed the leading and trailing spaces for valuetwo, which is shown in the second Message Box.

VBA Case Functions

The VBA LCase String Function

The VBA LCase Function converts letters in a text or string to lower case. The syntax of the VBA LCase String Function is:

LCase(String) where:

  • String – The original text.

The following code shows you how to use the LCase String Function to convert all the letters in the given string to lower case:

Sub UsingTheLCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "THIS IS THE PRODUCT"
valueTwo = LCase(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The LCase Function in VBA

The LCase Function has converted all the letters in the string to lower case.

The VBA UCase String Function

The VBA UCase Function converts letters in a text or string to upper case. The syntax of the VBA UCase String Function is:

UCase(String) where:

  • String – The original text.

The following code shows you how to use the UCase String Function to convert all the letters in the given string to upper case:

Sub UsingTheUCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "this is the product"
valueTwo = UCase(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The UCase Function in VBA

The UCase Function has converted all the letters in the string to upper case.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

The VBA StrConv Function

The VBA StrConv Function can convert letters in a text or string to upper case, lower case, proper case or unicode depending on type of conversion you specify.  The syntax of the VBA StrConv String Function is:

StrConv(String, Conversion, [LCID]) where:

  • String – The original text.
  • Conversion – The type of conversion that you want.
  • [LCID] (Optional) – An optional parameter that specifies the LocaleID. If blank, the system LocaleID is used.

The following code shows you how to use the StrConv String Function to convert the string to proper case:

Sub UsingTheStrConvStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "this is THE product"
valueTwo = StrConv(valueOne, vbProperCase)

MsgBox valueTwo

End Sub

The result is:

Using The StrConv Function in VBA

You specify the type of conversion you want to perform using the conversion parameter:

  • vbLowerCase converts all the letters in the text to lower case.
  • vbUpperCase converts all the letters in the text to upper case.
  • vbProperCase converts the first letter of each word in the text to upper case, while all the other letters are kept as lower case.
  • vbUnicode converts a string to unicode.
  • vbFromUnicode converts a string from unicode to the default code page of the system.

Comparing Strings

The VBA StrComp Function

The VBA StrComp String Function allows you to compare two strings. The function returns:

  • 0 if the two strings match
  • -1 if string1 is less than string2
  • 1 if string1 is greater than string2
  • A null value if either of the strings was Null

The following code shows you how to use the StrComp Function to compare two strings:

Sub UsingTheStrCompStringFunction()

Dim valueOne As String
Dim valueTwo As String
Dim resultofComparison As Integer

valueOne = "AutomateExcel"
valueTwo = "AutomateExcel"
resultofComparison = StrComp(valueOne, valueTwo)
Debug.Print resultofComparison

End Sub

The result is:

Using The StrComp Function in VBA

The StrComp Function has found an exact match between the two strings and returned 0.

The VBA Like Operator

The VBA Like Operator allows you to compare a text or string to a pattern and see if there is a match. You would usually use the Like Operator in conjunction with wildcards. The following code shows you how to use the Like Operator:

Sub UsingTheLikeOperatorInVBA()

Dim valueOne As String
valueOne = "Let's view the output"

If valueOne Like "*view*" Then
MsgBox "There is a match, this string contains the word view"
Else
MsgBox "No match was found"
End If

End Sub

The result is:

Using The Like Operator in VBA

The wildcards you can use with the Like Operator to find pattern matches include:

  • ? which matches a single character
  • # which matches a single digit
  • * which matches zero or more characters

The following code shows you how you would use the Like Operator and the ? wildcard to match a pattern in your code:

Sub UsingTheLikeOperatorWithAWildcardInVBA()

Dim valueOne As String
valueOne = "The"

If valueOne Like "??e" Then
MsgBox "There is a match, a matching pattern was found"
Else
MsgBox "No match was found"
End If

End Sub

The result delivered is:
Using The Like Operator To Match Patterns in VBA

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Other Useful VBA String Functions

The VBA Replace String Function

The VBA Replace Function replaces a set of characters in a string with another set of characters. The syntax of the VBA Replace String Function is:

Replace(String, Find, Replace, [Start], [Count], [Compare]) where:

  • String – The original text.
  • Find – The substring to search for within the original text.
  • Replace – The substring to replace the Find substring with.
  • Start (Optional) – The position to begin searching from within the original text. If blank, the value of 1 is used and the function starts at the first character position.
  • Count (Optional) – The number of occurrences of the Find substring in the original text to replace. If blank, all the occurrences of the Find substring are replaced.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

    -vbBinaryCompare – Binary comparison
    -vbTextCompare – Text comparison
    -vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database.)

The following code shows you how to use the Replace String Function:

Sub UsingTheReplaceStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "ProductABC"
valueTwo = Replace(valueOne, "ABC", "XYZ")

MsgBox valueTwo

End Sub

The result is:

Using The Replace String Function in VBA

The Replace Function found the substring ABC within ProductABC and replaced it with the substring XYZ.

The VBA StrReverse Function

The VBA StrReverse Function reverses the characters in a given text or string. The syntax of the VBA StrReverse String Function is:

StrReverse(String) where:

  • String – The original text.

The following code shows you how to use the VBA StrReverse Function to reverse the characters in the string Product:

Sub UsingTheStrReverseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "Product"
valueTwo = StrReverse(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The StrReverse Function in VBA

The VBA Len String Function

The VBA Len Function returns the number of characters in a text string. The syntax of the VBA Len String Function is:

Len(String) where:

  • String – The original text.

The following code shows you how to use the Len String Function to determine the length of the string AutomateExcel:

Sub UsingTheLenFunction()

Dim valueOne As String
Dim stringLength As Integer

valueOne = "AutomateExcel"
stringLength = Len(valueOne)
Debug.Print stringLength


End Sub

The result is:

Using The Len String Function in VBA

The Len Function has counted all the characters in the text AutomateExcel, which is 13 letters.

В этой статье разберем работу со строками в VBA на примерах функций InStr, LCASE, UCase, Left, Right, Mid, LTrim, RTrim, Trim, Len, Replace, Space, StrComp, String, StrReverse.

Строки — это последовательность символов, которая может состоять либо из алфавитов, цифр, специальных символов, либо из всех них. Переменная называется строкой, если она заключена в двойные кавычки «».

Содержание:

  • Синтаксис
  • Примеры
  • Строковые функции
  • Название функции и описание
  • InStr
  • Синтаксис
  • Параметр Описание
  • пример
  • Синтаксис
  • Параметр Описание
  • пример
  • LCASE
  • Синтаксис
  • пример
  • UCase
  • Синтаксис
  • пример
  • Left
  • Синтаксис
  • Параметр Описание
  • пример
  • Right
  • Синтаксис
  • Параметр Описание
  • пример
  • Mid
  • Синтаксис
  • Параметр Описание
  • LTrim
  • Синтаксис
  • пример
  • RTrim
  • Синтаксис
  • пример
  • Trim
  • Синтаксис
  • пример
  • Len
  • Синтаксис
  • пример
  • Replace
  • Синтаксис
  • Параметр Описание
  • пример
  • Space
  • Синтаксис
  • Параметр Описание
  • пример
  • StrComp
  • Синтаксис
  • Параметр Описание
  • пример
  • String
  • Синтаксис
  • Параметр Описание
  • пример
  • StrReverse
  • Синтаксис
  • пример

Синтаксис

variablename = "string"

Примеры

str1 = "string"   ' Only Alphabets
str2 = "132.45"   ' Only Numbers
str3 = "!@#$;*"  ' Only Special Characters
Str4 = "Asc23@#"  ' Has all the above

Строковые функции

Существуют предопределенные функции VBA String, которые помогают разработчикам эффективно работать со строками. Ниже приведены методы String, поддерживаемые в VBA. Пожалуйста, нажмите на каждый из методов, чтобы знать подробно.

Название функции и описание

Функция InStr возвращает первое вхождение одной строки в другую строку. Поиск происходит слева направо.

Синтаксис

InStr([start,]string1,string2[,compare])

Параметр Описание

  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции слева направо.
  • String1 — требуемый параметр. Строка для поиска.
  • String2 — требуемый параметр. Строка, по которой выполняется поиск String1.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click() 
   Dim Var As Variant 
   Var = "Microsoft VBScript" 
   MsgBox ("Line 1 : " & InStr(1, Var, "s")) 
   MsgBox ("Line 2 : " & InStr(7, Var, "s")) 
   MsgBox ("Line 3 : " & InStr(1, Var, "f", 1)) 
   MsgBox ("Line 4 : " & InStr(1, Var, "t", 0)) 
   MsgBox ("Line 5 : " & InStr(1, Var, "i")) 
   MsgBox ("Line 6 : " & InStr(7, Var, "i")) 
   MsgBox ("Line 7 : " & InStr(Var, "VB")) 
End Sub 

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11

Возвращает первое вхождение указанной подстроки. Поиск происходит слева направо.

InStrRev

Функция InStrRev возвращает первое вхождение одной строки в другую строку. Поиск происходит справа налево.

Синтаксис

InStrRev(string1,string2[,start,[compare]])

Параметр Описание

  • String1 — требуемый параметр. Строка для поиска.
  • String2 — требуемый параметр. Строка, по которой выполняется поиск String1.
  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции справа налево.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и установите следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & InStrRev(var,"s",10))
   msgbox("Line 2 : " & InStrRev(var,"s",7))
   msgbox("Line 3 : " & InStrRev(var,"f",-1,1))
   msgbox("Line 4 : " & InStrRev(var,"t",5))
   msgbox("Line 5 : " & InStrRev(var,"i",7))
   msgbox("Line 6 : " & InStrRev(var,"i",7))
   msgbox("Line 7 : " & InStrRev(var,"VB",1))
End Sub

После выполнения вышеуказанного скрипта он производит следующий результат.

Line 1 : 6
Line 2 : 6
Line 3 : 8
Line 4 : 0
Line 5 : 2
Line 6 : 2
Line 7 : 0

Возвращает первое вхождение указанной подстроки. Поиск происходит справа налево.

LCASE

Функция LCase возвращает строку после преобразования введенной строки в строчные буквы.

Синтаксис

Lcase(String)

пример

Добавьте кнопку и поместите следующую функцию внутри нее.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & LCase(var))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & LCase(var))
   
   var = "microsoft"
   msgbox("Line 3 : " & LCase(var))
End Sub

После выполнения вышеуказанного скрипта он производит следующий вывод.

Line 1 : microsoft vbscript
Line 2 : ms vbscript
Line 3 : microsoft

Возвращает нижний регистр указанной строки.

UCase

Функция UCase возвращает строку после преобразования введенной строки в буквы буквы UPPER.

Синтаксис

UCase(String)

пример

Добавьте кнопку и поместите следующую функцию внутри нее.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & UCase(var))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & UCase(var))
   
   var = "microsoft"
   msgbox("Line 3 : " & UCase(var))
End Sub

После выполнения вышеуказанного скрипта он производит следующий вывод.

Line 1 : MICROSOFT VBSCRIPT
Line 2 : MS VBSCRIPT
Line 3 : MICROSOFT

Возвращает верхний регистр указанной строки.

Left

Функция Left возвращает указанное количество символов с левой стороны данной входной строки.

Синтаксис

Left(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с левой стороны.
  • Длина — требуемый параметр. Целое число, определяющее количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Left(var,2))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & Left(var,5))
   
   var = "microsoft"
   msgbox("Line 3 : " & Left(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : Mi
Line 2 : MS VB
Line 3 : microsoft

Возвращает определенное количество символов с левой стороны строки.

Right

Функция Right возвращает указанное количество символов с правой стороны данной входной строки.

Синтаксис

Right(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с правой стороны.
  • Длина — требуемый параметр. Целое число, которое задает количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Right(var,2))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & Right(var,5))
   
   var = "microsoft"
   msgbox("Line 3 : " & Right(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : pt
Line 2 : CRIPT
Line 3 : microsoft

Возвращает определенное количество символов с правой стороны строки.

Mid

Mid функция возвращает указанное количество символов из заданной входной строки.

Синтаксис

Mid(String,start[,Length])

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой задано количество символов, которые нужно вернуть.
  • Начало — требуемый параметр. Целое число, определяющее начальную позицию строки.
  • Длина — необязательный параметр. Целое число, определяющее количество возвращаемых символов.

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Mid(var,2))
   msgbox("Line 2 : " & Mid(var,2,5))
   msgbox("Line 3 : " & Mid(var,5,7))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : icrosoft VBScript
Line 2 : icros
Line 3 : osoft V

Возвращает определенное количество символов из строки на основе указанных параметров.

LTrim

Функция Ltrim удаляет пробелы с левой стороны строки.

Синтаксис

LTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var =       "             Microsoft VBScript"
   msgbox "After Ltrim : " & LTrim(var)
End Sub

Когда вы выполняете функцию, она производит следующий вывод.

After Ltrim : Microsoft VBScript

Возвращает строку после удаления пробелов в левой части указанной строки.

RTrim

Функция Rtrim удаляет пробелы с правой стороны строки.

Синтаксис

RTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var =       "Microsoft VBScript           "
   msgbox("After Rtrim : " & RTrim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After Rtrim : Microsoft VBScript

Возвращает строку после удаления пробелов в правой части указанной строки.

Trim

Функция Trim удаляет как ведущее, так и конечное пустое пространство данной входной строки.

Синтаксис

Trim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   var =       "            Microsoft VBScript           "
   msgbox ("After Trim : " & Trim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After trim : Microsoft VBScript

Возвращает строковое значение после удаления как верхнего, так и конечного пробелов.

Len

Функция Len возвращает длину данной входной строки, включая пробелы.

Синтаксис

Len(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   Dim var2 as Variant
   
   var1 ="Microsoft VBScript"
   msgbox("Length of var1 is : " & Len(var1))
  
   var2 =       "       Microsoft VBScript           "
   msgbox ("Length of var2 is : " & Len(var2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Length of var1 is : 18
Length of var2 is : 36

Возвращает длину данной строки.

Replace

Функция Replace заменяет указанную часть строки на определенную строку, указанное количество раз.

Синтаксис

Replace(string,find,replacewith[,start[,count[,compare]]])

Параметр Описание

  • String — обязательный параметр. Строка ввода, которую нужно искать для замены.
  • Find — требуемый параметр. Часть строки, которая будет заменена.
  • Replacewith — обязательный параметр. Строка замены, которая будет заменена на параметр find.
  • Start — необязательный параметр. Задает начальную позицию, из которой нужно искать и заменять строку. Значение по умолчанию — 1.
  • Count — необязательный параметр. Указывает количество раз, которое должна выполняться замена.
  • Compare — Необязательный параметр. Указывает метод сравнения, который будет использоваться. Значение по умолчанию — 0.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение
  • 1 = vbTextCompare — выполняет текстовое сравнение

пример

Private Sub Constant_demo_Click()
   Dim var as Variant
   var = "This is VBScript Programming"
  
   'VBScript to be replaced by MS VBScript
   msgbox("Line 1: " & Replace(var,"VBScript","MS VBScript"))
  
   'VB to be replaced by vb
   msgbox("Line 2: " & Replace(var,"VB","vb"))
  
   ''is' replaced by ##
   msgbox("Line 3: " & Replace(var,"is","##"))
  
   ''is' replaced by ## ignores the characters before the first occurence
   msgbox("Line 4: " & Replace(var,"is","##",5))
  
   ''s' is replaced by ## for the next 2 occurences.
   msgbox("Line 5: " & Replace(var,"s","##",1,2))
  
   ''r' is replaced by ## for all occurences textual comparison.
   msgbox("Line 6: " & Replace(var,"r","##",1,-1,1))
  
   ''t' is replaced by ## for all occurences Binary comparison
   msgbox("Line 7: " & Replace(var,"t","##",1,-1,0))
  
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming

Возвращает строку после замены строки другой строкой.

Space

Функция Space заполняет строку конкретным количеством пробелов.

Синтаксис

space(number)

Параметр Описание

Номер — требуемый параметр. Количество пробелов, которые мы хотим добавить к данной строке.

пример

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   
   var1 = "Microsoft"
   Dim var2 as Variant
   
   var2 = "VBScript"
   msgbox(var1 & Space(2)& var2)
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Microsoft VBScript

Заполняет строку указанным количеством пробелов.

StrComp

Функция StrComp возвращает целочисленное значение после сравнения двух заданных строк. Он может возвращать любое из трех значений -1, 0 или 1 на основе входных строк для сравнения.

  • Если String1 меньше String2, то StrComp возвращает -1
  • Если String1 равно String2, то StrComp возвращает 0
  • Если String1 больше String2, то StrComp возвращает 1

Синтаксис

StrComp(string1,string2[,compare])

Параметр Описание

  • String1 — требуемый параметр. Первое строковое выражение.
  • String2 — требуемый параметр. Второе строковое выражение.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   msgbox("Line 1 :" & StrComp("Microsoft","Microsoft"))
   msgbox("Line 2 :" &StrComp("Microsoft","MICROSOFT"))
   msgbox("Line 3 :" &StrComp("Microsoft","MiCrOsOfT"))
   msgbox("Line 4 :" &StrComp("Microsoft","MiCrOsOfT",1))
   msgbox("Line 5 :" &StrComp("Microsoft","MiCrOsOfT",0))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 :0
Line 2 :1
Line 3 :1
Line 4 :0
Line 5 :1

Возвращает целочисленное значение после сравнения двух указанных строк.

String

Функция String заполняет строку указанным символом для указанного количества раз.

Синтаксис

String(number,character)

Параметр Описание

  • Номер — требуемый параметр. Целочисленное значение, которое будет повторяться в течение определенного количества раз против параметра символа.
  • Символ — требуемый параметр. Значение символа, которое должно повторяться определенное количество раз.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   msgbox("Line 1 :" & String(3,"$"))
   msgbox("Line 2 :" & String(4,"*"))
   msgbox("Line 3 :" & String(5,100))
   msgbox("Line 4 :" & String(6,"ABCDE"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 :$$$
Line 2 :****
Line 3 :ddddd
Line 4 :AAAAAA

Возвращает строку с указанным символом для указанного количества раз.

StrReverse

Функция StrReverse меняет указанную строку.

Синтаксис

StrReverse(string)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   msgbox("Line 1 : " & StrReverse("VBSCRIPT"))
   msgbox("Line 2 : " & StrReverse("My First VBScript"))
   msgbox("Line 3 : " & StrReverse("123.45"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : TPIRCSBV
Line 2 : tpircSBV tsriF yM
Line 3 : 54.321

Возвращает строку после изменения последовательности символов данной строки.

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

VBA SubString

Excel VBA SubString

Excel VBA SubString is a very useful type of function in VBA which is used to slice and dice a data in a form of string. But in worksheet functions, we have three substring functions which are Left-right and mid function while in VBA we have Left-right mid and split functions as substring functions. As the name suggests itself substring function in VBA divides a string into multiple SubStrings. Also as explained above in VBA there are multiple VBA Substring functions. In this article, we will learn how to use these substring functions separately with examples. Before moving on with the examples first let us learn the syntax of these functions and what argument these functions take as input.

Syntax of Excel VBA SubString

Following are the different syntax:

Syntax of Left SubString Function:

Syntax of Left

Text string is the string we provide as input while the length is the number of characters we want from the input string.

Example: If we have a string as ANAND and want AN as substring the code will be

Left (“ANAND”,2)

Syntax of Right SubString Function:

Syntax of Right

Text string is the string we provide as input while the length is the number of characters we want from the input string.

Example: If we have a string as ANAND and use the same code as above the result will be

Right (“ANAND”,2)

This gives ND as a result.

Syntax of Mid SubString Function in VBA:

Syntax of Mid

Text string is the string we provide as input and Start position is the position where we want the character to start for extraction while the length is the number of characters we want from the input string.

Example: We have a string as COMPUTER and we want to PUT as the substring then the code will be as follows:

MID (“COMPUTER”,4,3)

Syntax of Split SubString Function:

Syntax of Split

  • Expression As String: This is a mandatory argument in the SPLIT function. It is basically the input string we provide.
  • Delimiter: This is an optional argument. It is the specific delimiter that divides the string but by default, space is considered as default delimiter.
  • Limit: This is also an optional argument. Limit means the maximum number of parts we want to do of a string. But again if we do not provide a limit to the function VBA treats it as default -1. This concludes that the string will be broken apart each time there is a delimiter in the string.
  • Compare: This final argument is also an optional argument. Compare is a compare method which is one of the two below:
  1. Either it is 0 which means SPLIT will perform a binary comparison which means every character should match itself.
  2. Or it can be 1 which means the SPLIT function will do a textual comparison.

Split Function is the trickiest and most useful among them all the substring functions above. All the other three substring functions use one string as input while Split function uses an array of string.

For example if I write Split(“I AM A GOOD BOY”) will divide the string as separately (each word as separate). Now let us use these substrings functions in examples.

Note: To use VBA we need to have the developer’s tab enabled from the file tab under the Options section.

How to Use SubString Functions in VBA?

We will learn how to use the SubString function in Excel by using the VBA Code.

You can download this VBA SubString Excel Template here – VBA SubString Excel Template

Example #1

Left Substring Function in VBA. Let us use the first substring function in VBA. For this, follow the below steps:

Step 1: Go to the developer’s Tab and click on Visual Basic to open VB Editor.

Developer Tab

Step 2: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 3: Declare a sub-function to start writing the code.

Code:

Sub Sample()

End Sub

Excel VBA SubString Example1-1

Step 4: Declare two strings one to take input from the user and another to store the value of the result.

Code:

Sub Sample()

Dim A, B As String

End Sub

Excel VBA SubString Example1-2

Step 5: Take the input from the user for the input string using the input box function.

Code:

Sub Sample()

Dim A, B As String
A = InputBox("Enter a String", "Single String")

End Sub

Input Box Example1-3

Step 6: In B variable store the value from the left function up to the third place.

Code:

Sub Sample()

Dim A, B As String
A = InputBox("Enter a String", "Single String")
B = Left(A, 3)

End Sub

VBA SubString Example1-4

Step 7: Use Msgbox function to display the final result.

Code:

Sub Sample()

Dim A, B As String
A = InputBox("Enter a String", "Single String")
B = Left(A, 3)
MsgBox B

End Sub

VBA SubString Example1-5

Step 8: Now run the above code by pressing the F5 key. and Write input String as ANAND.

Excel VBA SubString Example1-6

Step 9: When we press OK we see the result of the left substring function.

VBA SubString Example1-7

ANA is the three characters from the left of the string.

Example #2

RIGHT Substring function in VBA. For this, follow the below steps:

Step 1: In the same module declare another sub-function to start writing the code for the right substring function.

Code:

Sub Rightsub()

End Sub

VBA SubString Example1-8

Step 2: Declare two variables A and B as string.

Code:

Sub Rightsub()

Dim A, B As String

End Sub

VBA SubString Example1-9

Step 3: Take the input from user and store the value in A variable.

Code:

Sub Rightsub()

Dim A, B As String
A = InputBox("Enter a String", "Single String")

End Sub

VBA SubString Example1-10

Step 4: Use the Right function on the string to the third place and store the value in B variable.

Code:

Sub Rightsub()

Dim A, B As String
A = InputBox("Enter a String", "Single String")
B = Right(A, 3)

End Sub

Right function Example1-1

Step 5: Use Msgbox function to display the value of B.

Code:

Sub Rightsub()

Dim A, B As String
A = InputBox("Enter a String", "Single String")
B = Right(A, 3)
MsgBox B

End Sub

VBA SubString Example1-12

Step 6: Run the code and enter the input string as “MOTHER”.

VBA SubString Example1-13

Step 7: Press OK to see the result.

VBA SubString Example1-14

HER is the three characters from the right of the string.

Example #3

MID Substring Function in VBA. For this, follow the below steps:

Step 1: In the same module declare another sub-function to start writing the code for Mid function.

Code:

Sub MIDsub()

End Sub

Mid Function Example3-1

Step 2: Declare two variables A and B as String.

Code:

Sub MIDsub()

Dim A, B As String

End Sub

VBA SubString Example3-2

Step 3: Take input from the user and store the value in Variable A.

Code:

Sub MIDsub()

Dim A, B As String
A = InputBox("Enter a String", "Single String")

End Sub

VBA SubString Example3-3

Step 4: Use Mid function with starting position as 4 and length as 3 stores the value in B and display it using Msgbox function.

Code:

Sub MIDsub()

Dim A, B As String
A = InputBox("Enter a String", "Single String")
B = Mid(A, 4, 3)
MsgBox B

End Sub

MsgBox Example3-4

Step 5: Run the above code and give COMPUTER as input.

VBA SubString Example3-5

Step 6: Press OK to see the final result.

VBA SubString Example1-14

The substring PUT starts from 4th position and we have successfully extracted three characters.

Example #4

VBA Split SubString Function. For this, follow the below steps:

Step 1: In the same module declare a sub-function to start writing the code for sub-function.

Code:

Sub SplitSub()

End Sub

VBA SubString Example4-1

Step 2: Declare two Variables A as string and B as String array and take input string from the user and store it in Variable A.

Code:

Sub SplitSub()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Separate with Commas")

End Sub

VBA SubString Example4-2

Step 3: Use the Split SubString function and store its value in Variable B.

Code:

Sub SplitSub()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Separate with Commas")
B = Split(A, ",")

End Sub

Split Example4-3

Step 4: Use For loop to display every SubString in a single line.

Code:

Sub SplitSub()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Separate with Commas")
B = Split(A, ",")
For i = LBound(B) To UBound(B)
strg = strg & vbNewLine & "String Number " & i & " - " & B(i)
Next i
MsgBox strg

End Sub

For Loop Example4-4

Step 5 Run the above code and give I,AM,GOOD,BOY as input.

VBA SubString Example4-5

Step 6: Press OK to see the result.

VBA SubString Example4-6

We used “,” as a delimiter in the above example.

Conclusion

Like worksheet substring functions VBA also has substring functions. They are Left Right Mid and Split Functions. Basically Substring functions divide a string or an array of string into multiple substrings. If we want a substring from the left of the string we use Left function or right in the opposite case. If we want a middle character of any given string we use MID functions. Also if we have an array of strings we use split functions.

Things to Remember

There are few things which we need to remember about Substring functions in VBA:

  • It is similar to worksheet substring functions.
  • Substring functions divide a given string into substrings.
  • If we have an array of strings we use split functions.
  • Only the input string in split function is mandatory while the others are optional.

Recommended Articles

This is a guide to the VBA SubString. Here we discuss how to use the SubString function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys
  2. VBA On Error Goto
  3. VBA Input
  4. VBA LBound

На чтение 12 мин. Просмотров 18.3k.

VBA Instr

Функция VBA InStr является одной из наиболее часто используемых функций в VBA. Он используется для нахождения текста внутри строки и действительно отлично справляется с работой.

Тем не менее, она часто используется, чтобы помочь извлечь часть строки, и эту задачу она выполняет плохо.

Если вы обнаружили, что извлечение текста в VBA является болезненным процессом, тогда читайте дальше. Эта статья покажет вам более простой и лучший способ, используя три реальных примера!

Содержание

  1. Краткое руководство к статье
  2. Краткая справка
  3. Введение
  4. Когда VBA InStr, Left, Right и Mid полезны
  5. Работа со строками различной длины
  6. Использование функции VBA InStr с Mid
  7. Функция Split
  8. Пример 1: Получение части имени файла
  9. Пример 2: диапазон IP-адресов
  10. Пример 3. Проверьте правильность имени файла
  11. Заключение

Краткое руководство к статье

В следующей таблице приведено краткое руководство к тому, что рассматривается в этой статье.

Строка Тип Задача Как
1234ABC334 Фиксированный размер Оставить слева 4 символа Left(s,4)
1234ABC334 Фиксированный размер Оставить
справа 3
символа
Right(s,3)
1234ABC334 Фиксированный размер Оставить 5, 6, 7 символы Mid(s,5,3)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить имя Split(s,» «)(0)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
отчество
Split(s,» «)(1)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
фамилию
Split(s,» «)(2)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
фамилию
Dim v As
Variant
v = Split(s, » «)
lastname= v(UBound(v))

Краткая справка

Чтобы узнать больше об элементах, упомянутых в статье, перейдите по следующим ссылкам:

  • Если вы хотите узнать больше о функциях InStr или InStrRev, пожалуйста, прочитайте Поиск в строке.
  • Если вы хотите узнать больше о функциях Mid, Left или Right, посмотрите раздел Извлечение части строки.
  • Для получения дополнительной информации о функции Split проверьте Строка в массив, используя Split.
  • Оператор Like включен в Сравнение строк с шаблоном

Я использую Debug.Print в моих примерах. Он печатает значения в Immediate Window, которое вы можете просмотреть, нажав Ctrl + G (или выберите View-> Immediate Window)

Введение

В этой статье я собираюсь показать вам лучший способ извлечения символов из строки, чем использование функции VBA InStr с Left, Right или Mid.

Эта статья разбита следующим образом:

  • Раздел 1: Как извлечь из строк фиксированного размера.
  • Раздел 2: Как извлечь из строк переменного размера.
  • Раздел 3: Как извлечь из строки переменного размера, используя функцию Split.
  • Разделы с 4 по 6: некоторые примеры из реальной жизни.

Когда VBA InStr, Left, Right и Mid полезны

Если вы хотите проверить, содержит ли строка значение, InStr подходит для этой работы. Если вы хотите сделать простое извлечение, то отлично подойдут Left, Right и Mid.

Использование InStr для проверки, содержит ли строка текст

В следующем примере мы проверяем, содержит ли ФИО «Петрович». Если возвращаемое значение InStr больше нуля, то строка содержит значение, которое мы проверяем.

' Проверьте, содержит ли строка Петрович
    If InStr("Иван Петрович Сидоров", "Петрович") > 0 Then
        Debug.Print "Найдено"
    End If

Извлечение с Left, Right и Mid

Функция Left используется для получения символов слева от строки.
Функция Right используется для получения символов справа от строки.
Функция Mid используется для середины строки. Она такая же, как
Left, за исключением того, что вы даете ему стартовую позицию.

Sub IzvlechTekst()

    Dim s As String: s = "ABCD-7789.WXYZ"

    Debug.Print Left(s, 2) ' Печатает AB
    Debug.Print Left(s, 4) ' Печатает ABCD

    Debug.Print Right(s, 2) ' Печатает YZ
    Debug.Print Right(s, 4) ' Печатает WXYZ

    Debug.Print Mid(s, 1, 2) ' Печатает AB
    Debug.Print Mid(s, 6, 4) ' Печатает 7789

End Sub

VBA Left, Right and Mid

Эти три функции работают нормально, если требуемый текст всегда одинакового размера и в одном и том же месте. Для других сценариев они требуют использования InStr, чтобы найти определенную позицию в строке. Это усложняет их использование.

Используйте Left, Right или Mid, когда символы всегда будут в одной и той же позиции.

Работа со строками различной длины

Многие из строк, с которыми вы имеет дело, разной длины. Простой пример — когда у вас есть дело со списком имен. Длина строки и требуемая часть (например, имя) могут каждый раз отличаться. Например:

Brooke Hilt
Pamela Jurado
Zack Kinzel
Eddy Wormley
Kaitlyn Rainer
Jacque Trickett
Kandra Stanbery
Margo Hoppes
Berenice Meier
Garrett Hyre

(Если вам нужен случайный список имен, попробуйте этот генератор случайных имен)

Использование функции VBA InStr с Left

В следующем примере мы собираемся получить имя из строки. В этой строке первое имя — это имя перед первым пробелом.

Мы используем функцию VBA InStr, чтобы получить позицию первого пробела. Мы хотим получить все символы до пробела. Мы вычитаем одну из позиции, так как это дает нам позицию последней буквы имени.

Sub PoluchitImya()

    Dim s As String, lPosition As Long

    s = "John Henry Smith"
    ' Печатает John
    lPosition = InStr(s, " ") - 1
    Debug.Print Left(s, lPosition)

    s = "Lorraine Huggard"
    ' Печатает Lorraine
    lPosition = InStr(s, " ") - 1
    Debug.Print Left(s, lPosition)

End Sub

Давайте посмотрим на первый пример в приведенном выше коде. Первый пробел находится в позиции 5. Мы вычтем 1, что дает нам позицию 4. Это позиция последней буквы John, т.е.

VBA InStr and Left

Затем мы даем 4 функции Left, и она возвращает первые четыре символа, например, «John»

Мы можем выполнить ту же задачу в одной строке, передав возвращаемое значение из InStr в функцию Left.

 Dim s As String
    s = "John Henry Smith"

    ' Печатает John
    Debug.Print Left(s, InStr(s, " ") - 1)

Использование функции VBA InStr с Right

В этом примере мы получим последнее слово в строке, то есть Smith. Мы можем использовать функцию InStrRev. Это то же самое, что InStr, за исключением того, что поиск выполняется с конца строки.

Важно отметить, что InStrRev дает нам позицию с начала строки. Поэтому нам нужно использовать его немного иначе, чем мы использовали InStr и Left.

Sub PoluchitFamiliyu()

    Dim s As String: s = "John,Henry,Smith"
    Dim Position As Long, Length As Long

    Position = InStrRev(s, ",")
    Length = Len(s)

    ' Печатает Smith
    Debug.Print Right(s, Length - Position)

    ' Альтернативный метод. Печатает Smith - делает в одну строку
    Debug.Print Right(s, Len(s) - InStrRev(s, ","))

End Sub

Как работает приведенный выше пример:

  • Мы получаем позицию последнего пробела, используя InStrRev: 11
  • Мы получаем длину строки: 16.
  • Вычитаем позицию из длины: 16-11 = 5
  • Мы даем 5 функции Right и возвращаем Smith

VBA Instr and Right

Использование функции VBA InStr с Mid

В следующем примере мы получим «Henry» из строки. Слово, которое мы ищем, находится между первым и вторым пробелом.

Мы будем использовать функцию Mid здесь.

Sub PoluchitVtoroeImya()

    Dim s As String: s = "John Henry Smith"

    Dim firstChar As Long, secondChar As Long
    Dim count As Long

    ' Найти пробел плюс 1. Результат 6
    firstChar = InStr(s, " ") + 1
    ' Найти 2-й пробел. Результат 11
    secondChar = InStr(firstChar, s, " ")
    ' Получить число символов. Результат 5
    count = secondChar - firstChar

    ' Печатает Henry
    Debug.Print Mid(s, firstChar, count)

End Sub

Как видите, это сложно сделать и требует немного усилий, чтобы выяснить. Нам нужно найти первое место. Тогда нам нужно найти второе место. Затем мы должны вычесть одно из другого, чтобы дать нам количество символов, которые нужно взять.

VBA Instr and Mid

Если у вас есть строка с большим количеством слов, то это может быть очень сложно. К счастью для нас, гораздо проще было извлечь символы из строки. Это называется функцией Split.

Функция Split

Мы можем использовать функцию Split для выполнения приведенных выше примеров. Функция Split разбивает строку на массив. Тогда мы можем легко получить доступ к каждому элементу.

Давайте попробуем те же три примера еще раз, и на этот раз мы будем использовать Split.

  Dim s As String: s = "John Henry Smith"

    Debug.Print Split(s, " ")(0) ' John
    Debug.Print Split(s, " ")(1) ' Henry
    Debug.Print Split(s, " ")(2) ' Smith

Ого! Какая разница с использованием Split. Как это работает:

  1. Функция Split разбивает строку везде, где есть пробел.
  2. Каждый элемент помещается в массив, начиная с нуля.
  3. Используя номер местоположения, мы можем получить доступ к элементу массива.  

В следующей таблице показано, как может выглядеть массив после использования Split.

Примечание: первая позиция в массиве равна нулю. Наличие нулевых массивов является стандартным в языках программирования.

0 1 2
John Henry Smith

В приведенном выше коде мы разделяем строку каждый раз, когда ее используем. Мы также можем разделить строку один раз и сохранить ее в переменной массива. Тогда мы можем получить к нему доступ, когда захотим.

Sub SplitName()
    Dim s As String: s = "John Henry Smith"
    Dim arr() As String
    arr = Split(s, " ")

    Debug.Print arr(0) ' John
    Debug.Print arr(1) ' Henry
    Debug.Print arr(2) ' Smith
End Sub

Если вы хотите узнать больше о массивах, я написал о них целую статью под названием «Полное руководство по использованию массивов в Excel VBA».

В следующих разделах мы рассмотрим примеры из реальной жизни. Вы увидите преимущество использования Split вместо функции InStr.

Пожалуйста, не стесняйтесь попробовать это сами. Это отличный способ учиться, и вы можете повеселиться, пытаясь понять их (или, может быть, только у меня так!)

Пример 1: Получение части имени файла

Представьте, что мы хотим извлечь числа из следующих имен файлов

«VB_23476_Val.xls»
«VV_987_Val.txt»
«VZZA_12223_Val.doc»

Это похоже на пример, где мы получаем второй элемент. Чтобы получить значения здесь, мы используем подчеркивание (то есть «_»), чтобы разбить строку. Смотрите пример кода ниже:

Sub PoluchitNomer()

    ' Печатает 23476
    Debug.Print Split("VB_23476_Val.xls", "_")(1)
    ' Печатает 987
    Debug.Print Split("VV_987_Val.txt", "_")(1)
    ' Печатает 12223
    Debug.Print Split("ABBZA_12223_Val.doc", "_")(1)

End Sub

В реальном мире вы обычно читаете такие строки из разных ячеек. Допустим, эти имена файлов хранятся в ячейках от А1 до А3. Мы немного изменим приведенный выше код:

Sub ChitatNomera()

    Dim c As Range
    For Each c In Range("A1:A3")
        ' Разделите каждый элемент по мере его прочтения
        Debug.Print Split(c, "_")(1)
    Next c

End Sub

Пример 2: диапазон IP-адресов

Пример здесь взят из вопроса на веб-сайте StackOverflow.

У пользователя есть строка с IP-адресом в формате «BE-ABCDDD-DDS 172.16.23.3».

Он хочет, чтобы IP в диапазоне от 172,16 до 172,31 был действительным. Так например:

  • «BE-ABCDDD-DDS 172.16.23.3» действителен
  • «BE-ABCDDD-DDS 172.25.23.3» действителен
  • «BE-ABCDDED-DDS 172.14.23.3» не действителен
  • «BE-ABCDDDZZ-DDS 172.32.23.3» не действителен

Вот как бы я это сделал. Сначала я разбил строку по периодам. Число, которое мы ищем, находится между первым и вторым периодом. Поэтому это второй пункт. Когда мы разделяем строку, она помещается на первую позицию в массиве (помните, что массив начинается с нулевой позиции).

Полученный массив будет выглядеть так:

0 1 2 3
BE-ABCDDD-DDS 172 31 23 3

Код ниже показывает, как это сделать.

Sub IPAdd()

    ' Проверьте номер, чтобы проверить разные IP-адреса
    Dim s1 As String: s1 = "BE-ABCDDD-DDS 172.31.23.3"

    ' Разбить строку, используя символ точки
    Dim num As Long
    num = Split(s1, ".")(1)

    ' Проверьте правильность номера
    Debug.Print num >= 16 And num <= 31

End Sub

Пример 3. Проверьте правильность имени файла

В этом последнем примере мы хотим проверить правильность имени файла. Есть три правила.

  1. Должно заканчиваться на .pdf
  2. Он должен содержать АА
  3. Он должен содержать 1234 после А

В следующих таблицах показаны некоторые допустимые и недействительные элементы:

Имя файла Статус
AA1234.pdf Действителен
AA_ljgslf_1234.pdf Действителен
AA1234.pdf1 Недействительно — не заканчивается на .pdf
1234 AA.pdf Недействительно — АА не до 1234
12_AA_1234_NM.pdf Действителен

Сначала мы сделаем это, используя функции InStr и Right.

Sub IspInstr()

    Dim f As String: f = "AA_1234_(5).pdf"

    ' Сначала найдите АА, так как 1234 должен идти после
    Dim lPos As Long: lPos = InStr(f, "AA")
    ' Ищите 1234 и убедитесь, что последние четыре символа - .pdf
    Debug.Print InStr(lPos, f, "1234") > 0 And Right(f, 4) = ".pdf"

End Sub

Этот код очень грязный. К счастью для нас, у VBA есть Сравнение с шаблоном. Мы можем проверить шаблон строки без необходимости искать элементы и позиции и т.д. Мы используем оператор Like в VBA для сопоставления с шаблоном. Пример ниже показывает, как это сделать.

Sub IspSravnenie()

    Dim f As String: f = "AA_1234_(5).pdf"

    ' Определить шаблон
    Dim pattern As String: pattern = "*AA*1234*.pdf"
    ' Проверьте каждый элемент по шаблону
    Debug.Print f Like pattern   ' ИСТИНА

End Sub

В приведенном выше примере звездочка в шаблоне относится к любому количеству символов.

Давайте разберем этот паттерн * AA * 1234 * .pdf

*- любая группа символов
AA — точные символы AА

*- любая группа символов
1234 — точные символы 1234

*- любая группа символов
.pdf — точные символы .pdf

Чтобы показать, что это работает правильно, давайте попробуем это на всех именах примеров в таблице.

Sub IspSravnenieTest()

    ' Создать коллекцию имен файлов
    Dim coll As New Collection
    coll.Add "AA1234.pdf"
    coll.Add "AA_ljgslf_1234.pdf"
    coll.Add "AA1234.pdf1"
    coll.Add "1234 AA.pdf"
    coll.Add "12_AA_1234_NM.pdf"

    ' Определить шаблон
    Dim pattern As String: pattern = "*AA*1234*.pdf"

    ' Проверьте каждый элемент по шаблону
    Dim f As Variant
    For Each f In coll
        Debug.Print f Like pattern
    Next f

End Sub

На выходе:

ИСТИНА
ИСТИНА
ЛОЖЬ
ЛОЖЬ
ИСТИНА

Чтобы узнать больше о сопоставлении с шаблоном и ключевом слове Like, ознакомьтесь с этой публикацией.

Заключение

InStr и InStrRev действительно полезны только для простых задач, таких как проверка наличия текста в строке.

Left, Right и Mid полезны, когда положение текста всегда одинаково.

Функция Split — лучший способ извлечь переменную строку.

При попытке проверить формат строки, которая не является фиксированной по размеру, ключевое слово Like (т.е. Сопоставление с образцом) обычно обеспечивает более простое решение.

Понравилась статья? Поделить с друзьями:
  • Vba excel среднее значение
  • Vba excel среднее арифметическое
  • Vba excel сравнить столбец
  • Vba excel сравнить значения ячеек
  • Vba excel сумма прописью с копейками