Vba excel функция len

Работа с текстом в коде 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 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


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!
vba save as

Learn More!

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]

VBA LEN function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. It returns the length of a given string. It has one mandatory String parameter. If input string has Null, then it returns null. We use in both Worksheet and VBA function.
The LEN function can use in either procedure or function in a VBA editor window in Excel. We can use this VBA LEN function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the LEN function, where we can use this LEN function and real-time examples in VBA.

Table of Contents:

  • Overview
  • Syntax of VBA LEN Function
  • Parameters or Arguments
  • Where we can apply or use the VBA LEN Function?
  • Example 1: Find Length of a string:”987654321″
  • Example 2: Find Length of a string:”Life is Beautiful.”
  • Example 3: Find Length of empty string:””
  • Example 4: Find Length of a string::”123$#@”
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA LEN function is

Len(Expression)

Note: This LEN function founds the length of specified string.

Parameters or Arguments

This function has one mandatory parameter or argument for the LEN Function.
Where
Expression: The expression is a mandatory argument. The expression is the string which we want to know the length.

Where we can apply or use the VBA LEN Function?

We can use this VBA LEN function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Find Length of a string:”987654321″

Here is a simple example of the VBA LEN function. This below example macro returns the length a given string (Includes numbers).

'Find Length of a string:"987654321"
Sub VBA_Len_Function_Ex1()

    Dim sString As String, iCnt As Integer
    
    sString = "987654321"
    
    iCnt = Len(sString)
    
    MsgBox "The length of a given string is : " & iCnt, vbInformation, "VBA Len Function"

End Sub

Output: Here is the screen shot of the first example output.
VBA Len Function

Example 2: Find Length of a string:”Life is Beautiful.”

Here is a simple example of the VBA LEN function. This below example macro returns the length a given string (Includes space and dot).

'Find Length of a string:"Life is Beautiful."
Sub VBA_Len_Function_Ex()

    Dim sString As String, iCnt As Integer
    
    sString = "Life is Beautiful."
    
    iCnt = Len(sString)
    
    MsgBox "The length of a given string is : " & iCnt, vbInformation, "VBA Len Function"

End Sub

Output: Here is the screen shot of the second example output.
VBA Len Function

Example 3: Find Length of empty string:””

Here is a simple example of the VBA LEN function. This below example macro returns zero if it is empty string.

'Find Length of empty string:""
Sub VBA_Len_Function_Ex3()

    Dim sString As String, iCnt As Integer
    
    sString = ""
    
    iCnt = Len(sString)
    
    MsgBox "The length of a given string is : " & iCnt, vbInformation, "VBA Len Function"
End Sub

Output: Here is the screen shot of the third example output.
VBA Len Function

Example 4: Find Length of a string::”123$#@”

Here is a simple example of the VBA LEN function. This below example macro returns the length a given string (Includes special characters).

'Find Length of a string::"123$#@"
Sub VBA_Len_Function_Ex4()

    Dim sString As String, iCnt As Integer
    
    sString = "123$#@"
    
    iCnt = Len(sString)
    
    MsgBox "The length of a given string is : " & iCnt, vbInformation, "VBA Len Function"

End Sub

Output: Here is the screen shot of the fourth example output.
VBA Len Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Scanner Class in JavaVisual 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!

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