Vba excel сколько символов в ячейке

Помогаю со студенческими работами здесь

Как подсчитать сумму в итоговой ячейке по определенному значению если в ячейке есть буквы и цыфры
Добрый день, всем.
Помогите пожалуйста, как можно посчитать сумму в итоговой ячейке по…

Можно ли как-то изменить в настройках максимальное количество выводимых цифр (значения числа) в ячейке
То количество цифр которое фактически получается у значения числа равного от (171!) и более.
А то…

Как подсчитать количество измененных символов?
Условие задачи такое: заменить все большие буквы на маленькие и подсчитать количество замен. Каким…

Как подсчитать количество символов в файле???
Как подсчитать количество символов в файле, а потом вывести на экран определенное количество…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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!

 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

Всем доброго дня! Подскажите пожалуйста способ подсчёта с помощью макроса количества символов «U»  в каждой ячейке, разделители (например запятая, пробел или какие-то ещё) могут быть, а могут и отсутствовать. Буду очень благодарен если подскажете не готовое решение, а только нужную команду VBA  с её синтаксисом (желательно подробно, как для совсем новичка) — остальное постараюсь сам сделать. В прилагаемом примере, по-моему, всё подробно описано.

 

V

Пользователь

Сообщений: 5018
Регистрация: 22.12.2012

#2

25.02.2014 10:05:24

формулой выглядело бы так  ;)

Код
=СУММПРОИЗВ(ДЛСТР(D2:D5)-ДЛСТР(ПОДСТАВИТЬ(D2:D5;"U";""))) 
 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

Спасибо за формулу, попробую и с ней реализовать нужное мне, но всё же лучше макрос.

 

V

Пользователь

Сообщений: 5018
Регистрация: 22.12.2012

#4

25.02.2014 10:15:20

для одной ячейки

Код
UBound(Split(ActiveCell, "U")) 
 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

#5

25.02.2014 10:18:25

словами:
заменить U на пусто и посчитать разницу в   длине строки до и после замены

на vba:

Код
Dim n&, x
For Each x In [d2:d5].Value
 n = n + Len(x) - Len(Replace(x, "U", "")
Next x
[d7] = n

Живи и дай жить..

 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

Вот! То что нужно, только не могли бы Вы подробнее написать как работают эти команды (Split), а лучше как это работает в совокупности?
Если у Вас нет времени, то всё равно спасибо — Вы очень мне помогли!

 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

Слэн, спасибо! Если возможно объясните подробнее как работает строка (n = n + Len(x) — Len(Replace(x, «U», «») ) — я в ней не всё понимаю.

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

я же «словами» написал..

идете циклом for each x in по массиву [d2:d5].value

каждый раз меняете в x все U на пустые значения

сравниваете длину len(x) до и len(replace) после замены и накапливаете ее в n

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

spit тоже можно, но мне кажется медленнее работает, впрочем, мерять надо

 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

Всё, Слэн! Спасибо! Мне было непонятно что такое len(replace) — разъяснили. Будем считать закрытой эту тему. Огромное спасибо всем участникам!

 

V

Пользователь

Сообщений: 5018
Регистрация: 22.12.2012

Split делит текст в ячейке на части используя указанный разделитель. т.е. U159U158 делится на 3 части и получается до первой U часть (маркеруется 0), между первой и второй (1), после второй (2).
UBound — выводит последнее значение т.е. 2

 

Ivann

Пользователь

Сообщений: 6
Регистрация: 25.02.2014

#12

25.02.2014 10:43:09

V, Спасибо! Всё теперь мне понятно!

VBA length of String

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:

Syntax of VBA Length of string

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.

VBA length of string Example 1.1

Step 2: Open a Module from the Insert menu option as shown below.

VBA length of string - module

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 1.2

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

VBA length of String Example 2.1

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

VBA length of String Example 2.2

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

VBA length of String Example 2.3

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

Example 2.4

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 String of Length 1

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

 Example 3.1

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

Example 3.2

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

Example 3.3

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.

VBA String of length

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 –

  1. VBA Workbook
  2. VBA String Array
  3. VBA String Comparison
  4. VBA RGB

Let’s say I have this variable:

word = «habit»

which command in VBA will allow me to count how many characters are there in this variable (in my case it’s 5).

Important: the variable «word» contains only one word, no spaces, but may have contain numbers and hyphens.

asked Nov 12, 2009 at 20:19

brilliant's user avatar

4

Do you mean counting the number of characters in a string? That’s very simple

Dim strWord As String
Dim lngNumberOfCharacters as Long

strWord = "habit"
lngNumberOfCharacters = Len(strWord)
Debug.Print lngNumberOfCharacters

answered Nov 12, 2009 at 20:23

Ben McCormack's user avatar

Ben McCormackBen McCormack

31.8k46 gold badges145 silver badges221 bronze badges

Len(word)

Although that’s not what your question title asks =)

answered Nov 12, 2009 at 20:22

David Hedlund's user avatar

David HedlundDavid Hedlund

128k31 gold badges201 silver badges221 bronze badges

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

answered Jun 26, 2015 at 14:40

user5053510's user avatar

3

Len is what you want.

word = "habit"  
length = Len(word)

answered Nov 12, 2009 at 20:22

Austin Salonen's user avatar

Austin SalonenAustin Salonen

48.8k15 gold badges108 silver badges139 bronze badges

Use the Len function

length = Len(myString)

answered Nov 12, 2009 at 20:22

Robert Harvey's user avatar

Robert HarveyRobert Harvey

177k47 gold badges333 silver badges499 bronze badges

  • Что такое длина строки VBA?

Что такое длина строки VBA?

VBA Len является важным инструментом для проверки данных. Функция VBA LEN Возвращает количество символов в предоставленной строке, т.е. для измерения длины текста или количества символов в тексте. VBA LEN относится к категории String. Его можно использовать как процедуру или функцию в окне редактора VBA. Он часто используется как вспомогательная функция наряду с другими строковыми функциями, такими как MID, RIGHT, т. Е. Для извлечения частей имени из полного имени.

Синтаксис VBA Длина строки в Excel

Синтаксис функции VBA Length of String в Excel выглядит следующим образом:

После ввода LEN нажмите на пробел, появится вышеупомянутый синтаксис, где он содержит нижеупомянутый аргумент.

  • Строка: это выражение или текстовая строка или имя переменной, из которой вы хотите вернуть длину.

т.е. Len («Длина») = вернуть значение 6, потому что длина текста «Длина» равна 6. Если вы берете переменную в качестве Variant вместо long, то она считается такой же, как строка. то есть функции Len обрабатывают переменную варианта как String.

Как использовать длину строки функции в Excel VBA?

Ниже приведены различные примеры использования длины строки в Excel с использованием кода VBA.

Вы можете скачать этот шаблон VBA Длина строки Excel здесь — VBA Длина шаблона Excel строки

Длина строки VBA — Пример № 1

Выполните следующие шаги, чтобы использовать функцию длины строки в Excel VBA.

Шаг 1. Перейдите на вкладку « Разработчики » и нажмите на Visual Basic .

Шаг 2: Откройте модуль из меню «Вставка», как показано ниже.

Шаг 3: Под объектами Microsoft Excel щелкните правой кнопкой мыши лист 1 ( VB_LEN ) Вставьте и в разделе меню выберите Модуль, чтобы создать новый пустой модуль.

Длина строки VBA — Пример № 2

Предположим, у меня есть слово «NULL », и я хочу узнать количество символов в этой текстовой строке, т. Е. Для этого, с помощью макро-кода функции VB LEN, я могу это выяснить.

Шаг 1: В редакторе VBA после ввода Sub у меня есть имя LENGTH ()

 Sub LENGTH () End Sub 

Шаг 2: Поскольку функция VBA LEN категоризирована по строковому типу, DIM (измерение) используется в коде VBA для объявления имени переменной, ее типа. В VBA вы должны всегда изначально объявлять, что вы настраиваете переменную. Это делается (в основном) словом Dim.

DIM используется для объявления переменной и выделения памяти для переменной.

Синтаксис: Dim ( вставить имя переменной ) как ( вставить тип переменной )

Код:

 Sub LENGTH () Dim L As Variant End Sub 

Шаг 3: После объявления переменной присвойте значение этой переменной с помощью функции LEN.

Код:

 Sub LENGTH () Dim L As Variant L = Len (Конец Sub 

Шаг 4: После ввода LEN и нажатия на пробел, и как только вы вводите открытую скобку, ниже приведенный синтаксис появляется для правильной функции.

Строка: это выражение или текстовая строка или имя переменной, из которой вы хотите вернуть длину, т.е. «ДЛИНА»

Код:

 Sub LENGTH () Dim L As Variant L = Len ("LENGTH") MsgBox L End Sub 

Как только вы закончили вводить аргументы функции LEN . Теперь я хочу отобразить этот результат функции len в окне сообщения. затем в следующей строке кода, давайте нажмем Ctrl + Пробел, набираем MsgBox, после этого вы можете упомянуть имя переменной.

Шаг 5: Теперь код готов, вы можете запустить его, нажав клавишу F5. Как только вы это сделаете, появится всплывающее сообщение с результатом «6», которое указывает количество символов в предоставленной строке или тексте (длина)

Длина строки VBA — Пример № 3

Теперь вместо вывода, отображаемого в окне сообщения, я хочу, чтобы результаты или выходные данные отображались на листе. На листе у меня есть данные, т.е. штат США в ячейке «A4», теперь я хочу узнать количество символов в текстовой строке состояния, здесь я могу использовать функцию Len с небольшим изменением в коде.

Шаг 1: После объявления переменной мне нужно снова ввести имя переменной и адрес ячейки полнотекстовой строки с помощью функции Range или cell.

Код:

 Sub TEXT_LENGTH () Dim L As Variant L = Range ("A4") End Sub 

Шаг 2: Теперь мне снова нужно ввести имя переменной, применить функцию LEN и ввести ее аргументы.

Код:

 Sub TEXT_LENGTH () Dim L As Variant L = диапазон ("A4") L = Len ("Массачусетс") End Sub 

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

Шаг 3: Теперь давайте применим функцию диапазона, сначала мне нужно ввести функцию диапазона или ячейки, а затем ввести имя переменной, чтобы в этой конкретной ячейке («B4») появился результат.

Код:

 Sub TEXT_LENGTH () Dim L As Variant L = Диапазон ("A4") L = Диапазон Len ("Массачусетс") ("B4"). Значение = L End Sub 

Шаг 4: Теперь код готов, я могу запустить его, нажав клавишу F5. как только я это сделаю, вы можете наблюдать выходное значение функции LEN, появляющееся в ячейке «B4», т.е. 13, которое указывает количество символов в предоставленной строке или тексте.

То, что нужно запомнить

  • Помимо функции LEN, LenB используется для вычисления или определения фактического количества требуемых байтов для предоставленной переменной в памяти.
  • Переменная объекта не должна использоваться в функции Len.

Рекомендуемые статьи

Это руководство по длине строки функции VBA. Здесь мы обсудим, как использовать функцию длины строки VBA в Excel вместе с некоторыми практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Полное руководство по VBA Workbook
  2. НЕПРАВИЛЬНАЯ функция в Excel
  3. Функция подсчета VBA
  4. Функция Excel XOR

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