Что такое string vba excel

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

The string is a data type that holds a sequence of characters like the alphabet, special characters, and numbers. In VBA we can manipulate strings in such a way, that we can do concatenation, we can also reverse a string, and also add or remove any string in a string. In this article, we will learn about excel VBA strings. 

Declaration of String

Strings are a combination of characters. Strings can be declared in the same way as integers or characters are declared in VBA. For example, Dim str As String, here str is a variable with the string data type

declaration of string in vba

Assigning String value

String value should be surrounded with double quotes whenever it will be assigned to a string variable. For example, str = “I am Ayush”, here “I am Ayush”, is assigned in the double quotes. 

assigning string value in vba

Concatenation

Concatenation means the joining of two strings, into one string, using the “&” operator. For example, str = “Ayu”, str1 = “sh”, can be concatenated/joined into one string, str2 by str & str1. The final output of str2 is “Ayush”

concat two strings in vba

String Manipulation

String manipulation is a concept that provides us with different in-built functions which help to manipulate the string. There are fifteen-plus functions in string manipulation, but here we will discuss some of the most commonly used string manipulation functions. For example, like LCase, UCase, Replace, and StrReverse. 

LCase()

The LCase() function, returns the string after converting it into lowercase. The function takes one mandatory argument i.e. input_string. 

Syntax of the function: LCase(input_string)

For example, “AYUSH” string has to be converted, into a lowercase string. Use LCase(“AYUSH”), and update the returned value of the function, with the original string i.e. str. The final output will be “ayush”

lowercase in string in vba lcase() function

UCase()

The UCase() function, returns the string after converting it into uppercase. The function takes one mandatory argument i.e. input_string.

Syntax of the function: UCase(input_string)

For example, “ayush” string has to be converted, into an uppercase string. Use UCase(“ayush”), and update the returned value of the function, with the original string i.e. str. The final output will be “ayush”

uppercase function in vba strings

Replace()

The Replace() function, replaces a part of the string with another string. The function takes three mandatory arguments i.e. input_string, string2, string3.

Syntax of the function: Replace(input_string, string2, string3)

input_string: It is the first argument of the replace() function. It takes the required string on which you want to apply the replacement. 

string2: It is the second argument of the replace() function. It is the string, which will be replaced in input_string. This string should be a sub-string of input_string. 

string3: It is the third argument of the replace() function. It is the new string, which will be replaced in place of string2. 

For example, consider a string “Codimh”, the “mh” substring can be replaced with “ng”, in the given input string. Use, Replace(“Codimh”, “mh”, “ng”), function, to replace old string with the new string. The final output of str is Coding.  

replace function in vba strings

StrReverse()

The StrReverse() function, returns the reverse of a string. The function takes one mandatory argument i.e. input_string.

Syntax of the function: StrReverse(input_string)

For example, consider a string “Coding”, the given string can be reversed using StrReverse(“Coding”). The returned value of the given function is updated to the string str. The final output of the str is “gnidoC”

strreverse function in vba strings

Substring Functions

There are 3 different types of substring functions, these functions return a substring in a string. 

Left()

The Left() function, returns the substring from the left side of the string. The function takes two mandatory arguments i.e. input_string and number. 

Syntax of the function: Left(input_string, number)

input_string: It is the first argument of the Left() function. It is the input string, for which the left substring has to be returned. 

number: It is the second argument of the Left() function. It tells the number of characters to be returned from the left start of the string. 

For example, consider a string “Coding”, a left substring of length two can be returned using Left(“Coding”, 2). The final output of the str is “Co”.

returns left string in vba string

Right()

The Right() function, returns the substring from the right side of the string. The function takes two mandatory arguments i.e. input_string and number.

Syntax of the function: Right(input_string, number)

input_string: It is the first argument of the Right() function. It is the input string, for which the right substring has to be returned. 

number: It is the second argument of the Right() function. It tells the number of characters to be returned from the right start of the string. 

For example, consider a string “Coding”, a right substring of length two can be returned using Right(“Coding”, 2). The final output of the str is “ng”.

returns right substring in excel vba

Mid()

The Mid() function, returns a substring of any size a user wants. The function takes three mandatory arguments i.e. input_string, number1, and number2.

Syntax of the function: Mid(input_string, number1, number2)

input_string: It is the first argument of the Mid() function. It is the input string, for which the substring has to be returned. 

number1: It is the second argument of the Mid() function. It tells the starting index of the substring. 

number2: It is the third argument of the Mid() function. It tells the number of characters of the substring. 

For example, consider a string “Coding”, and we need to return a substring “odi”. This can be achieved using the Mid(“Coding”, 2, 3) function. 

Note: 1-based indexing of string has been considered in the Mid() function. 

returns mid string in excel vba

Length and Position

Len() 

The Len() function, returns the length of the string. The function takes one mandatory argument i.e. input_string. 

Syntax of the function: Len(input_string)

input_string: It is the first argument of the Len() function. It is the input string, for which the length has to be returned.

For example, consider a string “Coding”, the length of the string can be achieved by using Len(“Coding”). The final output of the program is 6

return length of string in vba excel

InStr()

The InStr() function, returns the first position of a substring in the string. The function takes three mandatory arguments i.e. number1, input_string, and string. 

Syntax of the function: InStr(number1, input_string, string)

number1: It is the first argument of the InStr() function. This number tells the position of the start of the search in the input_string. 

input_string: It is the second argument of the InStr() function. It is the input string, in which the search has to be made. 

string: It is the third argument of the InStr() function. It is the string that has to be searched in the input_string. 

For example, consider a string “Coding”, the start of the search is from index 1 i.e. character ‘C’, and the substring to be searched is “o”. This could be achieved using InStr(1, “Coding”, “o”). The final output of the program is 2

search substring in a string in excel vba

VBA String

Excel VBA String Function

Excel VBA String Function is the most basic function used in VBA. As for numbers, we have an integer function in excel, so for characters and text, we can use VBA String. We can perform and use VBA Strings in many ways. With the help of function VBA String, we can calculate the length of text, combine 2 different words or sentences, and print the text message in a message box.

The formula for String Function in Excel VBA

VBA String has the following syntax:

Syntax of String Function

As we can see in the syntax, it uses Number as Long, which has no limit and the characters such as alphabets and words.

How to Use Excel VBA String Function?

We will learn how to use a VBA String function with few examples in excel.

You can download this VBA String Excel Template here – VBA String Excel Template

VBA String Function – Example #1

First, we will see the simple example where we will apply and use a string function.

Follow the below steps to use the String function in VBA.

Step 1: Go to VBA, and from the Insert menu tab, open a new module as shown below.

VBA String Example 1-1

Once we do that, we get the new Module window.

Step 2: Now start writing Sub-category in the performed function or any other name.

Code:

Sub VBA_String1()

End Sub

VBA String Example 1-2

Step 3: Now define a dimension “Dim A as String”. This will allow us to use character or text in our next command line.

Code:

Sub VBA_String1()

Dim A As String

End Sub

VBA String Example 1-3

Step 4: Now, we can store any text or character or sentence in defined string A. Let’s consider the sentence “How are you doing?” as shown below.

Code:

Sub VBA_String1()

Dim A As String

A = "How are you doing?"

End Sub

VBA String Example 1-4

Step 5: Now, to see this text somewhere, we need to print it in a message box. For this, we will use the MsgBox function as shown below.

Code:

Sub VBA_String1()

Dim A As String

A = "How are you doing?"

MsgBox A

End Sub

VBA String Example 1-5

Step 6: Now, compile and run the code. We will get a message box saying “How are you doing?” in the excel window.

Result of Example 1

This is how we can use text or character by using the String function of VBA.

VBA String Function – Example #2

Now in this example, we will see and print a part of the text with the help of the String function in VBA.

Follow the below steps to use the String function in VBA.

Step 1: Write Subcategory in any name or in performed function’s name as shown below.

Code:

Sub VBA_String2()

End Sub

Example 2-1

Step 2: Now define a dimension “DIM” A or any other character as STRING as shown below.

Code:

Sub VBA_String2()

Dim A As String

End Sub

VBA String Example 2-2

Step 3: In defined dimension A store some value of character or text. Let’s store a text as “Sample Text”, as shown below.

Code:

Sub VBA_String2()

Dim A As String

A = "Sample Text"

End Sub

VBA String Example 2-3

Step 4: Again, to see the value stored in defined dimension A as String, we will use the message box. To print a message, consider the MsgBox command; as we have discussed, to get a portion of the text, so use LEFT with the number of characters you want. Let’s say 3. This we print the First 3 letters from the left into the message box.

Code:

Sub VBA_String2()

Dim A As String

A = "Sample Text"

MsgBox Left("Sample Text", 3)

End Sub

VBA String Example 2-4

Step 5: Now, compile and run the complete code.

Result of Example 3

We will get a message box with the message “Sam”, as shown below. As we have selected LEFT with 3 character limit for the message box, so I have printed the message Sam which is the first 3 letters of “Sample Text”.

In the same way, we can use the RIGHT, MID function to get the character from different sides as we did for the LEFT side.

VBA String Function – Example #3

In this example, we will see how the String function is used to calculate the length of defined and stored characters. This is also as easy as printing a message in the message box.

Follow the below steps to use the String function in VBA.

Step 1: Writing Sub-category in the name of the performed function as shown below.

Code:

Sub VBA_String3()

End Sub

Example 3-1

Step 2: Now define dimension A as String. Here we can use anything in place of “A”. The string will store the values given for A as a character.

Code:

Sub VBA_String3()

Dim A As String

End Sub

VBA String Example 3-2

Step 3: Now, to calculate the length of characters store in dimension A, use the LEN function as shown below. We will assign the defined dimension.

Code:

Sub VBA_String3()

Dim A As String

A = Len (

End Sub

VBA String Example 3-3

Step 4: Let’s say that character or text in “Sample Text” same as we used in example-2. And remember to quote this text in inverted commas, as shown below.

Code:

Sub VBA_String3()

Dim A As String

A = Len("Sample Text")

End Sub

VBA String Example 3-4

Step 5: At last, for printing the message stored in dimension A, we will use the MsgBox command, which will print the complete message and length of character stored in dimension A String.

Code:

Sub VBA_String3()

Dim A As String

A = Len("Sample Text")

MsgBox A

End Sub

VBA String Example 3-5

Step 6: Once done, compile and run the code.

Result of Example 3

We will get the length of characters store in A string as 11, which includes space as well.

VBA String Function – Example #4

In this example, we will see how to use 2 different strings in one message box. For this, we need to define 2 separate dimensions as String, and we will be using one single message box to print the text stored in both the dimensions.

Follow the below steps to use the String function in VBA.

Step 1: Write a sub-category in the name of the defined function as shown below.

Code:

Sub VBA_String4()

End Sub

Example 4-1

Step 2: Now define dimension “DIM” A and B as String in 2 separated line of code. For each dimension we define, we need to use a separate new line for it, as shown below.

Code:

Sub VBA_String4()

Dim A As String
Dim B As String

End Sub

VBA String Example 4-2

Step 3: Now store any character of values as text in both defined strings. Here we are using “First Name ” and “Last Name” just for text sample. As we can see in the below screenshot, we have given space after “First Name “ so that both strings should not get overlapped when we see these in the message box.

Code:

Sub VBA_String4()

Dim A As String
Dim B As String

A = "First Name "
B = "Last Name"

End Sub

VBA String Example 4-3

We can use anything or any value stored in A and B, and in fact, we can see any alphabets or words for defining a string.

Step 4: Now, to see the values stored in A and B, we will use MsgBox command and use “&” between A and B so that we would see both the values together in the same message box as shown below.

Code:

Sub VBA_String4()

Dim A As String
Dim B As String

A = "First Name "
B = "Last Name"

MsgBox (A & B)

End Sub

VBA String Example 4-4

Step 5: Once done, compile and run the code.

Result of Example 4

We will get a message box having “First Name” and “Last Name” together in the same box separated by a space.

Benefits of Excel VBA String Function

  • This is the easiest and basic function of VBA, where we can use any length of character and text.
  • A string can be used to print the text and characters in many different forms, as we have seen in the above examples.

Things to Remember

  • Always use inverted commas to quote the message while assigning it to any string.
  • Remember to save the file in Macro-Enabled Excel to avoid losing written code.

Recommended Articles

This has been a guide to VBA String Function. Here we discussed VBA String and how to use Excel VBA String Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Match
  2. VBA RGB
  3. VBA Number Format
  4. VBA XML

Функции Space, String и StrReverse, предназначенные в VBA Excel для создания строк из повторяющихся символов и смены порядка следования знаков.

Space – это функция, которая возвращает строку из указанного числа пробелов.

Синтаксис

Space (число)

  • число – параметр, задающий количество добавляемых пробелов.

Пример

Sub Primer1()

MsgBox «Десять» & Space(10) & «пробелов»

End Sub

Демонстрация работы функции Space

Функция String

String – это функция, которая возвращает строку из указанного числа символов, в том числе управляющих (табуляция, перевод строки, возврат каретки).

Синтаксис

String (число, символ)

  • число – параметр, задающий количество добавляемых символов;
  • символ – числовой код символа (0-255) или строка, из которой извлекается первый символ.

Соответствие символов числовым кодам смотрите на сайте разработчика: кодировка (0–127) и кодировка (128–255).

Пример

Sub Primer2()

MsgBox _

String(16, «кит») & vbLf & vbLf & _

String(10, 38) & String(2, 10) & _

String(14, 100)

End Sub

Демонстрация работы функции String

Обратите внимание, что запись String(2, 10) аналогична записи vbLf & vbLf.

Функция StrReverse

StrReverse – это функция, которая возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой.

Синтаксис

StrReverse (expression)

  • expression – выражение, возвращающее строку, у которой необходимо изменить порядок следования знаков.

Пример

Sub Primer3()

MsgBox _

«Было:  « & «кружок» & vbLf & vbLf & _

«Стало:  « & StrReverse(«кружок»)

End Sub

Демонстрация работы функции StrReverse

In this Article

  • String Variable Type
    • Fixed String Variable
  • Declare String Variable at Module or Global Level
    • Module Level
    • Global Level
  • Convert Values stored as String
  • Convert String Stored as Values

String Variable Type

The String data type is one of the most common data types in VBA. It stores “strings” of text.

To declare an variable String variable, you use the Dim Statement (short for Dimension):

Dim strName as String

To assign a value to a variable, you use the equal sign:

strName = "Fred Smith"

Putting this in a procedure looks like this:

Sub strExample()
'declare the string
   Dim strName as string
'populate the string
    strName = "Fred Smith"
'show the message box
   MsgBox strname
End Sub

If you run the code above, the following message box will be shown.

vba string declare

Fixed String Variable

There are actually 2 types of string variables – fixed and variable.

The “variable” string variable (shown in the previous example) allows your string to be any length. This is most common.

The “fixed” string variable defines the size of the string. A fixed string can hold up to 65,400 characters.

Dim strName as string *20

When you define a fixed variable, the number of characters in the variable is locked in place, even if you use fewer characters.

Notice the spaces in the graphic below – the variable has place holders for the rest of the characters in the string as ‘Fred Smith’ is less than 20 characters.

vba string variable size

However, if you have declared a string without specifying the length, then the string will only hold as many characters as are passed to it.

vba string fixed size

Declare String Variable at Module or Global Level

In the previous example, you declared the String variable within a procedure. Variables declared with a procedure can only be used within that procedure.

vba string procedure declare

Instead, you can declare String variables at the module or global level.

Module Level

Module level variables are declared at the top of code modules with the Dim statement.

vba string module declare

These variables can be used with any procedure in that code module.

Global Level

Global level variables are also declared at the top of code modules. However, instead of using the Dim statement, you use the Public statement to indicate that the string variable is available to be used throughout your VBA Project.

Public strName as String

vba string global declare

If  you declared the string variable at a module level and used in a different module, an error would occur.

vba string module error

However, if you use the Public keyword to declare the string variable, the error would not occur and the procedure would run perfectly.

Convert Values stored as String

There may be a time when you have values in Excel that are stored as text – for example, you may have imported a CSV file which may have brought in text instead of numbers.

Note that the value in A1 is left-aligned, indicating a text value.

vba string text

You can use a VBA Function can be used to convert these numbers to text

Sub ConvertValue()
'populate the string
    strQty = Range("A1")
'populate the double with the string
    dblQty = strQty
'populate the range with the number
    Range("A1") = dblQty
End Sub

Once you run the code, the number will move to the right-indicating that it is now stored as a number.

vba string number

This is particularly useful when you loop through a large range of cells.

vba string list

Sub ConvertValue()
    Dim strQty As String, dblQty As Double
    Dim rw As Integer, i As Integer
'count the rows to convert
    rw = Range("A1", Range("A1").End(xlDown)).Rows.Count
'loop through the cells and convert each one to a number
    For i = 0 To rw – 1
'populate the string
        strQty = Range("A1").Offset(i, 0)
'populate the double with the string
        dblQty = strQty
'populate the range with the number
        Range("A1").Offset(i, 0) = dblQty
    Next i
End Sub

The result will be that all the cells are then converted to numbers

vba number list

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!

automacro

Learn More

Convert String Stored as Values

Similarly, there might be values that you need to convert from a string to a value – for example, if you require a leading zero on a telephone number.

vba string number to string

Sub ConvertString()
    Dim strPhone As String, dblPhone As Double
    Dim rw As Integer, i As Integer
'count the rows to convert
    rw = Range("A1", Range("A1").End(xlDown)).Rows.Count
'loop through the cells and convert each one to a number
    For i = 0 To rw – 1
'populate the string
        dblPhone = Range("A1").Offset(i, 0)
'populate the double with the string
        strPhone = "'0" & dblPhone
'populate the range with the number
        Range("A1").Offset(i, 0) = strphone
    Next i
End Sub

vba string number to string converted

Note that you need to  begin the text string with an apostrophe (‘), before the zero in order to tell Excel to enter the value as string.

Понравилась статья? Поделить с друзьями:
  • Что такое selection в word
  • Что такое stop word
  • Что такое scroll lock в excel
  • Что такое stdev в excel
  • Что такое sqrt в excel