Работа с текстом в коде 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):
Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:
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 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.
In this Article
- Len Function
- VBA Len Count Characters
- VBA Len Strings or Variants
- VBA Len Count Occurrences of a Character
- VBA Len Count Occurrences of a Substring
This tutorial will demonstrate how to use the Len VBA function to get the length of a string.
Len Function
The VBA Len function returns the length of a specified string.
VBA Len Count Characters
The VBA Len function counts the characters in a string.
Sub LenExample_1()
MsgBox Len("12345") 'Result is: 5
MsgBox Len("12") 'Result is: 2
MsgBox Len("1") 'Result is: 1
MsgBox Len(" ") 'Result is: 1
'There is a space character in there.
MsgBox Len("") 'Result is: 0
MsgBox Len("AB Cd") 'Result is: 5
End Sub
VBA Len Strings or Variants
VBA Len Function can count the number of characters in variables declared as strings or variants. Actually, VBA Len will treat a variant as a string. If VBA Len is used with an integer, long, single or double then VBA Len is going to count the number of bytes needed to store the variable.
Sub LenExample_2()
Dim VarEx1 As String
VarEx1 = 12345
MsgBox Len(VarEx1) 'Result is: 5
'Len is counting the number of characters in variable
Dim VarEx2 As Variant
VarEx2 = 12345
MsgBox Len(VarEx2) 'Result is: 5
'Len is counting the number of characters in variable
Dim VarEx3 As Integer
VarEx3 = 12345
MsgBox Len(VarEx3) 'Result is: 2
'Len is counting the number of bytes used to store the variable
Dim VarEx4 As Long
VarEx4 = 12345
MsgBox Len(VarEx4) 'Result is: 2
'Len is counting the number of bytes used to store the variable
Dim VarEx5 As Single
VarEx5 = 12345
MsgBox Len(VarEx5) 'Result is: 2
'Len is counting the number of bytes used to store the variable
Dim VarEx6 As Double
VarEx6 = 12345
MsgBox Len(VarEx6) 'Result is: 2
'Len is counting the number of bytes used to store the variable
End Sub
VBA Len Count Occurrences of a Character
VBA Len function can be used with VBA Replace function to count how many times a character is found in a string.
VBA Replace Function can replace a substring with another substring in a text:
MsgBox Replace("XBCX", "X", "7") 'Result is: "7BC7"
We can use Replace to remove the characters we want to count with “” and then find the difference in length before and after the replacement.
Sub LenExample_3()
Dim StrEx As String 'Define a string variable
StrEx = "Jack,John,Jim,Jordan"
MsgBox Len(StrEx) - Len(Replace(StrEx, ",", "")) 'Result is: 3
'Breaking down the code above
MsgBox Len(StrEx) 'Result is: 20
MsgBox Replace(StrEx, ",", "") 'Result is: "JackJohnJimJordan"
MsgBox Len(Replace(StrEx, ",", "")) 'Result is: 17
MsgBox Len(StrEx) - Len(Replace(StrEx, ",", "")) 'Result is: 20-17=3
End Sub
VBA Len Count Occurrences of a Substring
VBA Len function can be used with VBA Replace function to count how many times a substring is found in a string.
VBA Replace Function can replace a substring with another substring in a text:
MsgBox Replace("XB cX", "X", "7") 'Result is: "7B c7"
We can use Replace to remove the substrings we want to count with “” and then find the difference in length before and after the replacement. Finally, we need to divide the difference with the length of the substring we replaced.
Sub LenExample_4()
Dim StrEx As String 'Define a string variable
StrEx = "Jack, John, Jim, Jordan"
Dim SubStr As String 'Define a substring variable
SubStr = ", "
'We will find how many times SubStr is found inside StrEx
MsgBox (Len(StrEx) - Len(Replace(StrEx, SubStr, ""))) / Len(SubStr) 'Result is: 3
'Breaking down the code above
MsgBox Len(StrEx) 'Result is: 23
MsgBox Replace(StrEx, SubStr, "") 'Result is: "JackJohnJimJordan"
MsgBox Len(Replace(StrEx, SubStr, "")) 'Result is: 17
MsgBox Len(StrEx) - Len(Replace(StrEx, SubStr, "")) 'Result is: 23-17=6
MsgBox (Len(StrEx) - Len(Replace(StrEx, SubStr, ""))) / Len(SubStr)
'Result is: (23-17)/2=3
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
What is VBA Length of String?
VBA Len is a significant tool for data validation. VBA LEN function Returns the number of characters in a supplied string i.e. to measure the length of text or number of characters in a text. VBA LEN is categorized under the String function. It can be used as either procedure or function in the VBA editor window. It is frequently used as a support function along with other string functions like MID, RIGHT i.e. To pullout name parts from a full name.
Syntax of VBA Length of String in Excel
The syntax for VBA Length of String function in excel is as follows:
After typing LEN click on spacebar, the above-mentioned syntax appears where it contains the below-mentioned argument.
- String: It is an expression or a text string or a variable name from which you want to return the length.
i.e. Len(“Length”) = return the value 6, because the length of the text “Length” is 6. If you take a variable as Variant instead of long then it is considered the same as a string. i.e. the Len functions treat the variant variable as a String.
How to Use Length of String Function in Excel VBA?
Below are the different examples to use Length of string in Excel using VBA code.
You can download this VBA Length of String Excel Template here – VBA Length of String Excel Template
VBA Length of String – Example #1
Follow the below steps to use a length of string function in excel VBA.
Step 1: Go to the Developers tab and click on Visual Basic.
Step 2: Open a Module from the Insert menu option as shown below.
Step 3: Under the Microsoft Excel objects, right-click on sheet 1 (VB_LEN) Insert and under the menu section select Module, so that a new blank module gets created.
VBA Length of String – Example #2
Suppose, I have the word “NULL” and I want to find out the number of characters in this text string i.e. for this, with the help of VB LEN function macro code, I can find out.
Step 1: In the VBA editor, I have given a name as LENGTH() after typing Sub
Sub LENGTH() End Sub
Step 2: As VBA LEN function is categorized under string type, DIM (Dimension) is used in a VBA code to declare a variable name, it’s type. In VBA, you need to always declare initially that you are setting up a variable. This is done (mostly) with the word Dim.
DIM is used to declare variable & storage allocation for variable.
Syntax: Dim [Insert Variable Name] as [Insert Variable Type]
Code:
Sub LENGTH() Dim L As Variant End Sub
Step 3: After declaring a variable, Assign a value to this variable with the help of LEN function.
Code:
Sub LENGTH() Dim L As Variant L = Len ( End Sub
Step 4: After typing LEN and click on the spacebar and once you enter open bracket below mentioned syntax appears for the right function.
String: It is an expression or a text string or a variable name from which you want to return length i.e. “LENGTH”
Code:
Sub LENGTH() Dim L As Variant L = Len("LENGTH") MsgBox L End Sub
Once you finished typing LEN function arguments. Now, I want to display this result of the len function in the message box. then in the next line of code, let’s click on Ctrl + Space, type MsgBox after this you can mention a variable name.
Step 5: Now, the code is ready, you can run it by click on the F5 key. Once you do that, Pop up message appears, with a result in it as “6” which indicates the number of characters in a supplied string or text (Length)
VBA Length of String – Example #3
Now, instead of output appearing in the message box, I want the result or output data to appear in the worksheet. In the worksheet, I have a data, i.e. USA state in the cell “A4”, now I want to find out a number of characters in the text string of state, Here I can use Len function with slight modification in the code.
Step 1: After declaring a variable, I have to input the variable name again and cell address of the full-text string with the help of Range or cell function.
Code:
Sub TEXT_LENGTH() Dim L As Variant L = Range("A4") End Sub
Step 2: Now, again I need to enter a variable name, and apply LEN function & input its arguments.
Code:
Sub TEXT_LENGTH() Dim L As Variant L = Range("A4") L = Len("Massachusetts") End Sub
In the previous example, we entered msg box for the result to be displayed, now, I want the result to appear in a specific cell in a worksheet. for this, I need to enter range or cell function for the result to be displayed.
Step 3: Now, let’s apply range function, initially I need to input the range or cell function and later enter the variable name, so that in that specific cell (“B4”), the result appears.
Code:
Sub TEXT_LENGTH() Dim L As Variant L = Range("A4") L = Len("Massachusetts") Range("B4").Value = L End Sub
Step 4: Now, the code is ready, I can run it by click on the F5 key. once I do that, you can observe an output value of LEN function appearing in the cell “B4” i.e. 13 which indicates the number of characters in a supplied string or text.
Things to Remember
- Apart from LEN function, LenB is used to calculate or to find out the actual number of required bytes for a provided variable in memory.
- Object variable should not be used in Len function.
Recommended Articles
This is a guide to VBA Length of String Function. Here we discuss how to use VBA Length of String Function in Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Workbook
- VBA String Array
- VBA String Comparison
- VBA RGB
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Len function (Visual Basic for Applications) |
vblr6.chm1011065 |
vblr6.chm1011065 |
office |
5b5b8789-90cc-ac2c-e6a7-1da1d684bd81 |
12/13/2018 |
medium |
Returns a Long containing the number of characters in a string or the number of bytes required to store a variable.
Syntax
Len(string | varname)
The Len function syntax has these parts:
Part | Description |
---|---|
string | Any valid string expression. If string contains Null, Null is returned. |
varname | Any valid variable name. If varname contains Null, Null is returned. If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains. |
Remarks
One (and only one) of the two possible arguments must be specified. With user-defined types, Len returns the size as it will be written to the file.
[!NOTE]
Use the LenB function with byte data contained in a string, as in double-byte character set (DBCS) languages. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string. With user-defined types, LenB returns the in-memory size, including any padding between elements. For sample code that uses LenB, see the second example in the example topic.
[!NOTE]
Len may not be able to determine the actual number of storage bytes required when used with variable-length strings in user-defined data types.
Example
The first example uses Len to return the number of characters in a string or the number of bytes required to store a variable. The Type…End Type block defining CustomerRecord
must be preceded by the keyword Private if it appears in a class module. In a standard module, a Type statement can be Public.
Type CustomerRecord ' Define user-defined type. ID As Integer ' Place this definition in a Name As String * 10 ' standard module. Address As String * 30 End Type Dim Customer As CustomerRecord ' Declare variables. Dim MyInt As Integer, MyCur As Currency Dim MyString, MyLen MyString = "Hello World" ' Initialize variable. MyLen = Len(MyInt) ' Returns 2. MyLen = Len(Customer) ' Returns 42. MyLen = Len(MyString) ' Returns 11. MyLen = Len(MyCur) ' Returns 8.
The second example uses LenB and a user-defined function (LenMbcs) to return the number of byte characters in a string if ANSI is used to represent the string.
Function LenMbcs (ByVal str as String) LenMbcs = LenB(StrConv(str, vbFromUnicode)) End Function Dim MyString, MyLen MyString = "ABc" ' Where "A" and "B" are DBCS and "c" is SBCS. MyLen = Len(MyString) ' Returns 3 - 3 characters in the string. MyLen = LenB(MyString) ' Returns 6 - 6 bytes used for Unicode. MyLen = LenMbcs(MyString) ' Returns 5 - 5 bytes used for ANSI.
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
Visual Basic for Applications or VBA is an event driven programming language which enhances, the applications of the Microsoft Office suite of products. It’s also an object-oriented programming language with an associated integrated development environment. It is most often used to create macros which automate routine tasks in MS office applications. However, VBA is most commonly used in MS Excel. You can code in VBA which will interact with or output to your excel spreadsheet.
You can learn more about using VBA Macros with Excel in this introductory course.
Strings are an important part of any programming language. A string is basically any kind of saved text. You can do a number of operations on strings including concatenation, reversal, sorting, finding string length, deriving substrings, searching for specific character in a string and more. Today, we introduce you to the concept of VBA string length. We assume that you know the basic concepts of Excel VBA and strings. If you are not familiar with these concepts we suggest that you go through our tutorial on basics of VBA.
What is a String?
A string is an array of characters. String length is the number of characters in a string. The variable which stores a string is declared as string data type. It is then assigned a value. Take a look at the example given here:
Dim MyName as String MyName=" John Smith"
The string type has built-in functions that help you perform several manipulations on a string. To understand the example on string length you need to have a basic knowledge of programming. The best way to learn more about strings and string manipulation would be to take a basic course on C programming. Yes, C programming. You’ll find most other courses just brush through strings, or assume you already know about them. C being a basic programming language, most C courses will cover all data types in depth, including strings.
VBA Function to Calculate the Length of a String
MS Len function calculates the length of a string and returns it as a value. The syntax of this function is as follows:
Len( text )
Len() function works in the versions starting from Excel 2000 to Excel 2013. Take a look at the example below:
Dim LResult As Long LResult = Len ("http://www.shutterstock.com/")
In case you’d like to, you can check out this tutorial on strings in C, and see how they compare.
Determining Whether a String is a Fixed Length String or Resizable
In VBA, strings are resizable. The string functions of VBA can be used to set or retrieve parts of strings which have variable length. However, there are times when you require fixed length strings.
Dim A as String *10
In the above statement, A is declared as string of 10 characters. The drawback of this method is that the length of the string is permanently fixed at 10. The size of the string cannot be resized at run time. You cannot increase or decrease the length of the string. It is a must to know the length of the string at the time of coding. At times you may need to find out whether a string variable is a fixed length string or a resizable string. It is not possible to do this with a function call as VBA converts fixed length strings to resizable strings while passing the string variable to a function. Therefore you have to write code within the function in which string is declared to determine whether string is fixed or resizable.
Example1: Program to Test for Fixed Length Strings
Dim A As String Dim B As String * 10 Dim Orig_Len As Long Dim Orig_Val As String B = "ABC" A = "DEF" Orig_Len = Len(B) Orig_Val = B B = B & " " If Orig_Len = Len(B) Then Debug.Print "B is a fixed length string" Else Debug.Print "B is a sizable string" B = OrigVal End If Orig_Len = Len(A) OrigVal = AA = A & " " If Orig_Len = Len(A) Then Debug.Print "A is a fixed length string" Else Debug.Print "A is a sizable string" A = OrigVal End If
In this program the variables are declared as type string. The length of the String variable is calculated using the Len(string length) function. Then the variable is concatenated with a space character. The string length is recalculated. The first and second string length value is compared. If both are same the string is of type fixed length string. If both are different then the string is of type resizable string. To understand more about strings and VBA macros, you can try out this course on Excel VBA.
Example 2: Convert a String’s Original Length to a Specified Length
Let’s take another example. Here’s a VBA Program to return a string variable containing the specified text either on the right or left, padded with PadChar to make a string of a specified length.
Public Enum Size_StringSide Text_Left = 1 Text_Right = 2 End Enum Public Function SizeString(Text1 As String, Length1 As Long, _ Optional ByVal TextSide As Size_StringSide = Text_Left, _ Optional PadChar As String = " ") As String Dim sPadChar As String If Len(Text1) >= Length1 Then SizeString = Left(Text1, Length1) Exit Function End If If Len(PadChar) = 0 Then sPadChar = " " Else sPadChar = Left(PadChar, 1) End If If (TextSide <> Text_Left) And (TextSide <> Text_Right) Then TextSide = Text_Left End If If TextSide = Text_Left Then SizeString = Text1 & String(Length1 - Len(Text1), sPadChar) Else SizeString = String(Length1 - Len(Text1), sPadChar) & Text1 End If End Function
Text1 stands for the original string. Length1 stands for the length of the result string. Textside indicates whether text should come on the left in which case the result is padded on the right using PadChar. In case text should appear on the right, the string is padded on the left. A space is used if padChar is omitted. If PadChar is longer than one character we use the left most character of padChar. If TextSide is neither Text_Left nor Text_Right by default, the procedure uses Text_left.
Example 3: Find Tab Character in a String
Dim tab_Str as String Dim char as String Dim length_i As Integer Dim xCntr_i As Integer tab_Str = "good" & vbTab & "morning" length_i = Len(tab_Str) char = Left(tab_Str, 1) For xCntr_i = 0 To length_i - 1 tabString = Right(tab_Str, Len(tab_Str) - 1) If char = Chr(9) Then MsgBox "Index number " & xCntr_i & " is a tab in the String." End If char = Left(tab_Str, 1) Next xCntr_i
In this program, the variables tab_str, char are declared as data type string. length_i and xCntr_i are declared as integers. Variable tab_Str is assigned value string which contains a tab character. The length of the string contained in tab_Str is calculated using the len() function. Then we loop through each character in the string and check for the tab character. In the end, we display the position of the tab character in the string using MsgBox() function.
You can try out more Excel VBA examples with MrExcel in this course.
Mastering programming requires that you put in the effort to create your own unique programs. Though reading through existing code helps, what works better is experimenting with the code and trying out different stuff on your own. Hope this tutorial helped you on your way to become a proficient VBA programmer. Once you’re ready to take it to the next level, you can move on to our advanced Excel course!