Vba excel посчитать количество символов в строке

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

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!

пуся

0 / 0 / 0

Регистрация: 17.01.2010

Сообщений: 14

1

Посчитать сколько символов содержится в строке

02.06.2010, 16:31. Показов 42726. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

дана строка символов.посчитать сколько символов содержится в ней.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
Private Sub CommandButton1_Click()
Dim stroka As Variant, k As Integer, char As Variant   'объявляем переменные
stroka = ?
k = 0       'переменная для подсчёта символов
For i = 1 To Len(stroka)    'цикл от 1 до длины нашего текста
char = Mid(stroka, i, 1)         'пусть char это i-ый символ нашей строки ...
If char <> " " Then k = k + 1  '...и если он не равен " " , то есть если он не пробел,увеличим счётчик
Next i           'и берём след. символ
    Ответ.Text = Слово ' присваиваем полю ввода "ответ" измененный текст
    кол.Text = Количество
End Sub

как правильно решить эту задачу??помогите пожалуйста!!



0



496 / 130 / 19

Регистрация: 30.03.2010

Сообщений: 224

02.06.2010, 16:39

2

Len(stroka) — это и есть количество символов в строке, так как, пробел тоже является символом
если же надо посчитать количество символов, не являющихся пробелом, то достаточно сделать k = Len(Replace(stroka,» «,»»)), то есть определить длину строки, в которой все пробелы удалены



2



0 / 0 / 0

Регистрация: 17.01.2010

Сообщений: 14

02.06.2010, 18:22

 [ТС]

4

пока не зачтут задачу так и буду их считать



0



3895 / 898 / 122

Регистрация: 16.04.2009

Сообщений: 1,824

02.06.2010, 20:26

5

пуся, а может Вам красную карточку за копии тем выдать?
Тогда придется считать в одиночку … «пока не зачтут»
Считайте что это было последнее китайское.



0



310 / 10 / 1

Регистрация: 09.10.2012

Сообщений: 52

11.01.2014, 18:37

6

Нужно посчитать пробелы в строке. На ум пришел вариант Len(stroka)-Len(Replace(stroka,chr(32),empty))
Минусы, не уверен что Replace быстро работает при обработке длинных строк. Но в тоже время циклить такую строку тоже не быстро.
Плюсы — значение получаем одной строкой без своих функций, циклов, и временных переменных.
Плюсов больше Ну а стандартной функции в VBA для счета нужного символа в строке я не нашел.



0



  • Remove From My Forums
  • Question

  •  Hi all,

    How can I count the number of characters in a string so it works as the example below? Len() works quit well but I would like it to stop on blanks.

    <some function> (me) »’ return 2

    <some function>(me_rest) »’ return 7

    <some function>(rest s) »’ return 4

     Thankful for help.

    Jonas

Answers

  • Hi,

    Couple of ways, use the Split function or Instr

        MsgBox Len(Split(«me»)(0)) »’ return 2
        MsgBox Len(Split(«me_rest»)(0)) »’ return 7
        MsgBox Len(Split(«rest s»)(0)) »’ return 4
       
        Dim strText As String
        Dim lngLen As Long
       
        strText = «rest s»
        lngLen = InStr(strText, » «) — 1
        If lngLen < 0 Then lngLen = Len(strText)
        MsgBox lngLen

  • Hi,

    you can use something like this:

    Function LenOfFirstWord(byval YourString As String) As Long
      Dim i As Long
      i = InStr(YourString, » «)
      If i > 0 Then
        LenOfFirstWord = i-1
      Else
        LenOfFirstWord = Len(YourString)
      End If
    End Function

    The above will return 0 for » hello world», so if you want leading spaces ignored use LTrim to remove them.


    SvenC

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

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