Как найти символ в строке vba

In this Article

  • INSTR Function
    • Instr Example
    • Instr Syntax
    • Instr Start Position
    • Case-Insensitive INSTR Test
  • InstrRev Function
  • VBA Coding Made Easy
  • InString Examples
    • If String Contains Substring
    • Find Text String in a Cell
    • Find Position of a Character in a String
    • Search String for Word
    • If Variable Contains String
    • Instr and the Left Function
  • Using Instr in Microsoft Access VBA

INSTR Function

The VBA Instr Function checks if a string of text is found in another string of text.  It returns 0 if the text is not found. Otherwise it returns the character position where the text is found.

The Instr Function performs exact matches. The VBA Like Operator can be used instead to perform inexact matches / pattern matching by using Wildcards.

Instr Example

The following code snippet searches the string “Look in this string” for the word “Look”. The Instr Function returns 1 because the text is found in the first position.

Sub FindSomeText()
  MsgBox InStr("Look in this string", "Look")
End Sub

This second example returns 7 because the text is found starting in the 7th position:

Sub FindSomeText2()
  MsgBox InStr("Don't Look in this string", "Look")
End Sub

Important! The Instr Function is case-sensitive by default. This means “look” will not match with “Look”. To make the test case-insensitive read below.

Instr Syntax

The syntax for the Instr function is as follows:

Instr( [start], string, substring, [compare] )

[start] (optional) – This optional argument is the starting position of the search. Enter 1 to start searching from position 1 (or leave blank). Enter 5 to start searching from position 5. Important! The INSTR function calculates the character position by counting from 1 NOT from the [start] position.

string – The string of text to search in.

substring – The string of text to find in the primary string.

[compare] (optional) – By default, Instr is case-sensitive. By setting this argument you can make Instr Case insensitive:

Argument vb Value

Argument Integer Description
vbBinaryCompare

0

(Default) Case-sensitive

vbTextCompare

1

Not Case-sensitive

vbDatabaseCompare

2

MS Access Only. Uses information in the database to perform comparison.

Instr Start Position

The Instr start position allows you to indicate the character position where you will begin your search.  Keep in mind however, the Instr output will always count from 1.

Here we set the start position to 3 to skip the first B:

Sub Instr_StartPosition()
  MsgBox InStr(3, "ABC ABC", "B")
End Sub

The result is 6 because the second B is the 6th character in the string.

Case-Insensitive INSTR Test

By default, VBA treats “L” different from “l”. In other words, VBA is case-sensitive. This is true of all text functions.  To make VBA case-insensitive, set the [compare] argument to 1 or vbTextCompare.

Public Sub FindText_IgnoreCase()
  MsgBox InStr(1, "Don't Look in this string", "look", vbTextCompare)
End Sub

Alternatively, you can add Option Compare Text to the top of your code module:

Option Compare Text
Option Compare Text

Public Sub FindText_IgnoreCase2()
  MsgBox InStr("Don't Look in this string", "look")
End Sub

Option Compare Text will impact all of the code in that module. I personally place this at the top of any module that deals with text because I never care about case differences.

InstrRev Function

The Instr Function searches from the left. Instead you can search from the right using the InstrRev Function.  The InstrRev Function works very similarly to the Instr function.

Sub FindSomeText_FromRight()
  MsgBox InStrRev("Look in this string", "Look")
End Sub

Just like the Instr function this will return 1 because there is only one instance of “Look” in the text. But if we add a second “Look”, you’ll see that it returns the position of the right-most “Look”:

Sub FindSomeText_FromRight()
  MsgBox InStrRev("Look in this string Look", "Look")
End Sub

Next we will review more Instr examples.

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!

VBA Instr

Learn More!

InString Examples

If String Contains Substring

Here we will use an If statement to test if a string contains a a substring of text:

Public Sub FindSomeText()

If InStr("Look in this string", "look") = 0 Then
   MsgBox "No match"
Else
   MsgBox "At least one match"
End If

End Sub

Find Text String in a Cell

You can also find a string in a cell:

Sub Find_String_Cell()
    If InStr(Range("B2").Value, "Dr.") > 0 Then
        Range("C2").Value = "Doctor"
    End If
End Sub

vba find text in cell

Or loop through a range of cells to test if the cells contain some text:

Sub Search_Range_For_Text()
Dim cell As Range

    For Each cell In Range("b2:b6")
        If InStr(cell.Value, "Dr.") > 0 Then
            cell.Offset(0, 1).Value = "Doctor"
        End If
    Next cell
    
End Sub

search range for text

VBA Programming | Code Generator does work for you!

Find Position of a Character in a String

This code will find the position of a single character in a string and assign the position to a variable:

Sub Find_Char()
  Dim n As Long
  n = InStr("Here Look Here", "L")
End Sub

Search String for Word

This code will search a string for a word:

Sub Search_String_For_Word()
    Dim n As Long
    n = InStr("Here Look Here", "Look")
  
    If n = 0 Then
        MsgBox "Word not found"
    Else
        MsgBox "Word found in position: " & n
    End If
End Sub

If Variable Contains String

This code will test if a string variable contains a string of text:

Sub Variable_Contains_String()
    Dim str As String
    str = "Look Here"
    
    If InStr(str, "Here") > 0 Then
        MsgBox "Here found!"
    End If
End Sub

Instr and the Left Function

Instr can be used along with other text functions like Left, Right, Len, and Mid to trim text.

With the Left function you can output the text prior to a string of text:

Sub Instr_Left()
    Dim str As String
    Dim n As Long
    
    str = "Look Here"
    
    n = InStr(str, "Here")
    
    MsgBox Left(str, n - 1)

End Sub

Using Instr in Microsoft Access VBA

All of the above examples work exactly the same in Access VBA as in Excel VBA.

vba instr access

To learn more, read our article: VBA text functions

<<Return to VBA Examples

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

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

InStr Function in Excel VBA

The VBA InStr function helps find the position of a given substring within a string. It returns the first occurrence of the substring in the form of an integer (output). A string is a series of characters or text supplied to the function in double quotation marks.

For example, the InStr can extract a substring from a sentence, apply the desired font to a particular string, find the position of a character within the string, and so on.

The VBA InStr function in excel begins searching from left to right.

Table of contents
  • InStr Function in Excel VBA
    • The Syntax of the VBA InStr Function
    • VBA InStr Examples
      • Example #1–“Start” Argument is Omitted
      • Example #2–“Start” Argument is Specified
      • Example #3–Case-sensitive Search
      • Example #4–Case-insensitive Search
      • Example #5–Advanced Level
    • Properties of VBA InStr Function
    • Frequently Asked Questions
    • Recommended Articles

VBA InStr

The Syntax of the VBA InStr Function

The syntax of the function is shown in the following image:

Instr Function

The function accepts the following arguments:

  • Start: This is the position from which the function begins to search. For example, if “start” is set at 3 and the character “a” is to be found in the word “Bangalore,” the output is 5.
  • String 1: This is the actual string within which the substring is to be found. For example, if the character “a” is to be found in the word “Bangalore,” “string 1” is “Bangalore.”
  • String 2: This is the substring to be found. For example, if the character “a” is to be found in the word “Bangalore,”“string 2” is “a.”
  • Compare: This is the type of comparison to be performed. The types of comparison methods are shown in the following image.

vba inStr

The three comparison methods are explained as follows:

1. vbBinaryCompare: This is a binary comparison and can be entered as zero (0). It is a case-sensitive search of the substring (string 2) in the actual string (string 1).

For example, if 0 is specified in the argument and:

a. The character “a” is to be found in the word “Bangalore,” the output is 2.

b. The character “A” is to be found in the word “Bangalore,” the output is 0. This is because the supplied string is in uppercase which is not found in “string 1.”

2. vbTextCompare: This is a textual comparison and can be entered as one (1). It is a case-insensitive search of the “string 2” in the “string 1.”

For example, if 1 is specified in the argument and:

a. The character “a” is to be found in the word “Bangalore,” the output is 2.

b. The character “A” is to be found in the word “Bangalore,” the output is 2. This is because this comparison method ignores the casing of the substring.

3. vbDatabaseCompare: This can be entered as two (2). It compares based on the information of the Microsoft Access database.

The “string 1” and “string 2” are required arguments, while “start” and “compare” are optional.

Note 1: If the “start” parameter is omitted, the default is 1, implying that the search begins from the first position.

Note 2: If the “compare” parameter is omitted, the default method is “vbBinaryCompare.”

VBA InStr Examples

You can download this VBA Instr Function Excel Template here – VBA Instr Function Excel Template

Example #1–“Start” Argument is Omitted

We have to find the position of character “a” in the word “Bangalore.”

Step 1: Enter the following code.

Sub Instr_Example1()

Dim i As Variant

i = InStr("Bangalore", "a")

MsgBox i

End Sub

Step 2: Press F5 or run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more manually, as shown in the following image.

VBA InStr Example 1-2

Step 3: The output is 2, as shown in the following image. Hence, the character “a” is at the second position in the word “Bangalore.”

VBA Instr Example 1-2

Example #2–“Start” Argument is Specified

We have to find the position of character “a” in the word “Bangalore.” The search should begin from the third position.

Step 1: Enter the following code.

Sub Instr_Example2()

Dim i As Variant

i = InStr(3, "Bangalore", "a")

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. 

VBA InStr Example 2-2

Step 3: The output is 5, as shown in the following image. Since the search begins from the third letter (n), the VBA InStr function in excel ignores the first occurrence (second position) of the character “a.”

Hence, in this case, the character “a” is at the fifth position in the word “Bangalore.”

VBA Instr Example 2-2

Example #3–Case-sensitive Search

We have to find the character “A” in the word “Bangalore.”

Let us supply the compare argument “vbBinaryCompare” to the VBA InStr function.

Step 1: Enter the following code.

Sub Instr_Example3()

Dim i As Variant

i = InStr(1, "Bangalore", "A", vbBinaryCompare)

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. 

VBA InStr Example 3-2

Step 3: The output is 0, as shown in the following image. Since the argument “vbBinaryCompare” is supplied, the VBA InStr function in excel searches for the uppercase letter “A.”

Hence, the function returns 0 because it could not find the uppercase letter “A” in the word “Bangalore.”

VBA Instr Example 3-2

Example #4–Case-insensitive Search

We have to find the character “A” in the word “Bangalore” using the case-insensitive approach.

Let us supply the compare argument “vbTextCompare” to the VBA InStr function.

Step 1: Enter the following code.

Sub Instr_Example4()

Dim i As Variant

i = InStr(1, "Bangalore", "A", vbTextCompare)

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image.

VBA InStr Example 4-2

Step 3: The output is 2, as shown in the following image. Since the argument “vbTextCompare” is supplied, the InStr function ignores the casing of the substring “A.”

Hence, the function returns 2 because the letter “A” or “a” is present at the second position in the word “Bangalore.”

Example 4-2

Example #5–Advanced Level

Let us consider an example of the advanced level of VBA InStr function in excel.

The succeeding image shows five worksheets in Excel with the names, “Data,” “Summary 1,” “Summary 2,” “Summary 3,” and “Summary 4.”

We want to hide all worksheets except for the sheet “Data.”

Example 5

Step 1: Enter the following code to hide all those sheets which contain the word “Summary” in their name.

Sub To_Hide_Specific_Sheet()

Dim Ws As Worksheet

For Each Ws In ActiveWorkbook.Worksheets

If InStr(Ws.Name, "Summary") > 0 Then
Ws.Visible = xlSheetVeryHidden
End If

Next Ws
'InStr function looks for word or phrase in the sheet name
'If it finds then it will be hidden
End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. In the output, only the sheet “Data” is visible. The remaining four sheets are hidden.

Example 5-2

Likewise, we can unhide those sheetsThere are different methods to Unhide Sheets in Excel as per the need to unhide all, all except one, multiple, or a particular worksheet. You can use Right Click, Excel Shortcut Key, or write a VBA code in Excel. read more which contain the word “Summary” in their name.

Step 1: Enter the following code to unhide all the sheets.

Sub To_UnHide_Specific_Sheet()

Dim Ws As Worksheet

For Each Ws In ActiveWorkbook.Worksheets

If InStr(Ws.Name, "Summary") > 0 Then
Ws.Visible = xlSheetVisible
End If

Next Ws
'InStr function looks for word or phrase in the sheet name
'If it finds then it will be hidden
End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. In the output, all the five sheets are unhidden.

Example 5-3

Properties of VBA InStr Function

The properties of the function are listed as follows:

  • It is a case-sensitive function. To eliminate this issue, supply the “compare” argument “vbTextCompare.”
  • It is a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more and cannot be used like other in-built formulas of Excel.
  • It returns zero if it cannot find “string 2” in “string 1.”

Frequently Asked Questions

Define the VBA InStr function.

The VBA InStr function returns the position of one string within another string. This position corresponds to the first occurrence of the substring. The function returns an integer as the output. It returns zero (0) if the substring is not found within the string.

The syntax and the arguments of the function are listed as follows:

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

Start: It specifies the position from which search should begin. The default value is 1.
String 1: It is the actual string within which the substring is to be searched.
String 2: It is the substring to be searched.
Compare: It specifies the comparison method to be used. The methods are stated as follows:
a. vbBinaryCompare or 0: It is used for a case-sensitive search of the substring within the string.
b. vbTextCompare or 1: It is used for a case-insensitive search of the substring within the string.
c. vbDatabaseCompare or 2: It is used for comparison with Microsoft Access database.

The arguments “string 1” and “string 2” are mandatory, while “start” and “compare” are optional.

What is the difference between the InStr and the InStrRev functions of VBA?

How to use the VBA InStr function in excel with wildcards?

With the usage of wildcards, the InStr function returns “true” or “false” depending on whether it has found the specified substring within the string or not.

The function supports the usage of the following wildcards:
1. Asterisk (*): It represents one or more characters of a string and works as follows:
“a*” refers to the text that begins with the character “a.”
• “*a” refers to the text that ends with the character “a.”
• “*a*” refers to the text that has the character “a” in the middle.
2. Question mark (?): It represents one character of a string and works as follows:
• “a?” refers to two characters beginning with “a.”
• “?a” refers to two characters ending with “a.”
• “?a?” refers to three characters having “a” in the middle.
Likewise, the VBA InStr function can be used with the tilde (~) as well.

Recommended Articles

This has been a guide to VBA InStr Function in Excel. Here we learn how to use the InStr function along with step by step examples and a downloadable excel template. Below you can find some useful Excel VBA articles-

  • VBA FileCopy Function
  • Excel VBA FileDialog
  • Excel VBA String Functions
  • Excel VBA SubString
  • VBA Name Worksheet

Contents

  • 1 Quick Guide to String Functions
  • 2 The Webinar
  • 3 Introduction
  • 4 Read This First!
    • 4.1 The Original String is not Changed
    • 4.2 How To Use Compare
  • 5 Appending Strings
  • 6 Extracting Part of a String
  • 7 Searching Within a String
    • 7.1 InStr Description of Parameters
    • 7.2 InStr Use and Examples
    • 7.3 InStrRev Description of Parameters
    • 7.4 InStrRev Use and Examples
  • 8 Removing Blanks
    • 8.1 Trim Functions Use and Examples
  • 9 Length of a String
  • 10 Reversing a String
  • 11 Comparing Strings
    • 11.1 Description of Parameters
    • 11.2 StrComp Return Values
    • 11.3 Use and Examples
    • 11.4 Compare Strings using Operators
  • 12 Comparing Strings using Pattern Matching
    • 12.1 Real-World Example of Pattern Matching
    • 12.2 Important Note on VBA Pattern Matching
  • 13 Replace Part of a String
    • 13.1 Replace Description of Parameters
    • 13.2 Use and Examples
    • 13.3 Multiple Replaces
  • 14 Convert Types to String(Basic)
    • 14.1 Explicit Conversion
    • 14.2 Multi Region
  • 15 Convert String to Number- CLng, CDbl, Val etc.
    • 15.1 The Val Function
  • 16 Generate a String of items – String Function
  • 17 Convert Case/Unicode – StrConv, UCase, LCase
    • 17.1 Other Conversions
  • 18 Using Strings With Arrays
    • 18.1 String to Array using Split
    • 18.2 Array to String using Join
  • 19 Formatting a String
    • 19.1 Helpful Tip for Using Format
  • 20 Conclusion
  • 21 What’s Next?

Quick Guide to String Functions

String operations Function(s)
Append two or more strings Format or “&”
Build a string from an array Join
Compare – normal StrComp or “=”
Compare – pattern Like
Convert to a string CStr, Str
Convert string to date Simple: CDate
Advanced: Format
Convert string to number Simple: CLng, CInt, CDbl, Val
Advanced: Format
Convert to unicode, wide, narrow StrConv
Convert to upper/lower case StrConv, UCase, LCase
Extract part of a string Left, Right, Mid
Format a string Format
Find characters in a string InStr, InStrRev
Generate a string String
Get length of a string Len
Remove blanks LTrim, RTrim, Trim
Replace part of a string Replace
Reverse a string StrReverse
Parse string to array Split

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba strings video

Introduction

Using strings is a very important part of VBA. There are many types of manipulation you may wish to do with strings. These include tasks such as

  • extracting part of a string
  • comparing strings
  • converting numbers to a string
  • formatting a date to include weekday
  • finding a character in a string
  • removing blanks
  • parsing to an array
  • and so on

The good news is that VBA contains plenty of functions to help you perform these tasks with ease.

This post provides an in-depth guide to using string in VBA. It explains strings in simple terms with clear code examples. I have laid it out so the post can be easily used as a quick reference guide.

If you are going to use strings a lot then I recommend you read the first section as it applies to a lot of the functions. Otherwise you can read in order or just go to the section you require.

Read This First!

The following two points are very important when dealing with VBA string functions.

The Original String is not Changed

An important point to remember is that the VBA string functions do not change the original string. They return a new string with the changes the function made. If you want to change the original string you simply assign the result to the original string. See the section Extracting Part of a String for examples of this.

How To Use Compare

Some of the string functions such as StrComp() and Instr() etc. have an optional Compare parameter. This works as follows:

vbTextCompare: Upper and lower case are considered the same

vbBinaryCompare: Upper and lower case are considered different

The following code uses the string comparison function StrComp() to demonstrate the Compare parameter

' https://excelmacromastery.com/
Sub Comp1()

    ' Prints 0  : Strings match
    Debug.Print StrComp("ABC", "abc", vbTextCompare)
    ' Prints -1 : Strings do not match
    Debug.Print StrComp("ABC", "abc", vbBinaryCompare)

End Sub

You can use the Option Compare setting instead of having to use this parameter each time. Option Compare is set at the top of a Module. Any function that uses the Compare parameter will take this setting as the default. The two ways to use Option Compare are:

1. Option Compare Text: makes vbTextCompare the default Compare argument

' https://excelmacromastery.com/
Option Compare Text

Sub Comp2()
    ' Strings match - uses vbCompareText as Compare argument
    Debug.Print StrComp("ABC", "abc")
    Debug.Print StrComp("DEF", "def")
End Sub

2. Option Compare Binary: Makes vbBinaryCompare the default Compare argument

' https://excelmacromastery.com/
Option Compare Binary

Sub Comp2()
    ' Strings do not match - uses vbCompareBinary as Compare argument
    Debug.Print StrComp("ABC", "abc")
    Debug.Print StrComp("DEF", "def")
End Sub

If Option Compare is not used then the default is Option Compare Binary.

Now that you understand these two important points about string we can go ahead and look at the string functions individually.

Go back to menu

Appending Strings

VBA String Functions - Smaller

ABC Cube Pile © Aleksandr Atkishkin | Dreamstime.com

You can append strings using the & operator. The following code shows some examples of using it

' https://excelmacromastery.com/
Sub Append()

    Debug.Print "ABC" & "DEF"
    Debug.Print "Jane" & " " & "Smith"
    Debug.Print "Long " & 22
    Debug.Print "Double " & 14.99
    Debug.Print "Date " & #12/12/2015#

End Sub

You can see in the example that different types such as dates and number are automatically converted to strings. You may see the + operator being used to append strings. The difference is that this operator will only work with string types. If you try to use it with other type you will get an error.

    ' This will give the error message:  "Type Mismatch"
    Debug.Print "Long " + 22

If you want to do more complex appending of strings then you may wish to use the Format function described below.

Go back to menu

The functions discussed in this section are useful when dealing with basic extracting from a string. For anything more complicated you might want to check out my post on How to Easily Extract From Any String Without Using VBA InStr.

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)

The Left, Right, and Mid functions are used to extract parts of a string. They are very simple functions to use. Left reads characters from the left, Right from the right and Mid from a starting point that you specify.

' https://excelmacromastery.com/
Sub UseLeftRightMid()

    Dim sCustomer As String
    sCustomer = "John Thomas Smith"

    Debug.Print Left(sCustomer, 4)  '  Prints: John
    Debug.Print Right(sCustomer, 5) '  Prints: Smith

    Debug.Print Left(sCustomer, 11)  '  Prints: John Thomas
    Debug.Print Right(sCustomer, 12)  '  Prints: Thomas Smith

    Debug.Print Mid(sCustomer, 1, 4) ' Prints: John
    Debug.Print Mid(sCustomer, 6, 6) ' Prints: Thomas
    Debug.Print Mid(sCustomer, 13, 5) ' Prints: Smith

End Sub

As mentioned in the previous section, VBA string functions do not change the original string. Instead, they return the result as a new string.

In the next example you can see that the string Fullname was not changed after using the Left function

' https://excelmacromastery.com/
Sub UsingLeftExample()

    Dim Fullname As String
    Fullname = "John Smith"

    Debug.Print "Firstname is: "; Left(Fullname, 4)
    ' Original string has not changed
    Debug.Print "Fullname is: "; Fullname

 End Sub

If you want to change the original string you simply assign it to the return value of the function

' https://excelmacromastery.com/
Sub ChangingString()

    Dim name As String
    name = "John Smith"

    ' Assign return string to the name variable
    name = Left(name, 4)

    Debug.Print "Name is: "; name

 End Sub

Go back to menu

Searching Within a String

Function Params Description Example
InStr String1, String2 Finds position of string InStr(“John Smith”,”h”)
InStrRev StringCheck, StringMatch Finds position of string from end InStrRev(“John Smith”,”h”)

InStr and InStrRev are VBA functions used to search through strings for a substring. If the search string is found then the position(from the start of the check string) of the search string is returned. If the search string is not found then zero is returned. If either string is null then null is returned.

InStr Description of Parameters

InStr() Start[Optional], String1, String2, Compare[Optional]

  • Start As Long[Optional – Default is 1]: This is a number that specifies the starting search position from the left
  • String1 As String: The string to search
  • String2 As String: The string to search for
  • Compare As vbCompareMethod : See the section on Compare above for more details

InStr Use and Examples

InStr returns the first position in a string where a given substring is found. The following shows some examples of using it

' https://excelmacromastery.com/
Sub FindSubString()

    Dim name As String
    name = "John Smith"

    ' Returns 3 - position of first h
    Debug.Print InStr(name, "h")
    ' Returns 10 - position of first h starting from position 4
    Debug.Print InStr(4, name, "h")
    ' Returns 8
    Debug.Print InStr(name, "it")
    ' Returns 6
    Debug.Print InStr(name, "Smith")
    ' Returns 0 - string "SSS" not found
    Debug.Print InStr(name, "SSS")

End Sub

InStrRev Description of Parameters

InStrRev() StringCheck, StringMatch, Start[Optional], Compare[Optional]

  • StringCheck As String: The string to search
  • StringMatch: The string to search for
  • Start As Long[Optional – Default is -1]: This is a number that specifies the starting search position from the right
  • Compare As vbCompareMethod: See the section on Compare above for more details

InStrRev Use and Examples

The InStrRev function is the same as InStr except that it searches from the end of the string. It’s important to note that the position returned is the position from the start. Therefore if there is only one instance of the search item then both InStr() and InStrRev() will return the same value.

The following code show some examples of using InStrRev

' https://excelmacromastery.com/
Sub UsingInstrRev()

    Dim name As String
    name = "John Smith"

    ' Both Return 1 - position of the only J
    Debug.Print InStr(name, "J")
    Debug.Print InStrRev(name, "J")

    ' Returns 10 - second h
    Debug.Print InStrRev(name, "h")
    ' Returns 3 - first h as searches from position 9
    Debug.Print InStrRev(name, "h", 9)

    ' Returns 1
    Debug.Print InStrRev(name, "John")

End Sub

The InStr and InStrRev functions are useful when dealing with basic string searches. However, if you are going to use them for extracting text from a string they can make things complicated. I have written about a much better way to do this in my post How to Easily Extract From Any String Without Using VBA InStr.

Go back to menu

Removing Blanks

Function Params Description Example
LTrim string Removes spaces from left LTrim(” John “)
RTrim string Removes spaces from right RTrim(” John “)
Trim string Removes Spaces from left and right Trim(” John “)

The Trim functions are simple functions that remove spaces from either the start or end of a string.

Trim Functions Use and Examples

  • LTrim removes spaces from the left of a string
  • RTrim removes spaces from the right of a string
  • Trim removes spaces from the left and right of a string
' https://excelmacromastery.com/
Sub TrimStr()

    Dim name As String
    name = "  John Smith  "

    ' Prints "John Smith  "
    Debug.Print LTrim(name)
    ' Prints "  John Smith"
    Debug.Print RTrim(name)
    ' Prints "John Smith"
    Debug.Print Trim(name)

End Sub

Go back to menu

Length of a String

Function Params Description Example
Len string Returns length of string Len (“John Smith”)

Len is a simple function when used with a string. It simply returns the number of characters the string contains. If used with a numeric type such as long it will return the number of bytes.

' https://excelmacromastery.com/
Sub GetLen()

    Dim name As String
    name = "John Smith"

    ' Prints 10
    Debug.Print Len("John Smith")
    ' Prints 3
    Debug.Print Len("ABC")

    ' Prints 4 as Long is 4 bytes in size
    Dim total As Long
    Debug.Print Len(total)

End Sub

Go back to menu

Reversing a String

Function Params Description Example
StrReverse string Reverses a string StrReverse (“John Smith”)

StrReverse is another easy-to-use function. It simply returns the given string with the characters reversed.

' https://excelmacromastery.com/
Sub RevStr()

    Dim s As String
    s = "Jane Smith"
    ' Prints: htimS enaJ
    Debug.Print StrReverse(s)

End Sub

Go back to menu

Comparing Strings

Function Params Description Example
StrComp string1, string2 Compares 2 strings StrComp (“John”, “John”)

The function StrComp is used to compare two strings. The following subsections describe how it is used.

Description of Parameters

StrComp()  String1, String2, Compare[Optional]

  • String1 As String: The first string to compare
  • String2 As String: The second string to compare
  • Compare As vbCompareMethod : See the section on Compare above for more details

StrComp Return Values

Return Value Description
0 Strings match
-1 string1 less than string2
1 string1 greater than string2
Null if either string is null

Use and Examples

The following are some examples of using the StrComp function

' https://excelmacromastery.com/
Sub UsingStrComp()

   ' Returns 0
   Debug.Print StrComp("ABC", "ABC", vbTextCompare)
   ' Returns 1
   Debug.Print StrComp("ABCD", "ABC", vbTextCompare)
   ' Returns -1
   Debug.Print StrComp("ABC", "ABCD", vbTextCompare)
   ' Returns Null
   Debug.Print StrComp(Null, "ABCD", vbTextCompare)

End Sub

Compare Strings using Operators

You can also use the equals sign to compare strings. The difference between the equals comparison and the StrComp function are:

  1. The equals sign returns only true or false.
  2. You cannot specify a Compare parameter using the equal sign – it uses the “Option Compare” setting.

The following shows some examples of using equals to compare strings

' https://excelmacromastery.com/
Option Compare Text

Sub CompareUsingEquals()

    ' Returns true
    Debug.Print "ABC" = "ABC"
    ' Returns true because "Compare Text" is set above
    Debug.Print "ABC" = "abc"
    ' Returns false
    Debug.Print "ABCD" = "ABC"
    ' Returns false
    Debug.Print "ABC" = "ABCD"
    ' Returns null
    Debug.Print Null = "ABCD"

End Sub

The Operator “<>” means “does not equal”. It is essentially the opposite of using the equals sign as the following code shows

' https://excelmacromastery.com/
Option Compare Text

Sub CompareWithNotEqual()

    ' Returns false
    Debug.Print "ABC" <> "ABC"
    ' Returns false because "Compare Text" is set above
    Debug.Print "ABC" <> "abc"
    ' Returns true
    Debug.Print "ABCD" <> "ABC"
    ' Returns true
    Debug.Print "ABC" <> "ABCD"
    ' Returns null
    Debug.Print Null <> "ABCD"

End Sub

Go back to menu

Comparing Strings using Pattern Matching

Operator Params Description Example
Like string, string pattern checks if string has the given pattern “abX” Like “??X”
“54abc5” Like “*abc#”
Token Meaning
? Any single char
# Any single digit(0-9)
* zero or more characters
[charlist] Any char in the list
[!charlist] Any char not in the char list

Pattern matching is used to determine if a string has a particular pattern of characters. For example, you may want to check that a customer number has 3 digits followed by 3 alphabetic characters or a string has the letters XX followed by any number of characters.

If the string matches the pattern then the return value is true, otherwise it is false.

Pattern matching is similar to the VBA Format function in that there are almost infinite ways to use it. In this section I am going to give some examples that will explain how it works. This should cover the most common uses. If you need more information about pattern matching you can refer to the MSDN Page for the Like operator.

Lets have a look at a basic example using the tokens. Take the following pattern string

[abc][!def]?#X*

Let’s look at how this string works
[abc] a character that is either a,b or c
[!def] a character that is not d,e or f
? any character
# any digit
X the character X
* followed by zero or more characters

Therefore the following string is valid
apY6X

a is one of abc
p is not one of the characters d, e or f
Y is any character
6 is a digit
X is the letter X

The following code examples show the results of various strings with this pattern

' https://excelmacromastery.com/
Sub Patterns()

    ' True
    Debug.Print 1; "apY6X" Like "[abc][!def]?#X*"
    ' True - any combination of chars after x is valid
    Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*"
    ' False - char d not in [abc]
    Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*"
    ' False - 2nd char e is in [def]
    Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*"
    ' False - A at position 4 is not a digit
    Debug.Print 5; "apYAX" Like "[abc][!def]?#X*"
    ' False - char at position 5 must be X
    Debug.Print 6; "apY6Z" Like "[abc][!def]?#X*"

End Sub

Real-World Example of Pattern Matching

To see a real-world example of using pattern matching check out Example 3: Check if a filename is valid.

Important Note on VBA Pattern Matching

The Like operator uses either Binary or Text comparison based on the Option Compare setting. Please see the section on Compare above for more details.

Go back to menu

Replace Part of a String

Function Params Description Example
Replace string, find, replace,
start, count, compare
Replaces a substring with a substring Replace (“Jon”,”n”,”hn”)

Replace is used to replace a substring in a string by another substring. It replaces all instances of the substring that are found by default.

Replace Description of Parameters

Replace()  Expression, Find, Replace, Start[Optional], Count[Optional], Compare[Optional]

  • Expression As String: The string to replace chars in
  • Find As String: The substring to replace in the Expression string
  • Replace As String: The string to replace the Find substring with
  • Start As Long[Optional – Default is 1]: The start position in the string
  • Count As Long[Optional – Default is -1]: The number of substitutions to make. The default -1 means all.
  • Compare As vbCompareMethod : See the section on Compare above for more details

Use and Examples

The following code shows some examples of using the Replace function

' https://excelmacromastery.com/
Sub ReplaceExamples()

    ' Replaces all the question marks with(?) with semi colons(;)
    Debug.Print Replace("A?B?C?D?E", "?", ";")
    ' Replace Smith with Jones
    Debug.Print Replace("Peter Smith,Ann Smith", "Smith", "Jones")
    ' Replace AX with AB
    Debug.Print Replace("ACD AXC BAX", "AX", "AB")

End Sub

Output
A;B;C;D;E
Peter Jones,Sophia Jones
ACD ABC BAB

In the following examples we use the Count optional parameter. Count determines the number of substitutions to make. So for example, setting Count equal to one means that only the first occurrence will be replaced.

' https://excelmacromastery.com/
Sub ReplaceCount()

    ' Replaces first question mark only
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1)
    ' Replaces first three question marks
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3)

End Sub

Output
A;B?C?D?E
A;B;C;D?E

The Start optional parameter allow you to return part of a string. The position you specify using Start is where it starts returning the string from. It will not return any part of the string before this position whether a replace was made or not.

' https://excelmacromastery.com/
Sub ReplacePartial()

    ' Use original string from position 4
    Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4)
    ' Use original string from position 8
    Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8)
    ' No item replaced but still only returns last 2 characters
    Debug.Print Replace("ABCD", "X", "Y", Start:=3)

End Sub

Output
;C;D;E
;E
CD

Sometimes you may only want to replace only upper or lower case letters. You can use the Compare parameter to do this. This is used in a lot of string functions.  For more information on this check out the Compare section above.

' https://excelmacromastery.com/
Sub ReplaceCase()

    ' Replace capital A's only
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare)
    ' Replace All A's
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare)

End Sub

Output
XaXa
XXXX

Multiple Replaces

If you want to replace multiple values in a string you can nest the calls. In the following code we want to replace X and Y with A and B respectively.

' https://excelmacromastery.com/
Sub ReplaceMulti()

    Dim newString As String

    ' Replace A with X
    newString = Replace("ABCD ABDN", "A", "X")
    ' Now replace B with Y in new string
    newString = Replace(newString, "B", "Y")

    Debug.Print newString

End Sub

In the next example we will change the above code to perform the same task. We will use the return value of the first replace as the argument for the second replace.

' https://excelmacromastery.com/
Sub ReplaceMultiNested()

    Dim newString As String

    ' Replace A with X and B with Y
    newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y")

    Debug.Print newString

End Sub

The result of both of these Subs is
XYCD XYDN

Go back to menu

Convert Types to String(Basic)

This section is about converting numbers to a string. A very important point here is that most the time VBA will automatically convert to a string for you. Let’s look at some examples

' https://excelmacromastery.com/
Sub AutoConverts()

    Dim s As String
    ' Automatically converts number to string
    s = 12.99
    Debug.Print s

    ' Automatically converts multiple numbers to string
    s = "ABC" & 6 & 12.99
    Debug.Print s

    ' Automatically converts double variable to string
    Dim d As Double, l As Long
    d = 19.99
    l = 55
    s = "Values are " & d & " " & l
    Debug.Print s

End Sub

When you run the above code you can see that the number were automatically converted to strings. So when you assign a value to a string VBA will look after the conversion for you most of the time. There are conversion functions in VBA and in the following sub sections we will look at the reasons for using them.

Explicit Conversion

Function Params Description Example
CStr expression Converts a number variable to a string CStr (“45.78”)
Str number Converts a number variable to a string Str (“45.78”)

In certain cases you may want to convert an item to a string without have to place it in a string variable first. In this case you can use the Str or CStr functions. Both take an  expression as a function and this can be any type such as long, double, data or boolean.

Let’s look at a simple example. Imagine you are reading a list of values from different types of cells to a collection. You can use the Str/CStr functions to ensure they are all stored as strings. The following code shows an example of this

' https://excelmacromastery.com/
Sub UseStr()

    Dim coll As New Collection
    Dim c As Range

    ' Read cell values to collection
    For Each c In Range("A1:A10")
        ' Use Str to convert cell value to a string
        coll.Add Str(c)
    Next

    ' Print out the collection values and type
    Dim i As Variant
    For Each i In coll
        Debug.Print i, TypeName(i)
    Next

End Sub

In the above example we use Str to convert the value of the cell to a string. The alternative to this would be to assign the value to a string and then assigning the string to the collection. So you can see that using Str here is much more efficient.

Multi Region

The difference between the Str and CStr functions is that CStr converts based on the region. If your macros will be used in multiple regions then you will need to use CStr for your string conversions.

It is good to practise to use CStr when reading values from cells. If your code ends up being used in another region then you will not have to make any changes to make it work correctly.

Go back to menu

Convert String to Number- CLng, CDbl, Val etc.

Function Returns Example
CBool Boolean CBool(“True”), CBool(“0”)
CCur Currency CCur(“245.567”)
CDate Date CDate(“1/1/2017”)
CDbl Double CCur(“245.567”)
CDec Decimal CDec(“245.567”)
CInt Integer CInt(“45”)
CLng Long Integer CLng(“45.78”)
CVar Variant CVar(“”)

The above functions are used to convert strings to various types. If you are assigning to a variable of this type then VBA will do the conversion automatically.

' https://excelmacromastery.com/
Sub StrToNumeric()

    Dim l As Long, d As Double, c As Currency
    Dim s As String
    s = "45.923239"

    l = s
    d = s
    c = s

    Debug.Print "Long is "; l
    Debug.Print "Double is "; d
    Debug.Print "Currency is "; c

End Sub

Using the conversion types gives more flexibility. It means you can determine the type at runtime. In the following code we set the type based on the sType argument passed to the PrintValue function. As this type can be read from an external source such as a cell, we can set the type at runtime. If we declare a variable as Long then it will always be long when the code runs.

' https://excelmacromastery.com/
Sub Test()
    ' Prints  46
    PrintValue "45.56", "Long"
    ' Print 45.56
    PrintValue "45.56", ""
End Sub

Sub PrintValue(ByVal s As String, ByVal sType As String)

    Dim value

    ' Set the data type based on a type string
    If sType = "Long" Then
        value = CLng(s)
    Else
        value = CDbl(s)
    End If
    Debug.Print "Type is "; TypeName(value); value

End Sub

If a string is not a valid number(i.e. contains symbols other numeric) then you get a “Type Mismatch” error.

' https://excelmacromastery.com/
Sub InvalidNumber()

    Dim l As Long

    ' Will give type mismatch error
    l = CLng("45A")

End Sub

The Val Function

The value function convert numeric parts of a string to the correct number type.

The Val function converts the first numbers it meets. Once it meets letters in a string it stops. If there are only letters then it returns zero as the value. The following code shows some examples of using Val

' https://excelmacromastery.com/
Sub UseVal()

    ' Prints 45
    Debug.Print Val("45 New Street")

    ' Prints 45
    Debug.Print Val("    45 New Street")

    ' Prints 0
    Debug.Print Val("New Street 45")

    ' Prints 12
    Debug.Print Val("12 f 34")

End Sub

The Val function has two disadvantages

1. Not Multi-Region – Val does not recognise international versions of numbers such as using commas instead of decimals. Therefore you should use the above conversion functions when you application will be used in multiple regions.

2. Converts invalid strings to zero – This may be okay in some instances but in most cases it is better if an invalid string raises an error. The application is then aware there is a problem and can act accordingly. The conversion functions such as CLng will raise an error if the string contains non-numeric characters.

Go back to menu

Generate a String of items – String Function

Function Params Description Example
String number, character Converts a number variable to a string String (5,”*”)

The String function is used to generate a string of repeated characters. The first argument is the number of times to repeat it, the second argument is the character.

' https://excelmacromastery.com/
Sub GenString()

    ' Prints: AAAAA
    Debug.Print String(5, "A")
    ' Prints: >>>>>
    Debug.Print String(5, 62)
    ' Prints: (((ABC)))
    Debug.Print String(3, "(") & "ABC" & String(3, ")")

End Sub

Go back to menu

Convert Case/Unicode – StrConv, UCase, LCase

Function Params Description Example
StrConv string, conversion, LCID Converts a String StrConv(“abc”,vbUpperCase)

If you want to convert the case of a string to upper or lower you can use the UCase and LCase functions for upper and lower respectively. You can also use the StrConv function with the vbUpperCase or vbLowerCase argument. The following code shows example of using these three functions

' https://excelmacromastery.com/
Sub ConvCase()

    Dim s As String
    s = "Mary had a little lamb"

    ' Upper
    Debug.Print UCase(s)
    Debug.Print StrConv(s, vbUpperCase)

    ' Lower
    Debug.Print LCase(s)
    Debug.Print StrConv(s, vbLowerCase)

    ' Sets the first letter of each word to upper case
    Debug.Print StrConv(s, vbProperCase)

End Sub

Output
MARY HAD A LITTLE LAMB
MARY HAD A LITTLE LAMB
mary had a little lamb
mary had a little lamb
Mary Had A Little Lamb

Other Conversions

As well as case the StrConv can perform other conversions based on the Conversion parameter. The following table shows a list of the different parameter values and what they do. For more information on StrConv check out the MSDN Page.

Constant Value Converts
vbUpperCase 1 to upper case
vbLowerCase 2 to lower case
vbProperCase 3 first letter of each word to uppercase
vbWide* 4 from Narrow to Wide
vbNarrow* 8 from Wide to Narrow
vbKatakana** 16 from Hiragana to Katakana
vbHiragana 32 from Katakana to Hiragana
vbUnicode 64 to unicode
vbFromUnicode 128 from unicode

Go back to menu

Using Strings With Arrays

Function Params Description Example
Split expression, delimiter,
limit, compare
Parses a delimited string to an array arr = Split(“A;B;C”,”;”)
Join source array, delimiter Converts a one dimensional array to a string s = Join(Arr, “;”)

String to Array using Split

You can easily parse a delimited string into an array. You simply use the Split function with the delimiter as parameter. The following code shows an example of using the Split function.

' https://excelmacromastery.com/
Sub StrToArr()

    Dim arr() As String
    ' Parse string to array
    arr = Split("John,Jane,Paul,Sophie", ",")

    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

Output
John
Jane
Paul
Sophie

You can find a complete guide to the split function here.

Array to String using Join

If you want to build a string from an array you can do so easily using the Join function. This is essentially a reverse of the Split function. The following code provides an example of using Join

' https://excelmacromastery.com/
Sub ArrToStr()

    Dim Arr(0 To 3) As String
    Arr(0) = "John"
    Arr(1) = "Jane"
    Arr(2) = "Paul"
    Arr(3) = "Sophie"

    ' Build string from array
    Dim sNames As String
    sNames = Join(Arr, ",")

    Debug.Print sNames

End Sub

Output
John,Jane,Paul,Sophie

Go back to menu

Formatting a String

Function Params Description Example
Format expression, format,
firstdayofweek, firstweekofyear
Formats a string Format(0.5, “0.00%”)

The Format function is used to format a string based on given instructions. It is mostly used to place a date or number in certain format. The examples below show the most common ways you would format a date.

' https://excelmacromastery.com/
Sub FormatDate()

    Dim s As String
    s = "31/12/2015 10:15:45"

    ' Prints: 31 12 15
    Debug.Print Format(s, "DD MM YY")
    ' Prints: Thu 31 Dec 2015
    Debug.Print Format(s, "DDD DD MMM YYYY")
    ' Prints: Thursday 31 December 2015
    Debug.Print Format(s, "DDDD DD MMMM YYYY")
    ' Prints: 10:15
    Debug.Print Format(s, "HH:MM")
    ' Prints: 10:15:45 AM
    Debug.Print Format(s, "HH:MM:SS AM/PM")

End Sub

The following examples are some common ways of formatting numbers

' https://excelmacromastery.com/
Sub FormatNumbers()

    ' Prints: 50.00%
    Debug.Print Format(0.5, "0.00%")
    ' Prints: 023.45
    Debug.Print Format(23.45, "00#.00")
    ' Prints: 23,000
    Debug.Print Format(23000, "##,000")
    ' Prints: 023,000
    Debug.Print Format(23000, "0##,000")
    ' Prints: $23.99
    Debug.Print Format(23.99, "$#0.00")

End Sub

The Format function is quite a large topic and could use up a full post on it’s own. If you want more information then the MSDN Format Page provides a lot of information.

Helpful Tip for Using Format

A quick way to figure out the formatting to use is by using the cell formatting on an Excel worksheet. For example add a number to a cell. Then right click and format the cell the way you require. When you are happy with the format select Custom from the category listbox on the left.  When you select this you can see the format string in the type textbox(see image below). This is the string format you can use in VBA.

VBA Format Function

Format Cells Dialog

Go back to menu

Conclusion

In almost any type of programming, you will spend a great deal of time manipulating strings. This post covers the many different ways you use strings in VBA.

To get the most from use the table at the top to find the type of function you wish to use. Clicking on the left column of this function will bring you to that section.

If you are new to strings in VBA, then I suggest you check out the Read this First section before using any of the functions.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Определение первого вхождения одной строки в другую с помощью функции InStr из кода VBA Excel. Синтаксис функции, параметры, примеры использования.

InStr – это функция, которая предназначена для определения номера позиции первого вхождения одной строки в другую. Она возвращает значение типа Variant (Long).

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

Функция InStr часто незаменима при определении параметров функций Left, Mid и Right. Также ее можно использовать для определения наличия искомой подстроки в заданной строке.

Еще есть в VBA Excel функция InStrB, которая работает с байтовыми данными, содержащимися в строке. Она возвращает позицию байта, а не символа первого вхождения одной строки в другую. Смотрите ниже Пример 3.

Синтаксис, параметры, значения

Синтаксис функции InStr

Полный вариант:

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

Сокращенный вариант:

Чаще всего в VBA Excel используется сокращенный вариант функции со значениями необязательных параметров по умолчанию.

Параметры функции InStr

Параметр Описание Значение по умолчанию
start Необязательный аргумент.* Числовое выражение, которое задает начальную позицию для поиска. 1
string1 Обязательный аргумент. Строковое выражение, в котором выполняется поиск.
string2 Обязательный аргумент. Искомое строковое выражение.
compare Необязательный аргумент. Задает тип сравнения строк. –1**

* Если задан аргумент compare, аргумент start является обязательным.
** Если аргумент compare не указан, используется значение инструкции Option Compare, заданное на уровне модуля. Если инструкция Option Compare в начале модуля отсутствует, используется ее значение по умолчанию – 0 (двоичное сравнение).

Если параметр start или параметр compare содержит значение NULL, возникает ошибка.

Значения аргумента «compare»

Константа Значение Описание
vbUseCompareOption -1 Сравнение с помощью параметра инструкции Option Compare.
vbBinaryCompare 0 Двоичное (бинарное) сравнение.*
vbTextCompare 1 Текстовое сравнение.*
vbDatabaseCompare 2 Сравнение на основе сведений из базы данных. Только для Microsoft Access.

* При двоичном сравнении учитывается регистр букв, при текстовом – не учитывается.

Значения функции InStr

Если Возвращаемое значение
string2 найдена в string1 Позиция первого найденного соответствия.
string2 не найдена в string1 0
string2 является пустой start
string2 равна Null Null
string1 является пустой 0
string1 равна Null Null
start больше длины string1 0

Примеры использования в VBA Excel

Пример 1

Самый простой пример:

Sub Test1()

Dim x As Variant

x = InStr(“На горе Фернандо-По, где гуляет Гиппо-по”, “Фернандо”)

MsgBox x

‘Здесь x будет равен 9

End Sub

Пример 2

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

Sub Test2()

Dim x As Variant

x = InStr(10, “На горе Фернандо-По, где гуляет Гиппо-по”, “по”, 0)

MsgBox x

‘Здесь x будет равен 36 (поиск с учетом регистра символов)

x = InStr(10, “На горе Фернандо-По, где гуляет Гиппо-по”, “по”, 1)

MsgBox x

‘Здесь x будет равен 18 (поиск без учета регистра символов)

End Sub

Обратите внимание: несмотря на то, что начало поиска мы задали с 10 символа, номер позиции первого вхождения считается с начала строки, в которой выполняется поиск.

Пример 3

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

Sub Test3()

Dim x As Variant

x = InStr(“На горе Фернандо-По, где гуляет Гиппо-по”, “гор”)

MsgBox x

‘Здесь x будет равен 4

x = InStrB(“На горе Фернандо-По, где гуляет Гиппо-по”, “гор”)

MsgBox x

‘Здесь x будет равен 7

End Sub

Результат 7 при побайтовом сравнении получен для кодировки, у которой один символ составляет 2 байта.


Добавить комментарий