Excel vba длина string

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

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!

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!

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

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

The String data type represents text. A string is an array of characters. VBA strings use 16-bit Unicode characters. VBA has a built-in Strings module with functions for manipulating strings. Efficiency is an important topic when it comes to dealing with strings.

String Literals

String literals are used to represent strings in code. Text surrounded by double quotes represents a string literal in VBA.

Public Sub Example()

    Debug.Print "Hello, World!" 'Prints: Hello, World!

End Sub

To create a string literal that contains double quotes, use double double quotes.

Public Sub Example()

    Debug.Print "Hello, World!"       'Prints: Hello, World!

    Debug.Print """Hello, World!"""   'Prints: "Hello, World!"

    Debug.Print "Hello, ""World""!"   'Prints: Hello, "World"!

    Debug.Print """"                  'Prints: "

    Debug.Print """"""                'Prints: ""

End Sub

String Type Conversion

To explicitly convert a value to a string use the CStr function. The Str function can be used to convert a number to a string. The Str function only recognizes the period as a decimal place, so when working with international numbers where the decimal may be a comma, use the CStr function.

Public Sub Example()

    Dim S As String

    S = CStr(350)         ' -> "350"

    S = CStr(3.5)         ' -> "3.5"

    S = CStr(True)        ' -> "True"

    S = CStr(#1/1/2021#)  ' -> "1/1/2021"

    S = CStr(3.5@)        ' -> "3.5"

End Sub

String Concatenation

Both the & and + operators can be used to concatenate strings in VBA. Using the & operator will implicitly convert non-string values to strings. Using the + operator will not implicitly convert non-strings to strings. Trying to concatenate a string value with a non-string value using + will cause a type mismatch error. The CStr function can be used to explicitly convert non-string values to strings. There is no significant difference in speed between using & and +.

Public Sub Example()

    Debug.Print "Hello, " + "World!"

    'Debug.Print "Hello, " + 1 'Causes Error

    Debug.Print "Hello, " + Cstr(1)

End Sub

Public Sub Example()

    Debug.Print "Hello, " & "World!"

    Debug.Print "Hello, " & 1

    Debug.Print "Hello, " & Cstr(1) 'Not necessary to use CStr with &

End Sub

Variable-Length Strings

Variable-Length Strings can hold a large number of characters (2 ^ 31). The size of a Variable-Length String is determined by the number of characters in the String. The Len and LenB functions can be used to return the number of characters and bytes respectively in a String.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    Debug.Print S

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Fixed-Length Strings

Fixed-length strings are given a specific length at design-time when they are declared which cannot be altered at run-time. When a string is too long to fit in the fixed-length string it will be truncated. When a string is shorter than the fixed-length string the remaining space will be set to space characters (Chr 32). An uninitialized fixed-length string will be all null characters (Chr 0) for the length of the string. Fixed-Length strings can store from 1 to 65,535 characters. The Len and LenB functions can be used to get the length of a string in terms of characters and bytes respectively.

Public Sub Example()

    Dim S As String * 10

    S = "Hello, World!"
    Debug.Print """" & S & """" 'Prints: "Hello, Wor"

    S = "ABCD"
    Debug.Print """" & S & """" 'Prints: "ABCD      "

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Byte Arrays

Byte arrays and Strings are interchangeable. Byte Arrays can be assigned directly to Strings and Strings can be assigned directly to Byte Arrays.

Public Sub Example()

    Dim S As String
    S = "Hello, World!"

    Dim Arr() As Byte
    Arr = S

    Debug.Print Arr

End Sub

VBA Strings use two bytes to store each character so every two bytes in a byte array represents one character. Most common characters only require one byte to store and thus the second byte will be zero.

Public Sub Example()

    Dim Arr(0 To 9) As Byte
    Arr(0) = 72
    Arr(1) = 0
    Arr(2) = 101
    Arr(3) = 0
    Arr(4) = 108
    Arr(5) = 0
    Arr(6) = 108
    Arr(7) = 0
    Arr(8) = 111
    Arr(9) = 0

    Debug.Print Arr 'Prints: Hello

End Sub

String Comparison

Strings can be compared using comparison operators or the StrComp function.

Comparison Operators

Strings can be compared in VBA using comparison operators: =, >, <, >=, <=, <>, Like. Comparing strings using comparison operators will return True or False. The compare method used to compare strings when using comparison operators is determined by the Option Compare statement. The Option Compare statement can specify Binary or Text. Binary comparison compares the binary representations of each character. Because the binary representations of uppercase and lowercase characters differ, binary comparison is case-sensitive. Text comparison compares characters using the case-insensitive sort order determined by the system’s locale. In Microsoft Access, Database comparison can be used to compare strings based on the sort order given the locale ID of the database where strings are being compared. If no Option Compare statement is specified the default comparison method is Binary comparison.

Option Compare Binary

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: False
End Sub

Option Compare Text

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: True
End Sub

StrComp Function

The StrComp function can be used to compare two strings. The function takes two string arguments and an optional compare method argument (vbBinaryCompare, vbDatabaseCompare, or vbTextCompare). If no compare argument is specified then the Option Compare statement determines the compare method. The function can return 1, 0, -1, or Null depending on the result of the comparison. The StrComp function is the most explicit way to compare strings because the function can take the compare method as an explicit argument instead of relying on the Option Compare statement.

Syntax: StrComp(string1, string2, [compare])

Result Return Value
string1 < string2 -1
string1 = string2 0
string1 > string2 1
string1 = Null Or string2 = Null Null
Public Sub Example()

    Debug.Print StrComp("A", "a", vbTextCompare) = 0 'Prints: True

End Sub

Mid

The Mid function can be used to retrieve sections of a string, iterate over each individual character in a string, and to assign sections of a string without reallocating an entirely new string. Using Mid to alter strings is faster than allocating new strings.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    'Get slice of string
    Debug.Print Mid$(S, 1, 2)

    'Loop over each character
    Dim i As Long
    For i = 1 To Len(S)
        Debug.Print Mid$(S, i, 1)
    Next i

    'Reassign character
    Mid(S, 1, 1) = "A"
    Debug.Print S 'Prints: Aello, World!

End Sub

StrConv

The StrConv function can be used to convert a string’s case and encoding.

Constant Value Description
vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in a string to uppercase.
vbWide* 4 Converts narrow (single-byte) characters in a string to wide (double-byte) characters.
vbNarrow* 8 Converts wide (double-byte) characters in a string to narrow (single-byte) characters.
vbKatakana** 16 Converts Hiragana characters in a string to Katakana characters.
vbHiragana** 32 Converts Katakana characters in a string to Hiragana characters.
vbUnicode 64 Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)
vbFromUnicode 128 Converts the string from Unicode to the default code page of the system. (Not available on the Macintosh.)

*Applies to East Asia locales. **Applies to Japan only.

Public Sub Example()

    Debug.Print StrConv("hello, world!", vbProperCase) 'Prints: Hello, World!

End Sub

Public Sub Example()

    Dim Arr(0 To 4) As Byte
    Arr(0) = 72
    Arr(1) = 101
    Arr(2) = 108
    Arr(3) = 108
    Arr(4) = 111

    Debug.Print StrConv(Arr, vbUnicode) 'Prints: Hello

End Sub

LSet and Rset

LSet and RSet can be used to assign strings while aligning the text to the left or right of the string. LSet and RSet are used with fixed-length strings and strings that are already assigned so that they have a specific length. There is some performance improvement using LSet and RSet compared to normal string assignment. Any unassigned characters will be filled with space characters. If the string is longer than the string variable it will be truncated.

Public Sub Example()

    Dim S As String
    S = Space$(10)

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Public Sub Example()

    Dim S As String * 10

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Cleaning Text

Text may contain characters that need to be removed. Extra spaces, non-printable characters, non-breaking spaces, and new line characters are some examples of characters that may need to be removed from text.

Trimming Text

The Trim functions can be used to remove leading spaces, trailing spaces, or both from a string.

Public Sub Example()

    Dim S As String
    S = "   Hello, World!   "

    Debug.Print """" & LTrim$(S) & """" 'Prints: "Hello, World!   "

    Debug.Print """" & RTrim$(S) & """" 'Prints: "   Hello, World!"

    Debug.Print """" & Trim$(S) & """"  'Prints: "Hello, World!"

End Sub

The VBA Trim function does not remove extra consecutive spaces in the middle of a String. To accomplish this, use a user-defined function.

Public Function TrimAll(S As String) As String

    TrimAll = Trim$(S)

    Do While InStr(TrimAll, "  ") > 0
        TrimAll = Replace(TrimAll, "  ", " ")
    Loop

End Function

Remove Non-Printable Characters

Any character in the ASCII table with a value less than 32 is a non-printable character. Thus, to remove non-printable characters, remove all characters with an ASCII value less than 32.

Public Function RemoveNonPrintableCharacters(S As String) As String

    Dim OutString As String
    Dim CurrentCharacter As String * 1
    Dim i As Long
    Dim j As Long

    OutString = Space$(Len(S))

    For i = 1 To Len(S)

        CurrentCharacter = Mid$(S, i, 1)

        If Asc(CurrentCharacter) > 31 Then
            j = j + 1
            Mid$(OutString, j, 1) = CurrentCharacter
        End If

        RemoveNonPrintableCharacters = Left$(OutString, j)

    Next i

End Function

Non-Breaking Spaces

Non-breaking spaces can cause issues when processing text input. Non-breaking spaces appear the same as normal spaces when displayed but they are not the same character. Normal spaces have the value 32 in the ASCII table whereas non-breaking spaces have the value 160 in the ASCII table. It is often beneficial when working with text data to replace non-breaking spaces with normal spaces before doing any other processing on the text.

Public Function ReplaceNonBreakingSpaces(S As String) As String

    ReplaceNonBreakingSpaces = Replace(S, Chr(160), Chr(32))

End Function

New Line Characters

New line characters can cause issues with processing text input. It is common when processing text input to replace new line characters with a space character. Depending on the source of the text there could be different new line characters which must be handled in a particular order.

Public Function ReplaceNewLineCharacters( _
S As String, Optional Replacement As String = " ") As String

    ReplaceNewLineCharacters = _
        Replace(S, vbCrLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbCr, Replacement)

End Function

Formatting Functions

VBA provides useful built-in functions for formatting text.

Format function

The Format/Format$ function is used to format dates, numbers, and strings according to a user-defined or predefined format. Use the $ version of the function to explicitly return a String instead of a Variant/String.

Public Sub Example()

    '''Dates
    Debug.Print Format$(Now, "mm/dd/yyyy")
    Debug.Print Format$(Now, "Short Date")
    Debug.Print Format$(Now, "mmmm d, yyyy")
    Debug.Print Format$(Now, "Long Date")
    Debug.Print Format$(Now, "Long Time")

    '''Numbers
    Debug.Print Format$(2147483647, "#,##0")
    Debug.Print Format$(2147483647, "Standard")
    Debug.Print Format$(2147483647, "Scientific")

    '''Strings
    'Fill from right to left
    Debug.Print Format$("ABCD", "'@@_@@_@@'")

    'Fill from left to right
    Debug.Print Format$("ABCD", "!'@@_@@_@@'")

    'Lower case
    Debug.Print Format$("ABCD", "<'@@_@@_@@'")

    'Upper case
    Debug.Print Format$("ABCD", ">'@@_@@_@@'")

    'No spaces for missing characters
    Debug.Print Format$("ABCD", "'&&_&&_&&'")

    'Escape double quotes
    Debug.Print Format$("ABCD", "!""@@_@@_@@""")

End Sub

Number Formats

To retrieve a string representing a number in a specific format use one of the number format functions.

Function Description
FormatCurrency Returns a formatted currency as a string using the currency symbol defined in the system control panel.
FormatDateTime Returns a formatted date as string.
FormatNumber Returns a formatted number as a string.
FormatPercent Returns a formatted percentage as a string.

Character Constants

Character Constants are constants used to represent certain special characters. Character constants are defined in the built-in VBA.Constants module.

VBA Constant Character Code Description
vbCr 13 Carriage Return
vbLf 10 Line Feed
vbCrLf 13 + 10 Carriage Return + Line Feed
vbNewLine vbCrLf on Windows or vbLf on Mac New Line Character for current platform
vbNullChar 0 Null Character
vbNullString N/A String pointer to null. vbNullString is equal to an empty string («») when compared but they are different. vbNullString takes less memory because it is only a pointer to null. An empty string is a string with its own location allocated in memory. vbNullString is clearer in meaning than an empty string and should generally be preferred. However, vbNullString cannot be passed to DLLs. Empty strings must be passed to DLLs instead.
vbTab 9 Tab Character
vbBack 8 Backspace Character
vbFormFeed 12 Not useful on Windows or Mac.
vbVerticalTab 11 Not useful on Windows or Mac.

Built-in Strings Module Functions

Member Description
Asc Returns the character code of the first letter in a string.
AscB Returns the first byte of a string.
AscW Returns the Unicode character code when Unicode is supported. If Unicode is not supported it works the same as Asc. *Do not use on Mac. **AscW only Works properly up to 32767 and then returns negative numbers. This problem occurs because Unicode characters are represented by unsigned 16-bit integers and VBA uses signed 16-bit integers. See the wrapper functions below to correct for this problem.
Chr Returns a character given a character code. Returns a Variant/String.
Chr$ Returns a character given a character code. Returns a String.
ChrB Returns a single-byte string representing a character given a character code. Returns a Variant/String. *Try StrConv(ChrB(65),vbUnicode)
ChrB$ Returns a single-byte string representing a character given a character code. Returns a String. *Try StrConv(ChrB$(65),vbUnicode).
ChrW Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr. Returns Variant/String. *Do not use ChrW on a Mac.
ChrW$ Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr$. Returns String. *Do not use ChrW$ on a Mac.
Filter Returns an array containing a filtered subset of a string array.
Format Returns a string formatted by a given a format expression. Returns Variant/String.
Format$ Returns a string formatted by a given a format expression. Returns String.
FormatCurrency Returns a string formatted as a currency. Uses the currency symbol defined in the system control panel.
FormatDateTime Returns a string formatted as a date or time.
FormatNumber Returns a string formatted as a number.
FormatPercent Returns a string formatted as a percentage.
InStr Returns the position of the first occurrence of one string within another string.
InStrB Returns the byte position of the first occurrence of one string within another string.
InStrRev Returns the position of an occurrence of one string within another string starting from the end of the string and searching toward the start of the string.
Join Returns a string containing the elements of an array joined together by a delimiter.
LCase Returns a string converted to lowercase. Returns Variant/String.
LCase$ Returns a string converted to lowercase. Returns String.
Left Returns a substring of a given length from the left side of a string. Returns Variant/String.
Left$ Returns a substring of a given length from the left side of a string. Returns String.
LeftB Returns a substring of a given length in bytes from the left side of a string. Returns Variant/String.
LeftB$ Returns a substring of a given length in bytes from the left side of a string. Returns String.
Len Returns the number of characters in a string or the number of bytes required to store a variable.
LenB Returns the number of bytes in a string or the number of bytes required to store a variable.
LTrim Returns a string without leading spaces. Returns Variant/String.
LTrim$ Returns a string without leading spaces. Returns String.
Mid Returns a substring of a given length. Returns Variant/String. Can be used to alter sections of a string.
Mid$ Returns a substring of a given length. Returns String. Can be used to alter sections of a string.
MidB Returns a substring of a given length in bytes. Returns Variant/String. Can be used to alter sections of a string.
MidB$ Returns a substring of a given length in bytes. Returns String. Can be used to alter sections of a string.
MonthName Returns a string representing a given month.
Replace Returns a string with a given substring replaced by another string. Returns String.
Right Returns a substring of a given length from the right side of a string. Returns Variant/String.
Right$ Returns a substring of a given length from the right side of a string. Returns String.
RightB Returns a substring of a given length in bytes from the right side of a string. Returns Variant/String.
RightB$ Returns a substring of a given length in bytes from the right side of a string. Returns String.
RTrim Returns a string without trailing spaces. Returns Variant/String.
RTrim$ Returns a string without trailing spaces. Returns String.
Space Returns a given number of spaces. Returns Variant/String.
Space$ Returns a given number of spaces. Returns String.
Split Returns a string array by splitting up a string on a delimiter.
StrComp Returns the result of a string comparison.
StrConv Returns a string converted according to a given option.
String Returns a string repeated for a given number of times. Returns Variant/String.
String$ Returns a string repeated for a given number of times. Returns String.
StrReverse Returns a reversed string.
Trim Returns a string without leading or trailing spaces. Returns Variant/String.
Trim$ Returns a string without leading or trailing spaces. Returns String.
UCase Returns a string converted to uppercase. Returns Variant/String.
UCase$ Returns a string converted to uppercase. Returns String.
WeekdayName Returns a string representing a given day of the week.
Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char)

    If AscW2 < 0 Then
        AscW2 = AscW2 + 65536
    End If

End Function

Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char) And &HFFFF&

End Function

Types of String Functions

The behaviors of several string functions in VBA can be altered by affixing a $, B, W, or some combination of the three to the end of the function name.

$ Functions

$ String functions explicitly return a String instead of a Variant/String. The String type uses less memory than the Variant/String type.

B Functions

B (Byte) String functions deal with bytes instead of characters.

W Functions

W (Wide) functions are expanded to include Unicode characters if the system supports Unicode.

String Classes

Using custom string classes can facilitate working with strings and make working with strings more efficient. the StringBuilder and ArrayList classes have high-level functionality and are designed to mitigate the inefficiencies of with working with strings.

StringBuilder

The StringBuilder class represents a single string that can be manipulated and mutated. The StringBuilder class improves efficiency by avoiding frequent reallocation of memory. The StringBuilder class has a number of high-level properties and methods that facilitate working with strings. Download and import the clsStringBuilder class into a VBA project.

Public Sub Example()

    '''Must import clsStringBuilder to VBA project

    Dim SB As clsStringBuilder
    Set SB = New clsStringBuilder

    SB.Append "ABC"
    SB.Append "123"

    SB.Insert 3, "XYZ"

    Debug.Print SB.Substring(3, 5)

    SB.Remove 3, 5

    Debug.Print SB.ToString

End Sub

ArrayList

The ArrayList class represents a list which can be manipulated and mutated. The ArrayList class improves efficiency by avoiding frequent reallocation of memory. The ArrayList class has a number of high-level properties and methods that facilitate working with a list of strings. Download and import the clsArrayListString class into a VBA project.

Public Sub Example()

    '''Must import clsArrayListString to VBA project

    Dim AL As clsArrayListString
    Set AL = New clsArrayListString

    'Build message
    AL.Append "Hello"
    AL.Append "How are you?"
    AL.Append "I'm great! Thank you."
    Debug.Print AL.JoinString(vbNewLine)

    AL.Reinitialize

    'Sort strings
    AL.Append "C"
    AL.Append "B"
    AL.Append "A"
    Debug.Print AL.JoinString
    AL.Sort
    Debug.Print AL.JoinString

End Sub

Понравилась статья? Поделить с друзьями:
  • Excel vba диапазон ячеек в переменную
  • Excel vba диапазон непустых ячеек
  • Excel vba диапазон как таблица
  • Excel vba диапазон весь столбец
  • Excel vba диапазон весь лист