Vba for excel строковые функции

Работа с текстом в коде VBA Excel. Функции, оператор & и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

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

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


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

Extracting Part of a String

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.)

In this Article

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

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

The VBA Left String Function

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

Left(String, Num_of_characters) where:

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

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

Sub UsingTheLeftStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

How to Use the Left String Function in VBA

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

The VBA Right String Function

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

Right(String, Num_of_characters) where:

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

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

Sub UsingTheRightStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

Using the Right String Function in VBA

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

The VBA Mid String Function

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

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

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

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

Sub UsingTheMidStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is outputted to a msgbox:

Using the Mid String Function in VBA

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

Finding the Position of a Substring

The VBA Instr String Function

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

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

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

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

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

Sub UsingTheInstrStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

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

Debug.Print positionofSubstring


End Sub

The result (outputted to the Immediate Window) is:

Using the Instr Function in VBA

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

VBA Coding Made Easy

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

automacro

Learn More

The VBA InstrRev String Function

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

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

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

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

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

Sub UsingTheInstrRevStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

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

Debug.Print positionofSubstring

End Sub

The result is outputted to the Immediate Window:

Using The InstrRev Function in VBA

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

Removing Spaces from a String

The VBA LTrim String Function

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

LTrim(String) where:

  • String – The original text.

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

Sub UsingTheLTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:

String With Leading Spaces

Using the LTrim String Function To Remove Leading Spaces

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

VBA Programming | Code Generator does work for you!

The VBA RTrim String Function

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

RTrim(String) where:

  • String – The original text.

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

Sub UsingTheRTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueOne
MsgBox valueTwo

End Sub

The results delivered are:
Message box With Trailing Spaces

Using The RTrim String Function

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

The VBA Trim String Function

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

Trim(String) where:

  • String – The original text.

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

Sub UsingTheTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:
Message box With Leading And Trailing Spaces

Using The Trim Function in VBA

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

VBA Case Functions

The VBA LCase String Function

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

LCase(String) where:

  • String – The original text.

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

Sub UsingTheLCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

Using The LCase Function in VBA

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

The VBA UCase String Function

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

UCase(String) where:

  • String – The original text.

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

Sub UsingTheUCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

Using The UCase Function in VBA

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

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

The VBA StrConv Function

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

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

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

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

Sub UsingTheStrConvStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

Using The StrConv Function in VBA

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

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

Comparing Strings

The VBA StrComp Function

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

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

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

Sub UsingTheStrCompStringFunction()

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

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

End Sub

The result is:

Using The StrComp Function in VBA

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

The VBA Like Operator

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

Sub UsingTheLikeOperatorInVBA()

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

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

End Sub

The result is:

Using The Like Operator in VBA

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

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

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

Sub UsingTheLikeOperatorWithAWildcardInVBA()

Dim valueOne As String
valueOne = "The"

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

End Sub

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

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

Other Useful VBA String Functions

The VBA Replace String Function

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

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

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

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

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

Sub UsingTheReplaceStringFunction()

Dim valueOne As String
Dim valueTwo As String

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

MsgBox valueTwo

End Sub

The result is:

Using The Replace String Function in VBA

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

The VBA StrReverse Function

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

StrReverse(String) where:

  • String – The original text.

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

Sub UsingTheStrReverseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "Product"
valueTwo = StrReverse(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The StrReverse Function in VBA

The VBA Len String Function

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

Len(String) where:

  • String – The original text.

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

Sub UsingTheLenFunction()

Dim valueOne As String
Dim stringLength As Integer

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


End Sub

The result is:

Using The Len String Function in VBA

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

Главная » Функции VBA »

28 Апрель 2011              351443 просмотров

  • ASC()— эта функция позволяет вернуть числовой код для переданного символа. Например, ASC("D") вернет 68. Эту функцию удобно использовать для того, чтобы определить следующую или предыдущую букву. Обычно она используется вместе с функцией Chr(), которая производит обратную операцию — возвращает символ по переданному его числовому коду.Варианты этой функции — AscB() и AscW():
    • AscB() — возвращает только первый байт числового кода для символа.
    • AscW() — возвращает код для символа в кодировке Unicode
  • Chr() — возвращает символ по его числовому коду. Может использоваться в паре с функцией Asc(), но чаще всего её применяют, когда нужно вывести служебный символ (например кавычки — "), т.к. кавычки просто так в VBA-коде не ввести(нужно ставить двойные). Я обычно именно эту функцию и использую.
        Dim sWord As String
        sWord = Chr(34) & "Слово в кавычках" & Chr(34)

    Есть варианты этой функции — ChrB() и ChrW(). Работают аналогично таким же вариантам для функции Asc().

  • InStr() и InStrRev()— одна из самых популярных функций. Позволяет обнаружить в теле строковой переменной символ или последовательность символов и вернуть их позицию. Если последовательность не обнаружена, то возвращается 0.
        Dim sStr As String
        sStr = "w"
        If InStr(1, "Hello, World!", sStr, vbTextCompare) > 0 Then
            MsgBox "Искомое слово присутствует!"
        Else
            MsgBox "Искомое слово отсутствует!"
        End If

    Разница функций в том, что InStr() ищет указанное слово от начала строки, а InStrRev() с конца строки

  • Left(), Right(), Mid()— возможность взять указанное вами количество символов из существующей строковой переменной слева, справа или из середины соответственно.
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox Mid(sStr, 1, 5)
  • Len() — возможность получить число символов в строке. Часто используется с циклами, операциями замены и т.п.
  • LCase() и UCase() — перевести строку в нижний и верхний регистры соответственно. Часто используется для подготовки значения к сравнению, когда при сравнении регистр не важен (фамилии, названия фирм, городов и т.п.).
  • LSet() и RSet() — возможность заполнить одну переменную символами другой без изменения ее длины (соответственно слева и справа). Лишние символы обрезаются, на место недостающих подставляются пробелы.
  • LTrim(), RTrim(), Trim() — возможность убрать пробелы соответственно слева, справа или и слева, и справа.
  • Replace()— возможность заменить в строке одну последовательность символов на другую.
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox Replace(sStr, "Hello", "Bay")
  • Space() — получить строку из указанного вами количества пробелов;
    Еще одна похожая функция — Spc(), которая используется для форматирования вывода на консоль. Она размножает пробелы с учетом ширины командной строки.
  • StrComp() — возможность сравнить две строки.
  • StrConv() — возможность преобразовать строку (в Unicode и обратно, в верхний и нижний регистр, сделать первую букву слов заглавной и т.п.):
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox StrConv("Hello, World!", vbUpperCase)

    В качестве второго параметра параметра могут применяться константы:

    • vbUpperCase: Преобразует все текстовые символы в ВЕРХНИЙ РЕГИСТР
    • vbLowerCase: Преобразует все текстовые символы в нижний регистр
    • vbProperCase: Переводит первый символ каждого слова в Верхний Регистр
    • *vbWide: Преобразует символы строки из однобайтовых в двухбайтовые
    • *vbNarrow: Преобразует символы строки из двухбайтовых в однобайтовые
    • **vbKatakana: Преобразует символы Hiragana в символы Katakana
    • **vbHiragana: Преобразует символы Katakana в символы Hiragana
    • ***vbUnicode: Преобразует строку в Юникод с помощью кодовой страницы системы по умолчанию
    • ***vbFromUnicode: Преобразует строку из Юникод в кодовую страницу системы по умолчанию
    • * применимо для локализацией Дальнего востока
      ** применимо только для Японии
      *** не поддерживается операционными системами под управлением Macintosh

  • StrReverse() — «перевернуть» строку, разместив ее символы в обратном порядке. Функция работает только начиная от Excel 2000 и выше. Пример использования функции, а так же иные методы переворачивания слова можно посмотреть в этой статье: Как перевернуть слово?
  • Tab() — еще одна функция, которая используется для форматирования вывода на консоль. Размножает символы табуляции в том количестве, в котором вы укажете. Если никакое количество не указано, просто вставляет символ табуляции. Для вставки символа табуляции в строковое значение можно также использовать константу vbTab.
  • String() — позволяет получить строку из указанного количества символов (которые опять-таки указываются Вами). Обычно используются для форматирования вывода совместно с функцией Len().

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

vba string functionsVisual Basic for Applications or VBA is an event-driven programming language. It is used to automate tasks in the Microsoft Office suite of products – especially repetitive tasks. It enables programmers use this tool to write effective and efficient macros. VBA contains a host of useful functions, on top of those present in Excel or the other MS Office products.

Today, in this beginner’s level tutorial we’ll walk you through the basics of string usage in VBA, and then take a look at the important VBA string functions. If you’re new to VBA, you should first take this introductory course to using macros with VBA.

What is a String

A string, in VBA, is a type of data variable which can consist of text, numerical values, date and time and alphanumeric characters. Strings are a frequently used to store all kinds of data and are important part of VBA programs. There are five basic kinds of string operations which are commonly used in VBA. Let’s take a closer look at them.

1. Concatenation

The Ampersand (&) sign concatenates two strings into a new string. For instance “Welcome”&”Home” yields the string “WelcomeHome”. The syntax for it is

string1 & string2 [& string3 & string_n]

2. Formatting

There are bunch of formatting related functions you can use to represent the string in whichever way you need. A few such  commonly used functions are:

  • Format()-  This function formats the string according to the format you’ve chosen from a predefined set. They syntax is

Format ( expression, [ format ] )

For example:

Format(Now(), “Long Time”)  will display the current system time in the long  time format.

Format(Now(), “Long Date”)  will display the current system date in the long date format.

  • FormatCurrency() –  This formats an expression as a currency value.
  • FormatDateTime() – This function returns a formatted date/time value.
  • FormatNumber() – You can use this function to get a formatted number expression.
  • FormatPercent() – Use this function to get a formatted percent expression.

This course on VBA for Excel can show you other kinds of format manipulations in VBA.

3. Substrings

As the name suggests,  a substring function divides a string into different parts, per the specified criteria. Here are the functions which fall under this category.

  • Right()- Breaks out a substring from the right side of the main string. The second argument is the specified number of characters. The syntax is
Right (“String”, n)
Right (“Good Morning”, 4)    returns “ning”.
  • Mid()-  This function extracts a substring which contains a specified number of characters, from the specified position. The syntax is
Mid(String, position, n)

where position is the starting position of the string from which the substring is to be taken and n is the specified number of characters. Here’s an example

Mid(“Good Morning”, 7, 5) returns "ornin"
  • Left()- Obtains a specified number of characters from the left side of a string.  The syntax is
Left(“String”, n)

where n is the specified number of characters. Here’s an example

Left(“Good Morning”, 4) returns “Good”
  • Split()- It splits the original string into substrings. The syntax is
Split (string, Delimiter, limit)

where string is the input string to be separated. Delimiter character separates the string into parts. The default delimiter is the space character ” “. Limit is the maximum number of substrings. Let’s see an example

Split ("This is a test string", " ") yields the following substrings "This" "is" "a" "test" "string".

Learn more about other VBA functions and macros with this course.

4. Conversion Functions

These functions convert a string’s case – from uppercase to lowercase and vice versa.

  • LCase()- Converts a string or character to lowercase.
LCase(“Good Morning”) returns “good morning”
  • UCase()- COnverts the string to uppercase.
UCase(“Good Morning”) returns “GOOD MORNING”.

5. Find and Replace

These functions come in handy to search for certain substrings, and perhaps replacing them with specified strings.

  • Replace() – Use this function to replace a substring with another substring. The syntax is
Replace(source_string,find_string,replacement_string).

Here source_string is the source string, that you want to search in. find_string is the string to be searched for in the source string.

replacement_string will replace find in source string. For example:

Replace("wonderful", "der", "bat") will return "wonbatful"
  • InStr()- Use this function to get the start position of the first occurrence of a string in another. For example:
Instr(1, “Good Morning”,”Morning”) returns the integer 6.
  • InStrRev()- This function is similar to the previous one. Only difference is that it starts from the right side of the string.

List of other VBA string functions

Here we have put together some of the other most commonly used VBA string functions. Take a look.

  • Asc , AscW()– This function is used to get an integer value which represents the ASCII code corresponding to a character.
  • Chr , ChrW()–  This function returns a character corresponding to the ASCII code passed as parameter.
  • Filter()– Use this function to get a zero-based array which contains a subset of a string array.
  • Join()- This function is used to join substrings together.
  • Len()– Returns the length of a string, including the empty spaces.
  • LSet– This function aligns the string to the left.
  • Ltrim- Use this function to remove leading spaces. For example
Ltrim(“    Good Morning”) returns “Good Morning”
  • RTrim()- This is similar to the Ltrim function and lets you remove trailing spaces.
  • Trim()- This function is a super-set of the previous two. It removes both leading and trailing spaces from a string.
  • RSet– This function align the string to the right.
  • Space() – This function is used to put spaces in a string.
  • StrComp()– This compares two strings and lets you know whether they are identical or different.
  • StrConv()-This function converts the string as specified by the user.
  • StrReverse()- This function reverses a string in place. For example
StrReverse("Hello") will return "olleH"

Hope this tutorial helped you learn more about VBA string functions. Do try them out on your own to get a better grip on them. Note that string manipulation is just one part of VBA. You can learn more about other VBA macros and functions with this ultimate VBA course.

Excel VBA String Functions:

Excel VBA String Functions for Finding and Replacing Text, with Examples: LEFT, RIGHT, MID, LEN, REPLACE, InStr & InStrRev Functions

——————————————————-

Contents:

LEFT Function (Worksheet / VBA)

RIGHT Function (Worksheet / VBA)

MID Function (Worksheet / VBA)

LEN Function (Worksheet / VBA)

REPLACE Function (Worksheet)

REPLACE Function (VBA)

InStr & InStrRev Functions (VBA)

——————————————————-

In Excel vba, a String refers to a sequence of contiguous characters within quotation marks viz. «This is a string expression within quotation marks, in vba.» These characters are literally interpreted as characters, in the sense that these represent the characters themselves rather than their numeric values. A String can include letters, numbers, spaces, and punctuation. A string expression can have as its elements — a string of contiguous characters, a function that returns a string, a string variable, a string constant or a string variant. This section does a detailed discussion on using Excel VBA String Functions to manipulate text strings with vba code. Also refer related link: Excel VBA String Functions: SPLIT, JOIN, CONCATENATE.

LEFT Function (Worksheet / VBA)

The Excel LEFT function can be used both as a worksheet function and a VBA function. The LEFT function returns the specified number of characters in a text string, starting from the first or left-most character. Use this function to extract a sub-string from the left part of a text string. Syntax: LEFT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the LEFT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

RIGHT Function (Worksheet / VBA)

The Excel RIGHT function can be used both as a worksheet function and a VBA function. The RIGHT function returns the specified number of characters in a text string, starting from the last or right-most character. Use this function to extract a sub-string from the right part of a text string. Syntax: RIGHT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the RIGHT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

MID Function (Worksheet / VBA)

The Excel MID function can be used both as a worksheet function and a VBA function. The MID function returns the specified number of characters in a text string, starting from a specified position (ie. starting from a specified character number). Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers). The text_string argument is the text string from which you want to extract the specified number of characters. The start_number argument specifies the character number from which to start extracting the sub-string, the first character in a text string being start_number 1 and incrementing towards the right. The char_numbers argument specifies the number of characters to extract from the text string.

If start_number is greater than the length of the text string, an empty string (zero length) is returned; if it is less than the length of the text string but together with char_numbers (ie. start_number PLUS char_numbers) it is greater than the length of the text string, the MID function will return the text string in full from the start_number position to the end of the text string.

Using MID function as a worksheet function, if a negative value is specified for char_numbers, MID will return the #VALUE! error value; if start_number is less than 1, MID will return the #VALUE! error value. All arguments are necessary to be specified when using as a worksheet function.

Using MID function as a VBA function: The char_numbers argument is optional when used as VBA function, and if omitted the function will return the text string in full from the start_number position to the end of the text string. All other arguments are necessary to be specified when using as a vba function. If text_string contains Null, the function also returns Null.

LEN Function (Worksheet / VBA)

The Excel LEN function can be used both as a worksheet function and a VBA function. The worksheet LEN function returns the number of characters in a text string. Use this function to get the length of a text string. Syntax: LEN(text_string). It is necessary to mention the text_string argument which is the text string whose length you want to get in number of characters. Note that spaces also count as characters. The worksheet LENB function returns the number of bytes used to represent the characters in a text string — counts each character as 1 byte except when a DBCS language [viz. Japanese, Chinese (Simplified), Chinese (Traditional), and Korean] is set as the default language wherein a character is counted as 2 bytes. Syntax: LENB(text_string).

While using LEN as a VBA functionSyntax: Len(text_string) or Len(variable_name) — you can use either a text string or a variable name, and the function will return a Long value representing the number of characters contained in the string or the number of bytes required to store a variable. Using the vba Len function for a variable of type variant will treat the variable as a String and return the number of characters contained in it. A text_string or variable containing Null, will also return Null. The vba Len function returns the number of characters in the string where the variable is of subtype String or Variant, and wherein the variable is of subtype numeric the function returns the number of bytes used to store the variable.

Example — Using Left, Right, Mid & Len functions in vba code.

Sub Left_Right_Mid_Len()
‘using vba Left, Right, Mid & Len functions.

Dim str As String, strLeft As String, strRight As String, strMid As String

str = «James Bond»

strLeft = Left(str, 7)

‘returns «James B», which are the first 7 characters (space is counted as a distinct character).

MsgBox strLeft

strLeft = Left(str, 15)

‘returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

MsgBox strLeft

strRight = Right(str, 7)

‘returns «es Bond», which are the last 7 characters (space is counted as a distinct character).

MsgBox strRight

strRight = Right(str, 15)

‘returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

MsgBox strRight

strMid = Mid(str, 2, 6)

‘Returns «ames B». Starts from the second character ie. «a», and then specifies that 6 characters be returned starting from «a».

MsgBox strMid

strMid = Mid(str, 2, 15)

‘Returns «ames Bond». Returns all characters starting from the second character (start_number position) of «a», because the specified characters of 15 plus start number 2 (ie. total of 17) exceed the string length of 10 characters.

MsgBox strMid

strMid = Mid(str, 2)

‘Returns «ames Bond». Returns all characters starting from the second character (start_number position) of «a», because the second argument (char_numbers) is omitted.

MsgBox strMid

strMid = Mid(str, 12, 2)

‘Returns an empty string (zero length), because the start number of 12 exceeds the string length of 10 characters.

MsgBox strMid

‘Returns 10, the string length measured by its number of characters.

MsgBox Len(str)

‘Returns 10, the string length measured by its number of characters.

MsgBox Len(«James Bond»)

End Sub

Example — Using the vba Len function — variable types.

Sub Len_vbaFunc()
‘using vba Len function — variable types

‘—————————

‘returns 3 in both cases — number of characters in the string:

MsgBox Len(«bad»)

MsgBox Len(«245»)

‘returns 10 — number of characters in the string including the space:

MsgBox Len(«James Bond»)

‘—————————

‘a variable of type variant is treated as a string

Dim vVar As Variant

vVar = 245

‘returns 2, indicating variable subtype Integer:

MsgBox VarType(vVar)

‘Returns 3, the number of characters contained in the variable — the Len functions treats the variant variable as a String:

MsgBox Len(vVar)

‘—————————

‘a variable of type string

Dim strVar As String

strVar = «James Bond»

‘returns 8, indicating variable subtype String:

MsgBox VarType(strVar)

‘Returns 10, the number of characters contained in the variable of type String:

MsgBox Len(strVar)

‘—————————

‘a variable of type integer

Dim iVar As Integer

iVar = 245

‘Returns 2, the number of bytes used to store the variable:

MsgBox Len(iVar)

‘a variable of type long

Dim lVar As Long

lVar = 245

‘Returns 4, the number of bytes used to store the variable:

MsgBox Len(lVar)

‘a variable of type single

Dim sVar As Single

sVar = 245.567

‘Returns 4, the number of bytes used to store the variable:

MsgBox Len(sVar)

‘a variable of type double

Dim dVar As Double

dVar = 245.567

‘Returns 8, the number of bytes used to store the variable:

MsgBox Len(dVar)

‘—————————

End Sub

Example — Using LEN and MID Functions, to determine characters appearing at odd number positions in a text string.

Sub Mid_Len_OddNoCharacters()

‘Using LEN and MID Functions, to determine characters appearing at odd number positions in a text string

Sheets(«Sheet1»).Activate

Dim str As String, strOdd, i As Integer

‘assign text string in cell A2 («HELLO») to variable (str)

str = ActiveSheet.Range(«A2»).Value

‘loop though each character — vba Len function determines the length or number of characters in the text string

For i = 1 To Len(str)

‘check odd number position

If i Mod 2 = 1 Then

‘return character at odd number position, and add it to the string variable srtOdd

‘vba Mid function extracts 1 character from str, starting from character number i

strOdd = strOdd & Mid(str, i, 1)

End If

Next

MsgBox strOdd

‘enter the string (variable srtOdd) containing odd positioned characters in cell A3 («HLO»)

Range(«A3»).Value = strOdd

Example — Using LEFT, LEN and MID Functions, to return initials of full name.

Sub Left_Mid_Len_InitialsOfName()
‘Using LEFT, LEN and MID Functions, to return initials of full name.
‘return initials from a text string containing full name comprising of multiple words
‘consider a string containing the first name, middle name(s) & surname, having inbetween spaces — return initials of full name, wherein each initial is followed by a dot and space.

Sheets(«Sheet1»).Activate

Dim strName As String, strInitials As String

Dim i As Integer

‘assign variable strName to the text string — the first name, middle name(s) & surname with inbetween spaces:

‘strName = «   Alec Thomas stone     Hanson    «

strName = ActiveSheet.Range(«A6»).Value

‘loop though each character:

For i = 1 To Len(strName)

‘if first character

If i = 1 Then

‘if the first character is not blank space, it will be an initial:

If Left(strName, i) <> » » Then

‘add dot after first initial

strInitials = Left(strName, 1) & «.»

End If

‘if NOT first character

Else

‘if any character after the first character is preceded by a blank space, it will be an initial:

If Mid(strName, i — 1, 1) = » » And Mid(strName, i, 1) <> » » Then

‘determines if first initial

If Len(strInitials) < 1 Then

‘add dot after first initial

strInitials = Mid(strName, i, 1) & «.»

‘for multiple initials:

Else

‘for multiple initials, add to the previous initial(s):

strInitials = strInitials & » » & Mid(strName, i, 1) & «.»

End If

End If

End If

Next i

‘convert all initials to upper case:

strInitials = UCase(strInitials)

‘returns «A. T. S. H.» and enter the string variable strInitials in cell A7

MsgBox strInitials

Range(«A7»).Value = strInitials

‘returns 11 — 4 letters, 4 dots & 3 blank spaces

MsgBox Len(strInitials)

REPLACE Function (Worksheet)

The worksheet REPLACE function replaces part of a text string with a new text string, based on specified number of characters and starting from a specified position. Syntax: REPLACE(old_text, start_number, number_of_chars, new_text). It is necessary to specify all arguments. The old_text argument is the text string in which you want to replace with new text. The start_number argument is the position of the character in old_text, which you want to replace (ie. position of the first character from which replacement should start). Position is the character number, first character being number 1 & incrementing towards the right. The number_of_chars is the number of characters which will be replaced in the old_text (with new_text). The new_text is the text string which will replace the characters in old_text.

Example — using the Worksheet Replace Function in vba code to delete blank spaces in excess of a specified number, within a string

Function DeleteBlankSpaces(str As String, iSpaces As Integer) As String
‘using the Worksheet Replace Function in vba code to delete blank spaces in excess of a specified number, within a string (str)
‘use this code to reduce multiple spaces within a string to a specified number of spaces (iSpaces)
‘this code can also delete ALL spaces within a string
‘this code can also convert multiple spaces to a single space within a string, similar to the worksheet Trim function, except that using Trim deletes ALL blank spaces before the first (non-space) character also.

Dim n As Integer, counter As Integer

counter = 0

‘start from last character in the string and move to the first

For n = Len(str) To 1 Step -1

‘if character is blank space

If Mid(str, n, 1) = » « Then

‘increment counter by 1

counter = counter + 1

‘if blank space(s) equal to or less than specified number

If counter < iSpaces + 1 Then

‘go to next character ie. next n

GoTo skip

‘if blank space(s) in excess of specified number, then delete

Else

‘using the worksheet Replace function to replace with a zero-length string

str = Application.Replace(str, n, 1, «»)

End If

‘if character is NOT blank space, go to next character ie. next n

Else

‘restore to 0 if non-blank character

counter = 0

End If

skip:

Next n

‘function returns the final string after deleting excess consecutive blank spaces

DeleteBlankSpaces = str

Sub DelBlSp()
‘delete excess consecutive blank spaces within a string (str) ie. in excess of a specified number
‘Note: this code does not ensure uniform no. of blank spaces but ONLY deletes excess blanks

Sheets(«Sheet1»).Activate

Dim strText As String, iSpaces As Integer

‘assign string in cell A10 (» Specify    max spaces    in  text   .») of active sheet to variable (strText)

strText = ActiveSheet.Range(«A10»).Value

‘specify the maximum number of consecutive spaces to retain within the string — this procedure will delete spaces in excess of this specified Number

‘assign this max number to variable iSpaces

iSpaces = 2

‘strText contains 4 blank spaces after «Specify», 4 blank spaces after «spaces» & 3 blank spaces after «text», all of which are reduced to 2 blank spaces

‘enter final string in cell A11 (» Specify  max spaces  in  text  .») of active sheet — call DeleteBlankSpaces function and pass the arguments of string (strText) & specified blank spaces (iSpaces)

ActiveSheet.Range(«A11»).Value = DeleteBlankSpaces(strText, iSpaces)

Example — ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present

Function UniformBlankSpaces(str As String, iSpaces As Integer) As String
‘ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present

Dim n As Integer, counter As Integer

‘counter is used to determine the no. of consecutive blank spaces

counter = 0

‘start from last character in the string and move to the first

For n = Len(str) To 1 Step -1

‘if character is blank space

If Mid(str, n, 1) = » » Then

‘increment counter by 1

counter = counter + 1

‘if blank space(s) is less than specified number

If counter < iSpaces Then

‘if first character of the string is a blank space

If n = 1 Then

‘add blank space

str = Left(str, 1) & » » & Right(str, Len(str) — n)

‘if character preceding blank space at n is NOT a blank Space

ElseIf Mid(str, n — 1, 1) <> » » Then

‘add blank space

str = Mid(str, 1, n) & » » & Right(str, Len(str) — n)

‘if character preceding blank space at n is also a blank Space

Else

‘go to next character ie. next n

GoTo skip

End If

‘if blank space(s) in excess of specified number, then delete

ElseIf counter > iSpaces Then

‘using the worksheet Replace function to replace with a zero-length string

str = Application.Replace(str, n, 1, «»)

End If

‘if character is NOT blank space, go to next character ie. next n

Else

‘restore counter to 0 if non-blank character

counter = 0

End If

skip:

Next n

‘function returns the final string with uniform consecutive blank spaces

UniformBlankSpaces = str

Sub UniformBlSp()
‘ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present
‘Note: this code ensures uniform no. of blank spaces where lead & trailing spaces are also present

Sheets(«Sheet1»).Activate

Dim strText As String, iSpaces As Integer

‘assign string in cell A10 (» Specify    max spaces    in  text   .») of active sheet to variable (strText)

strText = ActiveSheet.Range(«A10»).Value

‘specify the uniform number of consecutive spaces to retain within the string — this procedure will delete/add spaces in excess/short of this specified Number

‘assign this number to variable iSpaces

iSpaces = 2

‘enter final string in cell A12 (»  Specify  max  spaces  in  text  .») — call UniformBlankSpaces function and pass the arguments of string & specified blank spaces

ActiveSheet.Range(«A12»).Value = UniformBlankSpaces(strText, iSpaces)

REPLACE Function (VBA)

The vba Replace Function is used to return a string in which a specified substring is replaced, a specified number of times, with another specified substring. Syntax:  Replace(expression, find, replace, start, count, compare). It is necessary to specify the arguments of expression, find and replace, while the start, count & compare arguments are optional.

The expression argument is the string in which a specific substring is replaced. For a zero-length expression string a zero-length string is returned, and for a Null expression the function will give an error. The find argument specifies the substring which is to be replaced. If find substring is zero-length, then a copy of the expression is returned. The replace argument specifies that ‘another substring’ which replaces (ie. the replacement substring). A replace substring of zero-length has the effect of deleting all occurrences of find from the expression. The start argument specifies the position (ie. character number) in the expression from where you want to start your search for the ‘find’ substring. If omitted, it will default to1 (ie. search will start from first character position). The string returned by the Replace function begins from this start position till the last character of the expression string, after the replacement(s). Specifying a start position which is greater than the length of the expression, will return a zero-length string. The count argument specifies the number of substring replacements you want to do. Omitting to specify this will default to the value -1, which will make all possible replacements. Specifying zero for the count will have the effect of no replacement and will return a copy of the expression. The compare argument specifies the type of comparison to use for evaluating substrings — a numeric value or a constant can be specified herein, as detailed below.

You can specify the following arguments for the compare argument: vbUseCompareOption (value: -1) performs a comparison using the setting of the Option Compare statement. vbBinaryCompare (value: 0) performs a binary comparison — string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages), wherein uppercase characters are always less than lowercase characters -> A < B < U < Z < a < b < u < z < À < Û < à < û. vbTextCompare (value: 1) performs a textual comparison — string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z). vbDatabaseCompare (value: 2) performs a comparison based on information in your database (can be used within Microsoft Access only). If you do not specify the compare argument, the comparison is done based on the defined Option Compare statement. Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method — you must specify ‘Option Compare Binary’ or ‘Option Compare Text’ at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.

Example — using the vba Replace function.

Sub Replace_vbaFunc()
‘using the vba Replace function

Dim str As String, strFind As String, strReplace As String

‘find all ocurrences of «s» to be replaced:

strFind = «s»

‘set replace string as zero-length:

strReplace = «»

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘returns the string after deleting all occurences of ‘s’ — «She wa elling ea hell!». Note that capital ‘S’ is not replaced.

str = Replace(str, strFind, strReplace)

MsgBox str

‘returns 22:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘returns the string after deleting all occurences of ‘s’ — «he wa elling ea hell!».

‘Note that capital ‘S’ is also replaced because a textual comparison has been done by setting the compare argument value to vbTextCompare (value: 1).

str = Replace(str, strFind, strReplace, , , 1)

MsgBox str

‘returns 21:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘deleting all occurences of ‘s’ from start position 8 — returns » elling ea hell!». Note that the character number 8 is a blank space and this is also returned.

‘the string returned by the Replace function begins from this start position till the last character of the expression string.

str = Replace(str, strFind, strReplace, 8)

MsgBox str

‘returns 16:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘Specifying a start position which is greater than the length of the expression, will return a zero-length string.

str = Replace(str, strFind, strReplace, 28)

‘returns a zero-length string:

MsgBox str

‘returns 0:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘The count argument specifies the number of substring replacements you want to do. Omitting to specify this will default to the value -1, which will make all possible replacements.

‘specifying a start position of 8, and count of 2:

str = Replace(str, strFind, strReplace, 8, 2)

‘returns » elling ea shells!», after deleting ‘s’ twice from start position of 8.

MsgBox str

‘returns 18:

MsgBox Len(str)

‘—————————

End Sub

Example — Manipulate Strings in Excel VBA — Remove Numericals, Delete/Add Blank Spaces, Capitalize letters.

To download Excel file with live code, click here.

Function StringManipulation(str As String) As String

‘String Manipulation using vba & worksheet Replace funcions, Trim / Len / Right / Mid / Chr / Asc / Ucase function.

‘This code manipulates a string text as follows:
‘1. removes numericals from a text string;
‘2. removes leading, trailing & inbetween spaces (leaves single space between words);
‘3. adds space (if not present) after each exclamation, comma, full stop and question mark;
‘4. capitalizes the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark;

Dim iTxtLen As Integer, iStrLen As Integer, n As Integer, i As Integer, ansiCode As Integer

‘—————————

‘REMOVE NUMERICALS

‘The vba Chr function returns a character (string data type) identified to the specified character code.

‘Excel uses ANSI character set for Windows computers. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set, so that the returned character corresponds to this character set.

‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII Character codes

For i = 48 To 57

‘remove all numericals from the text string using vba Replace function

str = Replace(str, Chr(i), «»)

Next i

‘—————————

‘REMOVE LEADING, TRAILING & INBETWEEN SPACES (LEAVE SINGLE SPACE BETWEEN WORDS)

‘use the worksheet TRIM function. Note: the TRIM function removes space character with ANSI code 32, does not remove the nonbreaking space character with ANSI code 160

str = Application.Trim(str)

‘—————————

‘ADD SPACE (IF NOT PRESENT) AFTER EACH EXCLAMATION, COMMA, DOT AND QUESTION MARK:

‘set variable (iTxtLen) value to string length

iTxtLen = Len(str)

‘start from last character in the string and move to the first

For n = iTxtLen To 1 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns dot / full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is not present after, except for the last Character

If Mid(str, n + 1, 1) <> Chr(32) And n <> iTxtLen Then

‘using Mid & Right functions to add space — note that current string length is used

str = Mid(str, 1, n) & Chr(32) & Right(str, iTxtLen — n)

‘update string length — increments by 1 after adding a space (character) — this enables correct use of the Right Function in above line

iTxtLen = iTxtLen + 1

End If

End If

Next n

‘—————————

‘DELETE SPACE (IF PRESENT) BEFORE EACH EXCLAMATION, COMMA, DOT & QUESTION MARK:

‘reset variable value to string length:

iTxtLen = Len(str)

‘exclude the first character

For n = iTxtLen To 2 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is present before

If Mid(str, n — 1, 1) = Chr(32) Then

‘using the worksheet Replace function to delete a space:

str = Application.Replace(str, n — 1, 1, «»)

‘omit rechecking the same character again- position of n shifts (decreases by 1) due to deleting a space character:

n = n — 1

End If

End If

Next n

‘—————————

‘CAPITALIZE LETTERS:

‘capitalize the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark, while all other letters are lower case

iStrLen = Len(str)

For i = 1 To iStrLen

‘determine the ANSI code of each character in the string: Excel uses ANSI character set for Windows computers. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set, so that the returned character corresponds to this character set.

‘The vba Asc function returns the corresponding character code (Integer data type) for the string letter — Asc(string).

ansiCode = Asc(Mid(str, i, 1))

Select Case ansiCode

’97 to 122 are the ANSI codes equating to small cap letters «a» to «z»

Case 97 To 122

‘character no 3 onwards to enable determining if 2 positions preceding it is an exclamation, full stop & question mark

If i > 2 Then

‘capitalizes a letter whose position is 2 characters after (1 character after, will be the space character added earlier) an exclamation, full stop & question mark:

If Mid(str, i — 2, 1) = Chr(33) Or Mid(str, i — 2, 1) = Chr(46) Or Mid(str, i — 2, 1) = Chr(63) Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘capitalize first letter of the string:

ElseIf i = 1 Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘if capital letter, skip to next character (ie. next i):

Case Else

GoTo skip

End Select

skip:

Next i

‘—————————

‘function returns the final manipulated string

StringManipulation = str

End Function

Sub Str_Man()
‘manipulate string

Sheets(«Sheet2»).Activate

Dim strText As String

‘specify the text string which is required to be manipulated (» 2manipulate    text string8 ,    by   vba   Code   .check   below cell  !    ok ?thanks 7 .   «), and assign to string variable strText

strText = ActiveSheet.Range(«A2»).Value

‘enter manipulated string in cell A3 («Manipulate text string, by vba Code. Check below cell! Ok? Thanks.») of active sheet — call StringManipulation function and pass the string (str) argument

ActiveSheet.Range(«A3»).Value = StringManipulation(strText)

End Sub

Example — Replace all occurrences of a substring in a string expression, with another substring — using the vba Replace function.

To download Excel file with live code, click here.

Function Replace_Str1(var As Variant, vFind As Variant, vReplace As Variant, iOption As Integer) As Variant

‘Replaces all occurrences of substring (vFind) in the string (var), with another substring (vReplace) — using the vba Replace function.

‘position of the first occurrence of vFind, within var:

iPosn = InStr(var, vFind)

‘if vFind not found within var

If iPosn < 1 Then

‘return var string:

Replace_Str1 = var

‘if vFind found within var

Else

‘use the vba Replace function to replace all instances of vFind with vReplace

Replace_Str1 = Replace(var, vFind, vReplace, , , iOption)

End If

Sub ReplaceStr1()
‘Replaces all occurrences of substring (vFind) in the string (var), with another substring (vReplace) — using the vba Replace function.
‘this procedure calls Replace_Str1 function and passes the four argumentes of string (var) in which a specific substring (vFind) is replaced with another substring (vReplace) and the type of comparison (iOption) to use for evaluating substrings

Sheets(«Sheet3»).Activate

Dim var As Variant, vFind As Variant, vReplace As Variant, iOption As Integer

‘var is the string within which vFind is searched & replaced by vReplace:

‘var = «she Sells sea shellS«

var = ActiveSheet.Range(«A2»).Value

‘vFind is the string to search within var & which will be replaced by vReplace:

vFind = «s«

‘vReplace is the string which replace all instances of vFind within var:

vReplace = «?«

‘———-

‘to delete all spaces, use a zero-length string for vReplace

‘vFind = » «

‘vReplace = «»

‘———-

‘in a case-insensitive comparison, if you specify to replace occurrences of «a» then instances of both «A» & «a» will be replaced.

‘to perform a binary comparison (case-sensitive), use value 0:

‘iOption = 0

‘to perform a text comparison (case-insensitive), use value 1:

iOption = 1

‘Null: where a variable contains no valid data — Null may have been explicitly assigned to a variable, or it could be a result of an operation between expressions containing Null.

‘if var is Null, exit procedure

If IsNull(var) Then

MsgBox «var is Null, exiting procedure»

Exit Sub

‘if var is not Null:

Else

‘if vFind is Null or a zero-length string:

If IsNull(vFind) Or vFind = «» Then

‘return var without any replacements & exit procedure:

MsgBox «Either vFind is Null or a zero-length»

ActiveSheet.Range(«A3») = var

Exit Sub

Else

‘if var or vFind are not Null, and vFind is not zero-length, replace all instances of vFind («?he ?ell? ?ea ?hell?»):

ActiveSheet.Range(«A3») = Replace_Str1(var, vFind, vReplace, iOption)

End If

End If

InStr & InStrRev Functions (VBA)

The InStr Function returns the position (character number) in which a string first occurs within another string. Syntax: InStr(start, string, substring, compare). It is necessary to specify the arguments of string and substring, while the start & compare arguments are optional.

The start argument specifies the position (ie. character number) within string from where you want to start your search for the substring. It is necessary to specify the start argument, if the compare argument is to be specified. If omitted, it will default to1 (ie. search will start from the first character position). Specifying a start position which is greater than the length of string will return a 0 (zero), and if start contains Null an error will occur. The string argument is the string expression within which substring is being searched. The function returns 0 if string is zero-length, and returns Null if string is Null. The substring argument is the string expression which is being searched within string and whose position will be returned by the function. The function returns 0 if substring is not found, returns the start value if string is zero-length, and returns Null if substring is Null. The compare argument specifies the type of comparison to use for evaluating strings — a numeric value or a constant can be specified herein, as detailed below.

You can specify the following arguments for the compare argument: vbUseCompareOption (value: -1) performs a comparison using the setting of the Option Compare statement. vbBinaryCompare (value: 0) performs a binary comparison — string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages), wherein uppercase characters are always less than lowercase characters -> A < B < U < Z < a < b < u < z < À < Û < à < û. vbTextCompare (value: 1) performs a textual comparison — string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z). vbDatabaseCompare (value: 2) performs a comparison based on information in your database (can be used within Microsoft Access only). If you do not specify the compare argument, the comparison is done based on the defined Option Compare statement. Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method — you must specify ‘Option Compare Binary’ or ‘Option Compare Text’ at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.

The InStrRev Function returns the position (character number) in which a string first occurs within another string, starting from the end of that another string. Syntax: InStrRev(string, substring, start, compare). Use InStrRev function instead of InStr to search in the reverse direction. It is necessary to specify the arguments of string and substring, while the start & compare arguments are optional. If start is omitted, -1 is used, meaning that the search will begin from the last character position. All other syntax explanations remain same as in the InStr function.

Example — Using the InStr function.

Sub InStrFunc()
‘using the InStr function

Dim str1 As String, str2 As String

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 3:

MsgBox InStr(str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 6:

MsgBox InStr(4, str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 0 because start value (24) is greater than length of str1 (20):

MsgBox InStr(24, str1, str2)

‘——————

str1 = «»

str2 = «e»

‘returns 0 because str1 is zero-length:

MsgBox InStr(str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «f»

‘returns 0 because str2 is not found:

MsgBox InStr(str1, str2)

‘——————

Dim str3 As Variant

str1 = «she sells sea shells»

str3 = Null

‘returns 1, indicating subtype Null — because str3 is Null:

MsgBox VarType(InStr(str1, str3))

‘——————

str1 = «she Sells sea shells»

str2 = «s»

‘returns 9 — the default text comparison type is Binary (case-sensitive):

MsgBox InStr(2, str1, str2)

‘returns 5 — performing a textual comparison wherein comparison type is not case-sensitive:

MsgBox InStr(2, str1, str2, 1)

‘——————

End Sub

Example — Replace all occurrences of a substring in a string expression, with another substring — using the InStr, Left & Mid functions.

To download Excel file with live code, click here.

Function Replace_Str2(var As Variant, vFind As Variant, vReplace As Variant) As Variant
‘Replace all occurrences of a substring in a string expression, with another substring — using the InStr, Left & Mid functions.
‘Replaces all occurrences of vFind in var, with vReplace — using the InStr, Left & Mid functions.
‘Replacement will be case-sensitive in this procedure ie. if you specify to replace occurrences of «a» then instances of «A» will NOT be replaced.

Dim iPosn As Integer

‘position of the first occurrence of vFind, within var:

iPosn = InStr(var, vFind)

‘length of vFind, which will be replaced with vReplace:

iFindLen = Len(vFind)

‘length of vReplace, which will replaced vFind:

iReplaceLen = Len(vReplace)

‘if vFind not found within var:

If iPosn < 1 Then

‘return var string & exit procedure:

Replace_Str2 = var

Exit Function

‘if vFind found within var:

Else

‘loop:

Do

‘replace vFind with vReplace within var — use the Left & Mid functions to return string. Omitting character nos from the Mid function will return the text string in full from start number position to end of the text string.

var = Left(var, iPosn — 1) & vReplace & Mid(var, iPosn + iFindLen)

‘position of the first occurrence of vFind within updated var, starting the position search from the first character AFTER the latest replacement (iPosn + iReplaceLen)

iPosn = InStr(iPosn + iReplaceLen, var, vFind)

‘if vFind not found within updated var, exit loop

If iPosn = 0 Then Exit Do

Loop

End If

Replace_Str2 = var

Sub ReplaceStr2()
‘Replaces all occurrences of vFind in var, with vReplace — using the InStr, Left & Mid functions.
‘Replacement will be case-sensitive in this procedure ie. if you specify to replace occurrences of «a» then instances of «A» will NOT be replaced.

Sheets(«Sheet3»).Activate

Dim var As Variant, vFind As Variant, vReplace As Variant

‘var is the string within which vFind is searched & replaced by vReplace:

‘var = «she Sells sea shellS«

var = ActiveSheet.Range(«A6»).Value

‘vFind is the string to search within var & which will be replaced by vReplace

vFind = «s«

‘vReplace is the string which replace all instances of vFind within var:

vReplace = «?«

‘if var is Null, exit procedure:

If IsNull(var) Then

MsgBox «var is Null, exiting procedure»

Exit Sub

‘if var is not Null:

Else

‘if vFind is Null or a zero-length string:

If IsNull(vFind) Or vFind = «» Then

‘return var without any replacements & exit procedure

MsgBox «Either vFind is Null or a zero-length»

ActiveSheet.Range(«A7»).Value = var

Exit Sub

Else

‘if var or vFind are not Null, and vFind is not zero-length, replace all instances of vFind («?he Sell? ?ea ?hellS»)

ActiveSheet.Range(«A7»).Value = Replace_Str2(var, vFind, vReplace)

End If

End If

Like this post? Please share to your friends:
  • Vba for excel самоучитель
  • Vba macros for word
  • Vba for excel изменить цвет ячейки если
  • Vba for excel практикум
  • Vba macros for excel access