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.
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.
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”.
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”.
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”.
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.
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”.
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”.
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”.
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.
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.
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.
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
Содержание
- Основы работы со строками в Visual Basic
- Строковые переменные
- Символы в строках
- Неизменность строк
- String function
- Syntax
- Remarks
- Example
- See also
- Support and feedback
- Тип данных String (Visual Basic)
- Remarks
- Символы Юникода
- Требования к формату
- Операции со строками
- Советы по программированию
- Strings in VBA
- What is a String
- Concatenation
- String Manipulation
- Spaces — add or remove
- Replace
- Substring functions
- Left & Right
- Length or Position
- Search
- Summary
Основы работы со строками в Visual Basic
Тип данных String представляет последовательность символов (каждый из которых, в свою очередь, представляет экземпляр типа данных Char ). В этом разделе представлены основные понятия строк в Visual Basic.
Строковые переменные
Экземпляру строки можно назначить литеральное значение, которое представляет ряд символов. Например:
Переменная String также может принимать любое выражение, результатом которого является строка. Ниже приведены примеры.
Любой литерал, который присваивается переменной String , должен быть заключен в кавычки («»). Это означает, что кавычки в пределах строки не могут быть представлены кавычкой. Например, следующий код вызовет ошибку компиляции:
Этот код вызывает ошибку, так как компилятор завершает строку после второй пары кавычек, а остаток строки интерпретируется как код. Чтобы решить эту проблему, Visual Basic интерпретирует две кавычки в строковом литерале как одну кавычку в строке. В следующем примере показан правильный способ указания кавычек в строке:
В предыдущем примере два символа кавычек перед словом Look становятся одним символом кавычек в строке. Три символа кавычек в конце строки представляют один символ кавычек в строке и конечный символ строки.
Строковые литералы могут содержать несколько строк:
Результирующая строка содержит последовательности новых строк, используемых в строковом литерале (vbcr, vbcrlf и т. д.). Вам больше не требуется использовать старое решение:
Символы в строках
Строку можно представить как последовательность значений Char . При этом тип String имеет встроенные функции, которые позволяют работать со строками, как с массивами. Как и все массивы в платформа .NET Framework, это отсчитываемые от нуля массивы. К определенному символу в строке можно обратиться с помощью свойства Chars , которое предоставляет механизм доступа к символу по позиции, в которой он отображается в строке. Например:
В приведенном выше примере свойство Chars строки возвращает четвертый символ в строке, D , и присваивает его myChar . Вы также можете получить длину определенной строки с помощью свойства Length . Если вам требуется выполнить несколько манипуляций со строкой, можно преобразовать ее в массив экземпляров Char с помощью функции ToCharArray строки. Например:
Переменная myArray теперь содержит массив значений Char , каждое из которых представляет символ из myString .
Неизменность строк
Строка неизменяема, что означает, что ее значение нельзя изменить после ее создания. Однако это не мешает назначить строковой переменной более одного значения. Рассмотрим следующий пример.
Здесь строковая переменная создается, получает значение, которое затем изменяется.
В частности, в первой строке создается экземпляр типа String , которому присваивается значение This string is immutable . Во второй строке примера создается новый экземпляр, которому присваивается значение Or is it? . При этом строковая переменная удаляет ссылку на первый экземпляр и сохраняет ссылку на новый экземпляр.
В отличие от других встроенных типов данных String — это ссылочный тип. Если переменная ссылочного типа передается в качестве аргумента функции или подпрограмме, вместо фактического значения строки передается ссылка на адрес в памяти, где хранятся данные. Поэтому в предыдущем примере имя переменной остается таким же, но оно указывает на другой экземпляр класса String , который содержит новое значение.
Источник
String function
Returns a Variant (String) containing a repeating character string of the length specified.
Syntax
String(number, character)
The String function syntax has these named arguments:
Part | Description |
---|---|
number | Required; Long. Length of the returned string. If number contains Null, Null is returned. |
character | Required; Variant. Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned. |
If you specify a number for character greater than 255, String converts the number to a valid character code by using this formula: character Mod 256.
Example
This example uses the String function to return repeating character strings of the length specified.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Тип данных String (Visual Basic)
Содержит последовательности 16-разрядных (2-байтовых) кодовых точек без знака, которые варьируются от 0 до 65535. Каждая кодовая точка или код символов представляет один символ Юникода. Строка может содержать от 0 до примерно двух миллиардов (2 ^ 31) символов Юникода.
String Используйте тип данных для хранения нескольких символов без дополнительных затрат Char() на управление массивом массивов массива массива Char элементов.
Значение String по умолчанию равно ( Nothing пустая ссылка). Обратите внимание, что это не то же самое, что и пустая строка (значение «» ).
Символы Юникода
Первые 128 кодовых точек (0–127) Юникода соответствуют буквам и символам стандартной клавиатуры США. Первые 128 кодовых точек совпадают с теми, которые определяет набор символов ASCII. Вторая 128 кодовых точек (128–255) представляет специальные символы, такие как латинские буквы алфавита, акценты, символы валюты и дроби. Юникод использует оставшиеся кодовые точки (256–65535) для широкого спектра символов. Сюда входят текстовые символы по всему миру, диакритические символы и математические и технические символы.
Для определения классификации Юникода можно использовать такие методы, как IsDigitIsPunctuation и отдельный символ в переменной String .
Требования к формату
Необходимо заключить String литерал в кавычки ( » » ). Если необходимо включить кавычки в качестве одного из символов в строке, используйте две смежные кавычки ( «» ). Это показано в следующем примере.
Обратите внимание, что непрерывные кавычки, представляющие кавычки в строке, не зависят от кавычек, начинающихся и заканчивающих литерал String .
Операции со строками
После назначения строки переменной String эта строка неизменяема, что означает, что ее длина или содержимое изменить нельзя. При любом изменении строки Visual Basic создает новую строку и отказывается от предыдущей. Затем String переменная указывает на новую строку.
Содержимое переменной String можно управлять с помощью различных строковых функций. В следующем примере показана Left функция
Строка, созданная другим компонентом, может быть заполнена начальными или конечными пробелами. При получении такой строки можно использовать TrimLTrimфункции и RTrim функции для удаления этих пробелов.
Дополнительные сведения о манипуляциях со строками см. в разделе «Строки».
Советы по программированию
Отрицательные числа. Помните, что символы, удерживаемые String без знака, не могут представлять отрицательные значения. В любом случае не следует использовать String для хранения числовых значений.
Вопросы взаимодействия. Если вы взаимодействуете с компонентами, не написанными для платформа .NET Framework, например для объектов Automation или COM, помните, что строковые символы имеют другую ширину данных (8 бит) в других средах. Если вы передаете строковый аргумент из 8-разрядных символов такому компоненту, объявите его как Byte() массив Byte элементов, а не String в новом коде Visual Basic.
Символы типов. Добавление символа $ типа идентификатора к любому идентификатору заставляет его к типу String данных. String не имеет символа литерального типа. Однако компилятор обрабатывает литералы, заключенные в кавычки ( » » ) как String .
Источник
Strings in VBA
For a selection of other String function available in other languages but adapted for VBA, visit the additional string functions page with , StartsWith and EndsWith, Contains, PadLeft and PadRight, IsNullOrEmpty and more.
What is a String
The variable type is used to hold strings of text. Strings are a sequence of characters: alphabetical, numbers, special characters in any combination.
It is good programming practice to declare a variable and its type before using it because it prevents mistakes (see Option Explicit):
To give the variable a value the value has to be surrounded with double quotes:
Note |
---|
The Visual Basic interpreter tries to understand (resolve) any assignment of a variable given its type. The following would also be automatically converted to the string type: str = 100 |
Concatenation
Concatenation means the joining of multiple strings into a single string. You can do this with the & (most commonly used) or + (alternative) symbol.
. returns value for str1: abc_1230/08/2022
Note that VBA is not particular about the variable types you want to append, it will automatically convert the provided type to string in the process.
String Manipulation
There are many VBA’s built-in string functions that alter a string. Some of them we’ll study here: Trim, LCase and UCase, Space, Replace and StrReverse
LCase(String): Returns the lower case of the specified string
Ucase(String): Returns the upper case of the specified string
When you have to compare two variable values it can be important to check if all values are in the same case for the cases that it is not important if a value is written with capital or not. Then you use Lcase or Ucase before the values.
Spaces — add or remove
Space(number) — fills a string with a specified number of spaces. Used in combination with/ concatenated with other variables via the ‘&’-symbol. Note that more often you will simply create a string containing the required number of spaces.
Other functions concerning spaces remove spaces. As variable-values with or without erroneous spaces differ it is important to check if there are any spaces in values.
LTrim(String) | Returns a string after removing the spaces on the left side of the specified string. |
RTrim(String) | Returns a string after removing the spaces on the right side of the specified string. |
Trim(String) | Returns a string value after removing both leading and trailing blank spaces. |
Replace
Syntax: Replace( string_to_search, string_to_replace, replace_with [start, [count, [compare]]] )
The arguments between the [] are optional. Start: This is the position in string_to_search to begin the search. If this parameter is omitted, the Replace function will begin the search at position 1.
Count: This is the number of occurrences to replace. If this parameter is omitted, the REPLACE function will replace all occurrences of string_to_replace with replace_with.
Compare: This can be one of the following 2 values:vbBinary, the Compare Binary comparison or vbTextCompare, Textual comparison.
StrReverse(«abc»). Reverses the specified string: cba
Substring functions
Substring functions return only a certain part of the original string. VBA has a neat collection of such procedures discussed below.
Left & Right
The functions Left and Right return the first or last number of characters:
Mid(string_to_search, start_position, number_of_characters)
For extracting a substring, starting at the start_position somewhere in the middle of a string. If you want to extract a substring from a string starting in the middle until the end of it you can omit the third argument.
Length or Position
The Len(String) returns the length, the number of characters, of the string, including the blank spaces.
A common use of Len is to check if the string is empty or not, and let that determine what to do:
Search
InStr( [start], string_to_search, substring, [compare] ) ‘Returns the first occurence of the specified substring. Search happens from left to right.
On the first place you can give the startposition of the search, if omitted the search starts at the beginning. On the second place comes the text to search, and on the 3th place what you want to find. VBA will then give you an Integer back in return. This number is 0 if the string is not found. If the string is found then you get the location of the start of the string you were search for.
InStrRev(string1,string2[,start,[compare]])
InStrRev(» «codevbatool», «o») result:10
Returns the first occurence of the specified substring. Search happens from Right to Left. You get the place of the first occurence from the right of the string, but counted from the left. it checks its position from the forward direction and gives its position as the result.
The practical use of InStrRev can be in finding the last index of a character inside a string.
Summary
Function Name | Description |
---|---|
InStr | Returns the first occurence of the specified substring. Search happens from left to right. |
InstrRev | Returns the first occurence of the specified substring. Search happens from Right to Left. |
Lcase | Returns the lower case of the specified string. |
Ucase | Returns the Upper case of the specified string. |
Left | Returns a specific number of characters from the left side of the string. |
Right | Returns a specific number of characters from the Right side of the string. |
Mid | Returns a specific number of characters from a string based on the specified parameters. |
Ltrim | Returns a string after removing the spaces on the left side of the specified string. |
Rtrim | Returns a string after removing the spaces on the right side of the specified string. |
Trim | Returns a string value after removing both leading and trailing blank spaces. |
Len | Returns the lenght of the given string. |
Replace | Returns a string after replacing a string with another string. |
Space | Fills a string with the specified number of spaces. |
StrComp | Returns an integer value after comparing the two specified strings. |
String | Returns a String with a specified character the specified number of times. |
StrReverse | Returns a String after reversing the sequence of the characters of the given string. |
Below image shows the Code VBA add-in support for VBA String procedures.
Источник
Table of Contents
- INTRODUCTION
- WHAT IS A STRING IN VBA ?
- EXAMPLE 1-ENTERING THE STRING/TEXT INTO CELL IN VBA
- EXAMPLE 2- JOIN THE TEXT GIVEN IN THE CELLS D3 , D4 AND D5
- EXAMPLE 3- REMOVING ANY SPECIFIC CHARACTER/S FROM STRING IN VBA
INTRODUCTION
STRING is the specific term given to the normal Text in the programming languages.
Strings are a very important component in any program as this is the only part of the language through which the program communicates with the user.
We ask the user for input through a STRING.
We process the user input.
We return the output to the user through a STRING.
So we can understand the importance of Strings in VBA.
Many times we need to handle strings very carefully for which we need to know several types of manipulations so that we can make our application can communicate effectively.
” STRINGS ARE THE ONLY WAY THROUGH WHICH OUR APPLICATIONS COMMUNICATE WITH THE USER”
So, we’ll learn many types of STRING MANIPULATIONS in this article.
WHAT IS A STRING IN VBA ?
Simple text is a String. A string is a collection of characters.
As we know programming languages consider the characters as the basic unit.
So when characters combine STRINGS are formed.
e.g.”WELCOME TO GYANKOSH.NET” is a String.
EXAMPLE 1-ENTERING THE STRING/TEXT INTO CELL IN VBA
OBJECTIVE
ENTER THE TEXT “WELCOME TO GYANKOSH.NET” INTO THE CELL D3 USING VBA.
Make use of VBA to enter the given text into cell positioned at location D3.
PLANNING THE SOLUTION
In this case we simply need to send the String to the cell.
Steps:
1. Select the cell.
2. Put the string into the cell.
CODE
' gyankosh.net
' putting a custom text/string in a specified cell
Sub stringtocell()
Range("d3").Value = "WELCOME TO GYANKOSH.NET"
End Sub
EXPLANATION
There is just one statement in the code.Range(“d3”) refers to CELL D3.
VALUE refers to the value of D3.
So we put the value of D3 as String “WELCOME TO GYANKOSH.NET”
RUNNING THE CODE AND OUTPUT
EXAMPLE 2- JOIN THE TEXT GIVEN IN THE CELLS D3 , D4 AND D5
OBJECTIVE
JOIN THE TEXT GIVEN IN THE CELLS D3, D4 AND D5 USING VBA
PLANNING THE SOLUTION
We’ll get the data from the cells and concatenate it.
Then again send it to cell D6.
1. Retrieve text present in D3 D4 AND D5.
2. Concatenate the data.
3. Put the data back in D6.
CODE
' gyankosh.net
' join the text in three given cells and output in fourth cell
Sub jointext()
Dim temp1 As String
Dim temp2 As String
Dim temp3 As String
Dim temp4 As String
temp1 = ActiveSheet.Cells(3, 4).Value 'ANOTHER WAY OF REACHING A CELL
temp2 = ActiveSheet.Cells(4, 4).Value
temp3 = ActiveSheet.Cells(5, 4).Value
Range("d6″).Value = temp1 + " " + temp2 + " " + temp3 'CONCATENATING
End Sub
EXPLANATION
We declare temp1, temp2, temp3, and temp4 as strings for holding the values temporarily.
We retrieve the value with a new method.
Activesheet.cells(row, column).value
All the values are in the temp variables.
We put the value in d6 and concatenate the temp1, temp2, and temp3.
RUNNING THE CODE AND OUTPUT
EXAMPLE 3- REMOVING ANY SPECIFIC CHARACTER/S FROM STRING IN VBA
OBJECTIVE
REMOVE CHARACTER c FROM THE GIVEN STRING-CAT CAUGHT A MOUSE
PLANNING THE SOLUTION
Whenever we need to inspect any string, we need to go character-wise. As we need to eliminate c, we need to check every character sequentially.
- Get the input from the cell to a string.
- Examine the string one by one.
- If the character is c , skip it, if others, leave them as such.
- Return back the string.
CODE
' gyankosh.net
' REMOVING CHARACTER C FROM THE GIVEN STRING
Sub replaceCharacter()
Dim temp1 As String
Dim temp2 As String
temp2 = ""
temp1 = Range("F3").Value 'getting value from cell
Dim I As Integer
For I = 1 To Len(temp1)
If Not UCase(Mid(temp1, I, 1)) = "C" Then 'scanning character if its equal to c or not
temp2 = temp2 + Mid(temp1, I, 1)
End If
Next I
Range("H3").Value = "The given string after removing c is " + temp2 'Sending the text back to cell.
End Sub
EXPLANATION
We declare temp1 and temp2 as a string variable and get the input from the cell.
temp2 is kept for putting in the characters, which we don’t need to skip.
Start the loop with variable i =1 up to the length of temp1.
Apply if the UPPER CASE of MID(TEMP1,I,1) which gives the ith character, is equal to c or not. If yes, skip it, and if not, just attach it with the temporary string temp2.
Output is taken by putting the value back to cell H3.
RUNNING THE CODE AND OUTPUT
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.
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.
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.
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.
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.
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
If you declared the string variable at a module level and used in a different module, an error would occur.
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.
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.
This is particularly useful when you loop through a large range of cells.
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 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!
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.
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
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.