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

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

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

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 (т.е. Сопоставление с образцом) обычно обеспечивает более простое решение.

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

In this Article

  • Left Function
    • VBA Left Function n First Characters
    • VBA Left Function n First Characters in a Variable
    • VBA Left Function n First Characters in a Cell
    • VBA Left Function Trim off the Last Letter
    • VBA Left to Extract First Name
  • VBA Left$ Function vs Left Function

This tutorial will demonstrate how to use the Left VBA Function.

Left Function

The VBA Left function returns the first n characters from a string.

VBA Left Function n First Characters

The VBA Left function returns the first n characters from a string:

Sub LeftExample_1()
MsgBox Left("ABCDEFGHI", 4)        'Result is: "ABCD"
MsgBox Left("ABCDEFGHI", 2)        'Result is: "AB"
MsgBox Left("ABCDEFGHI", 1)        'Result is: "A"
MsgBox Left("ABCDEFGHI", 100)      'Result is: "ABCDEFGHI"
End Sub

VBA Left Function n First Characters in a Variable

As shown above, you can define a string simply by entering text surrounded by quotation marks. But the LEFT Function will also work with string variables. These examples will extract the first n characters from a string variable.

Sub LeftExample_2()
Dim StrEx As String 'Define a string variable

StrEx = "ABCDEFGHI"

MsgBox Left(StrEx, 4)   'Result is: "ABCD"
MsgBox Left(StrEx, 2)   'Result is: "AB"
MsgBox Left(StrEx, 1)   'Result is: "A"
MsgBox Left(StrEx, 100) 'Result is: "ABCDEFGHI"

End Sub

VBA Left Function n First Characters in a Cell

Strings can be defined in VBA code but also you can use values from cells. Read the value of a cell, keep it in a string variable, and extract n first characters from that Worksheet Cell value.

left cell value vba

Sub LeftExample_3()
Dim StrEx As String 'Define a string variable

'Read the value of cell A1 in worksheet Sheet1
StrEx = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value

'For this example the value of cell A1 is "A bCDEFGHI"

MsgBox Left(StrEx, 4)   'Result is: "ABCD"
MsgBox Left(StrEx, 2)   'Result is: "AB"
MsgBox Left(StrEx, 1)   'Result is: "A"
MsgBox Left(StrEx, 100) 'Result is: "ABCDEFGHI"
End Sub

VBA Left Function Trim off the Last Letter

To remove letters from the end of a string, use the LEFT Function along with the LEN Function.

The VBA LEN function counts the number of characters in a string:

Len(StrEx)

By combining the functions, we can remove a certain number of characters from the end of the string:

Sub LeftExample_4()
Dim StrEx As String 'Define a string variable

StrEx = "ABCDEF"

MsgBox Left(StrEx, Len(StrEx))     'Result is: "ABCDEF"
MsgBox Left(StrEx, Len(StrEx) - 1) 'Result is: "ABCDE"
MsgBox Left(StrEx, Len(StrEx) - 2) 'Result is: "ABCD"
End Sub

To extract the first name from a string with a full name, use the Left Function along with the Instr Function.

The VBA Instr function searches for a substring inside a string and returns the position number of the substring.

InStr(StrEx, " ")

By combining the functions, we can extract the first word from a phrase:

Sub LeftExample_5()
Dim StrEx As String 'Define a string variable

StrEx = "Alexander Graham Bell"

MsgBox Left(StrEx, InStr(StrEx, " "))
'Result is: "Alexander "                   (notice the space at the end)

MsgBox Left(StrEx, InStr(StrEx, " ") - 1)
'Result is: "Alexander"                   (NO space at the end)

StrEx = "Leonardo da Vinci"

MsgBox InStr(StrEx, " ")
'Result is: 9 because space is found in position 9

MsgBox Left(StrEx, InStr(StrEx, " ") - 1)
'Result is: "Leonardo"
End Sub

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

VBA Left$ Function vs Left Function

Both the Left and the Left$ function will return the same answer if the variable where the data is being returned to is declared as a string. However, if the variable has been declared as a variant, then the Left function is allowed to return NULL values whereas the Left$ function can only return string values.

If, for example, you are truing to return some data from an Access query, but the data returned is a NULL value, the Left$ function will return an error.

Have a look at the code below:

leftleft string

In the above example, even though our variable has been declared as a variant, the Left$ function prevents the variable being populated with the NULL value.

In the code below however, the variable is populated with the NULL value.

left left populate variant

VBA Left Function

VBA Left Function

Left Function is used to extract N number of characters from a string from the left side. Left function is one of the VBA inbuilt functions that MS Excel provides. N is the number of characters which a user wants to extract from the string.

In other words, we use the Left VBA function to extract the leftmost substring from a string given by the user in excel. It can be used as a VBA function as well as a worksheet function in the excel. It can be used as the as a part of the formula in the cell.

Syntax of Left Function in Excel VBA

VBA Left function has the following syntax:

Syntax of Left

How to Use Excel VBA Left Function?

We will learn how to use a VBA Left function with few examples in Excel.

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

VBA Left Function – Example #1

Let’s assume, there is a text_1 string which value is ‘Microsoft Excel’. If a user wants to display only the first word of the string. So, how a user will be able to display the first word only.

Here the Left function can solve his problem, So follow the below steps to use Left function in Excel VBA.

Step 1: Open the MS Excel, go to Example #1 Sheet where the user wants to display the first word from the string ‘Microsoft Excel’.

Step 2: Go to the Developer tab >> Click on the Visual Basic.

VBA Left Example 1-1

Step 3: Create one Left_Example1() micro and inside declare a string as the text_1.

Code:

Sub Left_Example1()

  Dim text_1 As String

End Sub

VBA Left Example 1-2

Step 4: Assign text_1 the result of the left function output.

Code:

Sub Left_Example1()

  Dim text_1 As String

  text_1 = Left("Microsoft Excel", 9)

End Sub

VBA Left Example 1-3

Step 5: For display the result a user needs to add MsgBox.

Code:

Sub Left_Example1()

  Dim text_1 As String

  text_1 = Left("Microsoft Excel", 9)

  MsgBox ("First string is the: " & text_1)

End Sub

VBA Left Example 1-4

Step 6: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 1-5

Summary of Example #1:

As the user wants to display the first word from the string by using the left function we have achieved the output.

VBA Left Function – Example #2

Let’s find out how to use the Left Function in MS Excel for getting the first name of the employee from the employee table.

Let’s assume, there is an employee table in which some strings are available like ‘Employee Name’, ‘Home City’ and a monthly salary of each employee. If a user wants to display only the first Name of each employee of his office. So, how a user will be able to display the first name only.

Here the Left function can solve this problem, So follow the below steps to use Left function in Excel VBA.

Step 1: Open MS Excel, go to Example #2 Sheet where the user wants to display the first Name from the Employee data table.

VBA Left Example 2-1

Step 2: Go to the developer tab >> Click on the Visual Basic.

Step 3: Create one Left_Example2() micro and inside declare a string as the FirstName and ‘i’ as an integer for a loop.

Code:

Sub Left_Example2()

  Dim FirstName As String
  Dim i As Integer

End Sub

VBA Left Example 2-2

Step 4: Start loop and assign FirstName the result of the left function output.

Code:

Sub Left_Example2()

  Dim FirstName As String
  Dim i As Integer

  For i = 2 To 13
  FirstName = Left(Cells(i, 1).Value, InStr(1, Cells(i, 1).Value, " ") - 1)
  Cells(i, 5).Value = FirstName
  Next i

End Sub

VBA Left Example 2-3

Step 5: For display, the completion of a task just add a MsgBox.

Code:

Sub Left_Example2()

  Dim FirstName As String
  Dim i As Integer

  For i = 2 To 13
  FirstName = Left(Cells(i, 1).Value, InStr(1, Cells(i, 1).Value, " ") - 1)
  Cells(i, 5).Value = FirstName
  Next i

  MsgBox ("Fetching First Name task is completed!")

End Sub

VBA Left Example 2-4

Step 6: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 2-5

Summary of Example #2:

As the user wants to display the first name from the employee table by using the left function we have achieved the output.

VBA Left Function – Example #3

Let’s see how to use the Left Function in the MS Excel for getting salary in thousands of employees from the employee table.

Let’s assume, there is an employee table in which some strings are available like ‘Employee Name’, ‘Home City’ and a monthly salary of each employee. If a user wants to display only the salary in thousands of each employee of his office. So, how a user will be able to display the first name only.

Here the Left function can solve this problem, So follow the below steps to use Left function in Excel VBA.

Step 1: Open MS Excel, go to Example #3 Sheet where the user wants to display the salary in thousands from the Employee data table.

VBA Left Example 3-1

Step 2: Go to the developer tab >> Click on the Visual Basic.

Step 3: Create one Left_Example3() micro and inside declare a string as the Salary and ‘i’ as an integer for loop

Code:

Sub Left_Example3()

  Dim Salary As String
  Dim i As Integer

End Sub

VBA Left Example 3-2

Step 4: Start loop and assign FirstName the result of the left function output.

Code:

Sub Left_Example3()
  Dim Salary As String
  Dim i As Integer

  For i = 2 To 13
  Salary = Left(Cells(i, 3).Value, 2)
  Cells(i, 5).Value = Salary
  Next i

End Sub

 Example 3-3

Step 5: For display, the completion of a task just adds a MsgBox.

Code:

Sub Left_Example3()

  Dim Salary As String
  Dim i As Integer

  For i = 2 To 13
  Salary = Left(Cells(i, 3).Value, 2)
  Cells(i, 5).Value = Salary
  Next i
 
  MsgBox ("Fetching salary in Thousand task is completed!")

End Sub

Example 3-4

Step 6: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 3-5

Summary of Example #3:

As the user wants to display the salary in Thousands from the employee table by using the left function we have achieved the output.

Things to Remember

  • The Left function always returns string/text as the output in excel VBA.
  • If the Text value is Null, then it will return Null as the output.
  • The Left function can extract characters from the left side only.
  • We can use InStr function to find the space in VBA, by this a user can easily differentiate the word in the sentence.
  • Whenever a user needs a substring from the left side in the provided string they need to use the Left function to get it.

Recommended Articles

This has been a guide to VBA Left Function. Here we discussed on how to use Excel VBA Left Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA VLOOKUP
  2. VBA IsError
  3. VBA Match
  4. VBA RGB

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