Excel and string functions

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 Excel Starter 2010 More…Less

To get detailed information about a function, click its name in the first column.

Note: Version markers indicate the version of Excel a function was introduced. These functions aren’t available in earlier versions. For example, a version marker of 2013 indicates that this function is available in Excel 2013 and all later versions.

Function

Description

ARRAYTOTEXT function

Office 365 button

Returns an array of text values from any specified range

ASC function

Changes full-width (double-byte) English letters or katakana within a character string to half-width (single-byte) characters

BAHTTEXT function

Converts a number to text, using the ß (baht) currency format

CHAR function

Returns the character specified by the code number

CLEAN function

Removes all nonprintable characters from text

CODE function

Returns a numeric code for the first character in a text string

CONCAT function

Excel 2016

Combines the text from multiple ranges and/or strings, but it doesn’t provide the delimiter or IgnoreEmpty arguments.

CONCATENATE function

Joins several text items into one text item

DBCS function

Excel 2013

Changes half-width (single-byte) English letters or katakana within a character string to full-width (double-byte) characters

DOLLAR function

Converts a number to text, using the $ (dollar) currency format

EXACT function

Checks to see if two text values are identical

FIND, FINDB functions

Finds one text value within another (case-sensitive)

FIXED function

Formats a number as text with a fixed number of decimals

LEFT, LEFTB functions

Returns the leftmost characters from a text value

LEN, LENB functions

Returns the number of characters in a text string

LOWER function

Converts text to lowercase

MID, MIDB functions

Returns a specific number of characters from a text string starting at the position you specify

NUMBERVALUE function

Excel 2013

Converts text to number in a locale-independent manner

PHONETIC function

Extracts the phonetic (furigana) characters from a text string

PROPER function

Capitalizes the first letter in each word of a text value

REPLACE, REPLACEB functions

Replaces characters within text

REPT function

Repeats text a given number of times

RIGHT, RIGHTB functions

Returns the rightmost characters from a text value

SEARCH, SEARCHB functions

Finds one text value within another (not case-sensitive)

SUBSTITUTE function

Substitutes new text for old text in a text string

T function

Converts its arguments to text

TEXT function

Formats a number and converts it to text

TEXTAFTER function

Office 365 button

Returns text that occurs after given character or string

TEXTBEFORE function

Office 365 button

Returns text that occurs before a given character or string

TEXTJOIN function

Office 365 button

Combines the text from multiple ranges and/or strings

TEXTSPLIT function

Office 365 button

Splits text strings by using column and row delimiters

TRIM function

Removes spaces from text

UNICHAR function

Excel 2013

Returns the Unicode character that is references by the given numeric value

UNICODE function

Excel 2013

Returns the number (code point) that corresponds to the first character of the text

UPPER function

Converts text to uppercase

VALUE function

Converts a text argument to a number

VALUETOTEXT function

Office 365 button

Returns text from any specified value

Important: The calculated results of formulas and some Excel worksheet functions may differ slightly between a Windows PC using x86 or x86-64 architecture and a Windows RT PC using ARM architecture. Learn more about the differences.

See Also

Excel functions (by category)

Excel functions (alphabetical)

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

In Excel, there are multiple string (text) functions that can help you to deal with textual data. These functions can help you to change a text, change the case, find a string, count the length of the string, etc. In this post, we have covered top text functions. (Sample Files)

1. LEN Function

LEN function returns the count of characters in the value. In simple words, with the LEN function, you can count how many characters are there in value. You can refer to a cell or insert the value in the function directly.

Syntax

LEN(text)

Arguments

  • text: A string for which you want to count the characters.

Example

In the below example, we have used the LEN to count letters in a cell. “Hello, World” has 10 characters with a space between and we have got 11 in the result.

excel-len-function-example-1

In the below example, “22-Jan-2016” has 11 characters, but LEN returns 5.

excel-len-function-example-2

The reason behind it is that the LEN function counts the characters in the value of a cell and is not concerned with formatting.

Related: How to COUNT Words in Excel

2. FIND Function

FIND function returns a number which is the starting position of a substring in a string. In simple words, by using the find function you can find (case sensitive) a string’s starting position from another string.

Syntax

FIND(find_text,within_text,[start_num])

Arguments

  • find_text: The text which you want to find from another text.
  • within_text: The text from which you want to locate the text.
  • [start_num]: The number represents the starting position of the search.

Example

In the below example, we have used the FIND to locate the “:” and then with the help of MID and LEN, we have extracted the name from the cell.

3. SEARCH Function

SEARCH function returns a number which is the starting position of a substring in a string. In simple words, with the SEARCH function, you can search (non-case sensitive) for a text string’s starting position from another string.

Syntax

SEARCH(find_text,within_text,[start_num])

Arguments

  • find_text: A text which you want to find from another text.
  • within_text: A text from which you want to locate the text. You can refer to a cell, or you can input a text in your function.

Example

In the below example, we are searching for the alphabet “P” and we have specified start_num as 1 to start our search. Our formula returns 1 as the position of the text.

excel-search-function-example-1

But, if you look at the word, we also have a “P” in the 6th position. That means the SEARCH function can only return the position of the first occurrence of a text, or if you specify the start position accordingly.

4. LEFT Function

LEFT Functions return sequential characters from a string starting from the left side (starting). In simple words, with the LEFT function, you can extract characters from a string from its left side.

Syntax

LEFT(text,num_chars)

Arguments

  • text: A text or number from which you want to extract characters.
  • [num_char]: The number of characters you want to extract.

Example

In the below example, we have extracted the first five digits from a text string using LEFT by specifying the number of characters to extract.

excel-left-function-example-1

In the below example, we have used LEN and FIND along with the LEFT to create a formula that extracts the name from the cell.

excel-left-function-example-2

5. RIGHT Function

The RIGHT function returns sequential characters from a string starting from the right side (ending). In simple words, with the RIGHT function, you can extract characters from a string from its left side.

Syntax

RIGHT(text,num_chars)

Arguments

  • text: A text or number from which you want to extract characters.
  • [num_char]: A number of characters you want to extract.

Example

In the below example, we have extracted 6 characters using the right function. If you know, how many characters you need to extract from the string, you can simply extract them by using a number.

excel-right-function-example-1

Now, if you look at the below example, where we have to extract the last name from the cell, but we are not confirmed about the number of characters in the last name.

excel-right-function-example-2

So, we are using LEN and FIND to get the name. Let me show you how we have done this.

First of all, we have used the LEN to get the length of that entire text string, then we used the FIND to get the position number of space between first and last names. And in the end, we have used both the figures to get the last name.

Arguments

  • value1: A cell reference, an array, or a number that is directly entered into the function.
  • [value2]: A cell reference, an array, or a number that is directly entered into the function.

6. MID Function

MID returns a substring from a string using a specific position and number of characters. In simple words, with MID, you can extract a substring from a string by specifying the starting character and number of characters you want to extract.

Syntax

MID(text,start_num,num_chars)

Arguments

  • text: A text or a number from which you want to extract characters.
  • start_char: A number for the position of the character from where you want to extract characters.
  • num_chars: The number of characters you want to extract from the start_char.

Example

In the below example, we have used different values:

  • From the 6th character to the next 6 characters.
  • From the 6th character to the next 10 characters.
  • We have used starting a character in negative and it has returned an error.
  • By using 0 for the number of characters to extract and it has returned a blank.
  • With a negative number for the number of characters to extract and it has returned an error.
  • The starting number is zero and it has returned an error.
  • Text string directly into the function.
excel-mid-function-example-1

7. LOWER Function

LOWER returns the string after converting all the letters in small. In simple words, it converts a text string where all the letters you have are in small letters, numbers will stay intact.

Syntax

LOWER(text)

Arguments

  • text: The text which you want to convert to the lowercase.

Example

In the below example, we have compared the lower case, upper case, proper case, and sentence case with each other.

excel-lower-function-example-1

A lower case text has all the letters in a small case compared to others.

8. PROPER Function

The PROPER function returns the text string into a proper case. In simple words, with a PROPER function where the first letter of the word is in capital and rest in small (proper case).

Syntax

PROPER(text)

Arguments

  • text: The text which you want to convert to the proper case.

Example

In the below example, we have a proper case that has the first letter in the capital case in a word and the rest of the letters are in the lower case compared to the other two cases lowercase and uppercase.

excel-proper-function-example-1

In the below example, we have used the PROPER function to streamline first name and last name into the proper case.

excel-proper-function-example-2

9. UPPER Function

The UPPER function returns the string after converting all the letters in the capital. In simple words, it converts a text string where all the letters you have are in capital form and numbers will stay intact.

Syntax

UPPER(text)

Arguments

  • text: The text which you want to convert into uppercase.

Example

In the below example, we have used the UPPER to convert name text to capital letters from the text in which characters are in different cases.

excel-upper-function-example-1

10. REPT Function

REPT function returns a text value several times. In simple words, with the REPT function, you can specify a text, and a number to repeat that text.

Syntax

REPT(value1, [value2], …)

Example

In the below example, we have used different type of text for repetition using REPT. It can repeat any type of text or numbers and even symbols that you specify in function and the main use of the REPT function is for creating in-cell charts.

excel-rept-function-example-1

Join Strings | Left | Right | Mid | Len | Find | Substitute

Excel has many functions to offer when it comes to manipulating text strings.

Join Strings

To join strings, use the & operator.

Join Strings

Note: instead of using the & operator, use the CONCATENATE function in Excel.

Left

To extract the leftmost characters from a string, use the LEFT function.

Left Function

Right

To extract the rightmost characters from a string, use the RIGHT function.

Right Function

Mid

To extract a substring, starting in the middle of a string, use the MID function.

Mid Function

Note: started at position 5 (p) with length 3.

Len

To get the length of a string, use the LEN function.

Len Function

Note: space (position 8) included!

Find

To find the position of a substring in a string, use the FIND function.

Find Function

Note: string «am» found at position 3. Visit our page about the FIND function for more examples.

Substitute

To replace existing text with new text in a string, use the SUBSTITUTE function.

Substitute Function

Excel Text and String Functions:

Excel Functions for Finding and Replacing Text, with Examples: LEFT, RIGHT, MID, LEN, FIND, SEARCH, REPLACE, SUBSTITUTE

Related Links:

1. Excel Text and String Functions: TRIM & CLEAN.

2. Excel CODE & CHAR functions.

————————————————————————————————————————-

This section deals with the Excel Worksheet String Functions — click here for detailed explanation of Excel VBA String Functions.

LEFT Function (Worksheet / VBA)

The Excel LEFT function can be used both as a worksheet function and a VBA function. The LEFT function returns the specified number of characters in a text string, starting from the first or left-most character. Use this function to extract a sub-string from the left part of a text string. Syntax: LEFT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the LEFT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

Examples:

Cell A1 contains the text string «James Bond».

=LEFT(A1,7)

Returns «James B», which are the first 7 characters. Note that space is counted as a distinct character.

=LEFT(A1, 15)

Returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

=LEFT(A1)

Returns «J», a single character. Not specifying the number of characters, will default to 1.

—————————————————————————————————————————  

RIGHT Function (Worksheet / VBA)

The Excel RIGHT function can be used both as a worksheet function and a VBA function. The RIGHT function returns the specified number of characters in a text string, starting from the last or right-most character. Use this function to extract a sub-string from the right part of a text string. Syntax: RIGHT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the RIGHT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

Examples:

Cell A1 contains the text string «James Bond».

=RIGHT(A1,7)

Returns «es Bond», which are the last 7 characters. Note that space is counted as a distinct character.

=RIGHT(A1, 15)

Returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

=RIGHT(A1)

Returns «d», a single character. Not specifying the number of characters, will default to 1.

————————————————————————————————————————  

MID Function (Worksheet / VBA)

The Excel MID function can be used both as a worksheet function and a VBA function. The MID function returns the specified number of characters in a text string, starting from a specified position (ie. starting from a specified character number). Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers). The text_string argument is the text string from which you want to extract the specified number of characters. The start_number argument specifies the character number from which to start extracting the sub-string, the first character in a text string being start_number 1 and incrementing towards the right. The char_numbers argument specifies the number of characters to extract from the text string.

If start_number is greater than the length of the text string, an empty string (zero length) is returned; if it is less than the length of the text string but together with char_numbers (ie. start_number PLUS char_numbers) it is greater than the length of the text string, the MID function will return the text string in full from the start_number position to the end of the text string.

Using MID function as a worksheet function, if a negative value is specified for char_numbers, MID will return the #VALUE! error value; if start_number is less than 1, MID will return the #VALUE! error value. All arguments are necessary to be specified when using as a worksheet function.

Using MID function as a VBA function: The char_numbers argument is optional when used as VBA function, and if omitted the function will return the text string in full from the start_number position to the end of the text string. All other arguments are necessary to be specified when using as a vba function. If text_string contains Null, the function also returns Null.

Examples:

Cell A1 contains the text string «James Bond».

=MID(A1,2,6)

Returns «ames B». Starts from the second character ie. «a», and then specifies that 6 characters be returned starting from «a».

=MID(A1,2, 15)

Returns «ames Bond». Returns all characters starting from the second character of «a», because the specified characters number 15 plus start number 2 (ie. total of 17) exceed the string length of 10 characters.

=MID(A1, 12,2)

Returns empty text (), because the start number of 12 exceeds the string length of 10 characters.

=MID(A1,0,7)

Returns the #VALUE! error value, because the start number (ie. zero) is less than 1.

—————————————————————————————————————————  

LEN Function (Worksheet / VBA) 

The Excel LEN function can be used both as a worksheet function and a VBA function. The worksheet LEN function returns the number of characters in a text string. Use this function to get the length of a text string. Syntax: LEN(text_string). It is necessary to mention the text_string argument which is the text string whose length you want to get in number of characters. Note that spaces also count as characters. The worksheet LENB function returns the number of bytes used to represent the characters in a text string — counts each character as 1 byte except when a DBCS language [viz. Japanese, Chinese (Simplified), Chinese (Traditional), and Korean] is set as the default language wherein a character is counted as 2 bytes. Syntax: LENB(text_string).

While using LEN as a VBA functionSyntax: Len(text_string) or Len(variable_name) — you can use either a text string or a variable name, and the function will return a Long value representing the number of characters contained in the string or the number of bytes required to store a variable. Using the vba Len function for a variable of type variant will treat the variable as a String and return the number of characters contained in it. A text_string or variable containing Null, will also return Null. The vba Len function returns the number of characters in the string where the variable is of subtype String or Variant, and wherein the variable is of subtype numeric the function returns the number of bytes used to store the variable.

Example:

Cell A1 contains the text string «James Bond».

=LEN(A1)

Returns 10, the string length measured by its number of characters.

—————————————————————————————————————————  

FIND Function (Worksheet)

The FIND function returns the starting position of a text string, which it locates from within a second text string. The starting position is the number, which is calculated beginning from the first character of that second text string. FIND is case-sensitive. Syntax: FIND(text_to_find, within_text, start_number). It is necessary to mention the first 2 arguments, while start_number argument is optional. The text_to_find argument is the text string that you want to find or locate, and it cannot contain any wildcard characters. The within_text argument is the second text string within which you want to find or search. The start_number argument specifies the character number of within_text from where you want to start the search. The first character number of within_text is 1, incrementing towards the right. Omitting the start_number argument will start your search from the first character ie. number 1. The Excel FIND function is a worksheet function. FIND is not a VBA function but can be called or used in VBA code (worksheet functions can be called from VBA using the Application or Application.Worksheet objects).

If text_to_find cannot be located in within_text, or if start_number is specified as less than 1 or greater than the length of within_text, the FIND function will return the #VALUE! error value.

If you specify text_to_find as empty text («»), the FIND function will match the character numbered start_number (or 1, if start_number is omitted) in the within_text.

Difference with SEARCH is that FIND is case sensitive and does not allow wildcard characters. If you don’t want to do a case sensitive search or use wildcard characters, you can use SEARCH.

Examples:

Cell A2 contains the text string «Australia».

=FIND(«a»,A2)

Returns 6, which is the position of the first small cap character «a» in the string.

=FIND(«A»,A2)

Returns 1, which is the position of the first large cap character «a» in the string.

=FIND(«A», A2,7)

Returns the #VALUE! error value, because text «A» is not found in the string.

=FIND(«a», A2,7)

Returns 9, which is the position of the first small cap character «a» in the string, starting from character number 7. 

——————————————————————————————————————  

SEARCH Function (Worksheet)

The SEARCH function returns the starting position of a text string, which it locates from within a second text string. The starting position is the number, which is calculated beginning from the first character of that second text string. SEARCH is not case-sensitive. Syntax: SEARCH(text_to_find, within_text, start_number). It is necessary to mention the first 2 arguments, while start_number argument is optional. The text_to_find argument is the text string that you want to find or locate, and it cannot contain any wildcard characters. The within_text argument is the second text string within which you want to find or search. The start_number argument specifies the character number of within_text from where you want to start the search. The first character number of within_text is 1, incrementing towards the right. Omitting the start_number argument will start your search from the first character ie. number 1. The Excel SEARCH function is a worksheet function. SEARCH is not a VBA function but can be called or used in VBA code (worksheet functions can be called from VBA using the Application or Application.Worksheet objects).

The text_to_find argument can include the wildcard characters, question mark (?) and asterisk (*). Any single character is matched using a question mark; any sequence of characters are matched using an asterisk. To find an actual question mark or asterisk, type a tilde (~) before the character.

If text_to_find cannot be located in within_text, or if start_number is specified as less than 1 or greater than the length of within_text, the FIND function will return the #VALUE! error value.

If you specify text_to_find as empty text («»), the FIND function will match the character numbered start_number (or 1, if start_number is omitted) in the within_text.

Difference with FIND is that SEARCH is not case sensitive but allows use of wildcard characters. If you want to do a case sensitive search and not use wildcard characters, you can use FIND.

Examples:

Cell A2 contains the text string «Australia».

=SEARCH(«a»,A2)

Returns 1, which is the position of the first character «a» or «A» in the string. Note: using the FIND Function will return 6, because FIND will look for the first small cap character «a», being case-sensitive.

Cell A5 contains the text string «Daily is every day».

=SEARCH(«d?y», A5)

Returns 16, which is the starting character number of the first string which meets the criteria. This is the position of the first string that starts with «d» and ends with «y» and has only a single character inbetween.

=SEARCH(«d*y», A5)

Returns 1, which is the starting character number of the first string which meets the criteria. This is the position of the first string that starts with «d» and ends with «y» and has any number of characters inbetween. Note: The formula «=SEARCH(«d*y»,A5,2)» will return 16.

—————————————————————————————————————————  

REPLACE Function (Worksheet)

The REPLACE function replaces part of a text string with a new text string, based on specified number of characters and starting from a specified position. Syntax: REPLACE(old_text, start_number, number_of_chars, new_text). It is necessary to specify all arguments. The old_text argument is the text string in which you want to replace with new text. The start_number argument is the position of the character in old_text, which you want to replace (ie. position of the first character from which replacement should start). Position is the character number, first character being number 1 & incrementing towards the right. The number_of_chars is the number of charactres which will be replaced in the old_text (with new_text). The new_text is the text string which will replace the characters in old_text.

There is also a REPLACE Function in vba, which is not being discussed here. Refer our VBA section for details.

Example:

Cell A2 contains the text string «Australia».

=REPLACE(A2, 8,2, «Asia»)

Returns «AustralAsia». Replaces 2 characters, starting with the character number 8, with «Asia».

—————————————————————————————————————————  

SUBSTITUTE Function (Worksheet)

Use the SUBSTITUTE function to replace old text with new text in a text string. Substitute Function vs Replace Function: The difference is that in Substitute you replace specific text with new text while in Replace you replace any text based on its position and length within a text string. Syntax: SUBSTITUTE(text, old_text, new_text, instance_num). It is necessary to specify all arguments except instance_num. The text argument is the text string which contains the old text which you want to replace. The old_text argument is the text string which you want to replace with new text. The new_text argument is the new text which replaces the old text. The instance_num argument is a numerical value which specifies the occurrence of old text which you want to replace with new text. All occurrences of old text within the text string will be replaced with new text if you omit to specify this argument, else only the specified number of occurrences of the old text will be replaced with new text.

Examples:

Cell A2 contains the text string «Australia».

=SUBSTITUTE(A2,»ia», «Asia»)

Returns «AustralAsia». Substitutes «ia» with «Asia».

Cell A4 contains the text string «Tue, Feb 01, 2011».

=SUBSTITUTE(A4,1, 2,3)

Returns «Tue, Feb 01, 2012». Substitutes the third instance of «1» with «2».

=SUBSTITUTE(A4, 1,2)

Returns «Tue, Feb 02, 2022». Substitutes all instances of «1» with «2».

—————————————————————————————————————————  

Nesting FIND within MID (Example)

Cell A3 contains the text string «James Bond Daniel Craig», and we want to replace a part of the text so as to have the new string «James Bond 007».

=MID(A3,1,FIND(«Daniel Craig», A3)-1)& «007»  [Formula]

Returns the string «James Bond 007».

=FIND(«Daniel Craig», A3) -> This part of the formula returns 12, which is the position of «Daniel Craig» in the text. Deduct 1 from this number, to arrive at the position of the last character in the text before «Daniel Craig».

=MID(A3,1,FIND(«Daniel Craig», A3)-1) -> This part returns the text «James Bond «, having deleted the text «Daniel Craig» which we wish to replace. MID Function returns 11 characters (note that there is a space after James Bond) from the text string, starting from character number 1.

=MID(A3,1,FIND(«Daniel Craig», A3)-1)& «007» -> This completes the formula by adding the text «007». We have now replaced the text «Daniel Craig» with «007», to return the string «James Bond 007».

Nesting FIND within REPLACE (Example)

Cell A3 contains the string «James Bond Daniel Craig», and we want to replace a part of the text so as to have the new string «James Bond 007».

=REPLACE(A3, FIND(«Daniel Craig», A3),13, «007»)  [Formula]

Returns the string «James Bond 007».

=FIND(«Daniel Craig»,A3) -> This part of the formula returns 12, which is the position of «Daniel Craig» in the text.

=REPLACE(A3, FIND(«Daniel Craig»,A3), 12,»007″) -> The REPLACE Function replaces in the A3 string, starting with character number 12, and replaces 12 characters («Daniel Craig») in the old text. This completes the formula having now replaced the text «Daniel Craig» with «007», to return the string «James Bond 007».

Splitting a String into Separate Cells (Examples)

Example 1

We have used the LEFT, RIGHT, MID, LEN and FIND Functions to manipulate text, and split a string into separate cells — in the string (column A) each word is separated with a comma and a blank space, and the length of Month, Date & Year is fixed (3, 2 & 4 characters respectively) while number of characters for Day vary.

Refer Table 1 — Dates in column A have been split into separate cells, in columns C to F. We take each cell at a time, and explain how it is done.

Cell C2 contains the formula «=LEFT(A2, FIND(«,», A2)-1)», and returns the day of week as «Tuesday». FIND(«,», A2)  part of the formula returns 8, which is the position of the first occurrence of the character «,» in the string. Reducing this by 1 (to 7), we use the LEFT function to extract the 7-character text (which is the day of week) appearing to the left of the character «,».

Cell D2 contains the formula «=MID(A2, FIND(«,»,A2)+2, 3)», and returns the month as «Feb». FIND(«,», A2)  part of the formula returns 8, which is the position of the first occurrence of the character «,» in the string. Increasing this by 2 (to 10), we use the MID function to return the 3-character text (which is the month), starting from character number 10.

Cell E2 contains the formula «=MID(A2, FIND(«,», A2)+6, 2)», and returns the date as «01». FIND(«,», A2)  part of the formula returns 8, which is the position of the first occurrence of the character «,» in the string. Increasing this by 6 (to 14), we use the MID function to return the 2-character text (which is the date), starting from character number 14.

Cell F2 contains the formula «=RIGHT(A2, 4)», and returns the year as «2011». RIGHT returns the last 4 characters in the text string, which is the corresponding year.

Example 2

The formulas have been made more complex, by using the full month name instead of the abbreviated form. Now the number of characters in the month name will vary, whereas the length of abbreviated month name was fixed (viz. 3).

Refer Table 2 — Dates in column A have been split into separate cells, in columns C to F. We take each cell at a time, and explain how it is done.

Cell C2 contains the formula «=LEFT(A2,FIND(«,», A2)-1)», and returns the day of week as «Tuesday». FIND(«,», A2)  part of the formula returns 8, which is the position of the first occurrence of the character «,» in the string. Reducing this by 1 (to 7), we use the LEFT function to extract the 7-character text (which is the day of week) appearing to the left of the character «,».

Cell D2 contains the formula «=MID(A2, FIND(«,», A2)+2, LEN(A2)-9-(FIND(«,», A2)+1))», and returns the month as «February». FIND(«,»,A2)  part of the formula returns 8, which is the position of the first occurrence of the character «,» in the string. Increasing this by 2 (to 10), we use the MID function to return the text (which is the month), starting from character number 10. But for this, we need to know the length of this text (ie. month name), which is determined by «LEN(A2)-9- (FIND(«,», A2)+1)». The string length of 26 [LEN(A2)] is reduced by: (i) 9, which is the number of characters after the month name ie. » 01, 2011″ (note the 2 spaces inbetween); and (ii) the formula part (FIND(«,»,A2)+1) which returns 9, which are the number of characters before start of month name ie. «Tuesday, » (note the 1 space inbetween). Therefore, length of the month name («February») is determined to be equal to: 26 minus 9 minus 9, which is 8.

Cell E2 contains the formula «=MID(A2,FIND(«,», A2, FIND(«,», A2)+1)-2, 2)», and returns the date as «01». We use the MID function to return the 2-character text (which is the date), but the starting character number is to be determined. The formula part FIND(«,»,A2,FIND(«,»,A2)+1)-2 determines this character number to start from. The formula FIND(«,»,A2)+1 returns 9, which is the next character number after the first occurrence of «,». The formula FIND(«,»,A2,FIND(«,»,A2)+1)  returns 21, whihc is the position of the second occurrence of «,». Reducing this by 2 (to 19) will give us the starting character number of date, which we had set to find out. Therefore, the MID formula to find the date, will return the 2-character text date, starting from character number 19.

Cell F2 contains the formula «=RIGHT(A2, 4)», and returns the year as «2011». RIGHT returns the last 4 characters in the text string, which is the corresponding year.

Содержание

  1. Excel String Functions: LEFT, RIGHT, MID, LEN and FIND
  2. Excel String Functions: LEFT, RIGHT, MID, LEN and FIND
  3. Retrieve a specific number of characters from the left side of a string
  4. Retrieve a specific number of characters from the right side of a string
  5. Get a specific number of characters from the middle of a string
  6. Gel all characters before a symbol (for a varying-length string)
  7. Gel all characters before space (for a varying-length string )
  8. Obtain all characters after a symbol (for a varying-length string )
  9. Obtain all characters between two symbols (for a varying-length string)
  10. Excel String Functions – Summary
  11. VBA Text and String Functions in Excel
  12. List of Text and String Functions in Excel VBA:
  13. Other Useful Resources:

Excel String Functions: LEFT, RIGHT, MID, LEN and FIND

Need to retrieve specific characters from a string in Excel? If so, in this guide, you’ll see how to use the Excel string functions to obtain your desired characters within a string.

Specifically, you’ll observe how to apply the following Excel string functions using practical examples:

Excel String Functions Used Description of Operation
LEFT Get characters from the left side of a string
RIGHT Get characters from the right side of a string
MID Get characters from the middle of a string
LEFT, FIND Get all characters before a symbol
LEFT, FIND Get all characters before a space
RIGHT, LEN, FIND Get all characters after a symbol
MID, FIND Get all characters between two symbols

Excel String Functions: LEFT, RIGHT, MID, LEN and FIND

To start, let’s say that you stored different strings in Excel. These strings may contain a mixture of:

  • Letters
  • Digits
  • Symbols (such as a dash symbol “-“)
  • Spaces

Now, let’s suppose that your goal is to isolate/retrieve only the digits within those strings.

How would you then achieve this goal using the Excel string functions?

Let’s dive into few examples to see how you can accomplish this goal.

Retrieve a specific number of characters from the left side of a string

In the following example, you’ll see three strings. Each of those strings would contain a total of 9 characters:

  • Five digits starting from the left side of the string
  • One dash symbol (“-“)
  • Three letters at the end of the string

As indicated before, the goal is to retrieve only the digits within the strings.

How would you do that in Excel?

Here are the steps:

(1) First, type/paste the table below into Excel, within the range of cells A1 to B4 (to keep things simple across all the examples to come, the tables to be typed/pasted into Excel, should be stored in the range of cells A1 to B4):

Identifier Result
55555-End
77777-End
99999-End

Since the goal is to retrieve the first 5 digits from the left, you’ll need to use the LEFT formula, which has the following structure:

(2) Next, type the following formula in cell B2:

(3) Finally, drag the LEFT formula from cell B2 to B4 in order to get the results across your 3 records.

This is how your table would look like in Excel after applying the LEFT formula:

Identifier Result
55555-End 55555
77777-End 77777
99999-End 99999

Retrieve a specific number of characters from the right side of a string

Wait a minute! what if your digits are located on the right-side of the string?

Let’s look at the opposite case, where you have your digits on the right-side of a string.

Here are the steps that you’ll need to follow in order to retrieve those digits:

(1) Type/paste the following table into cells A1 to B4:

Identifier Result
ID-55555
ID-77777
ID-99999

Here, you’ll need to use the RIGHT formula that has the following structure:

(2) Then, type the following formula in cell B2:

(3) Finally, drag your RIGHT formula from cell B2 to B4.

This is how the table would look like after applying the RIGHT formula:

Identifier Result
ID-55555 55555
ID-77777 77777
ID-99999 99999

Get a specific number of characters from the middle of a string

So far you have seen cases where the digits are located either on the left-side, or the right-side, of a string.

But what if the digits are located in the middle of the string, and you’d like to retrieve only those digits?

Here are the steps that you can apply:

(1) Type/paste the following table into cells A1 to B4:

Identifier Result
ID-55555-End
ID-77777-End
ID-99999-End

Here, you’ll need to use the MID formula with the following structure:

(2) Now type the following formula in cell B2:

(3) Finally, drag the MID formula from cell B2 to B4.

This is how the table would look like:

Identifier Result
ID-55555-End 55555
ID-77777-End 77777
ID-99999-End 99999

In the subsequent sections, you’ll see how to retrieve your desired characters from strings of varying lengths.

Gel all characters before a symbol (for a varying-length string)

Ready to get more fancy?

Let’s say that you have your desired digits on the left side of a string, BUT the number of digits on the left side of the string keeps changing.

In the following example, you’ll see how to retrieve all the desired digits before a symbol (e.g., the dash symbol “-“) for a varying-length string.

For that, you’ll need to use the FIND function to find your symbol.

Here is the structure of the FIND function:

Now let’s look at the steps to get all of your characters before the dash symbol:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
111-IDAA
2222222-IDB
33-IDCCC

(2) Then, type the following formula in cell B2:

Note that the “-1” at the end of the formula simply drops the dash symbol from your results (as we are only interested to keep the digits on the left without the dash symbol).

(3) As before, drag your formula from cell B2 to B4. Here are the results:

Identifier Result
111-IDAA 111
2222222-IDB 2222222
33-IDCCC 33

While you used the dash symbol in the above example, the above formula would also work for other symbols, such as $, % and so on.

Gel all characters before space (for a varying-length string )

But what if you have a space (rather than a symbol), and you only want to get all the characters before that space?

That would require a small modification to the formula you saw in the last section.

Specifically, instead of putting the dash symbol in the FIND function, simply leave an empty space within the quotations:

Let’s look at the full steps:

(1) To start, type/paste the following table into cells A1 to B4:

Identifier Result
111 IDAA
2222222 IDB
33 IDCCC

(2) Then, type the following formula in cell B2:

(3) Finally, drag the formula from cell B2 to B4:

Identifier Result
111 IDAA 111
2222222 IDB 2222222
33 IDCCC 33

Obtain all characters after a symbol (for a varying-length string )

There may be cases where you may need to get all of your desired characters after a symbol (for a varying-length string).

To do that, you may use the LEN function, which can provide you the total number of characters within a string. Here is the structure of the LEN function:

Let’s now review the steps to get all the digits, after the symbol of “-“, for varying-length strings:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
IDAA-111
IDB-2222222
IDCCC-33

(2) Secondly, type the following formula in cell B2:

(3) Finally, drag your formula from cell B2 to B4:

Identifier Result
IDAA-111 111
IDB-2222222 2222222
IDCCC-33 33

Obtain all characters between two symbols (for a varying-length string)

Last, but not least, is a scenario where you may need to get all of your desired characters between two symbols (for a varying-length string).

In order to accomplish this task, you can apply a mix of some of the concepts we already covered earlier.

Let’s now look at the steps to retrieve only the digits between the two symbols of dash “-“:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
IDAA-111-AA
IDB-2222222-B
IDCCC-33-CCC

(2) Then, type the following formula in cell B2:

(3) And finally, drag your formula from cell B2 to B4:

Identifier Result
IDAA-111-AA 111
IDB-2222222-B 2222222
IDCCC-33-CCC 33

Excel String Functions – Summary

Excel string functions can be used to retrieve specific characters within a string.

You just saw how to apply Excel string functions across multiple scenarios. You can use any of the concepts above, or a mixture of the techniques described, in order to get your desired characters within a string.

Источник

VBA Text and String Functions in Excel

VBA Text and String Functions help us to search and manipulate data. These are Asc, Chr, Format, InStr, InStrRev, LCase, Left, Len, LTrim, Mid, Replace, Right, RTrim, Space, Split, Str, String, StrComp, StrConv, StrReverse, Trim, UCase, etc. These functions are Built-In functions. We can use these VBA Text and String functions in either procedure or function. These functions we use in the VBA editor window in Excel. These Text and String functions you can use any number of times in VBA macro codes.

List of Text and String Functions in Excel VBA:

Here are the list of Text and String functions. And also find its description, syntax and return type. We can use these multiple Text and String functions in one statement.

Function Description Syntax Return Type
VBA Asc VBA ASC function returns the ASCII value of the first character from a string. Asc(String) Integer
VBA Chr VBA Chr function returns a character of the ASCII value. Chr(CharCode) String
VBA Format VBA Format function returns a formatted string from a string expression. Format(Expression, [Format], [FirstDayOfWeek],[FirstWeekOfYear]) String
VBA InStr VBA InStr function returns the position of a substring within a string. InStr([start], string, substring, [compare]) Long
VBA InStrRev VBA InStrRev function returns the position of a substring within a string, searching from right to left. InStrRev(StringCheck, StringMatch, [Start], [Compare]) Long
VBA LCase VBA LCase function converts a string to lowercase text. LCase(String) String
VBA Left VBA Left function returns the specified number of characters from a given string, starting from the left most character. Left(string, [length]) String
VBA Len VBA Len function returns the length of a given string. Len(Expression) Integer
VBA LTrim VBA LTrim function removes leading spaces from a given string. LTrim(String) String
VBA Mid VBA Mid function returns a specified number of characters from a specified string. Mid(String, Start, [Length]) String
VBA Replace VBA Replace function replaces a substring with another string in a given string. Replace(Expression, Find, Replace, [Start], [Count], [Compare]) String
VBA Right VBA Right function returns the specified number of characters from a given string, starting from the right most character. Right(string, [length]) String
VBA RTrim VBA RTrim function removes trailing spaces from a given string. RTrim(String) String
VBA Space VBA Space function returns a string with a specified number of spaces. Space(Number) String
VBA Split VBA Split function returns an array of substrings based on a delimiter. Split(Expression, [Delimiter], [Limit], [Compare]) String
VBA Str VBA Str function returns a string which represents a number. Str(Number) String
VBA String VBA String function returns a string which consists of repeated characters. String(Number, Character) String
VBA StrComp VBA StrComp function returns an integer value representing the result of string comparision. StrComp(String1, String2, [Compare]) Integer
VBA StrConv VBA StrConv function converts a string to a specified format(vbUpperCase, vbLowerCase, vbUnicode, vbWide, vbNarrow, vbProperCase, etc.) StrConv(String, Conversion, [LocaleID]) String
VBA StrReverse VBA StrReverse function reverses a given string. StrReverse(Expression) String
VBA Trim VBA Trim function removes leading and trailing spaces from a given string. Trim(String) String
VBA UCase VBA UCase function converts a string to uppercase text. UCase(String) String

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

Need to retrieve specific characters from a string in Excel? If so, in this guide, you’ll see how to use the Excel string functions to obtain your desired characters within a string.

Specifically, you’ll observe how to apply the following Excel string functions using practical examples:

Excel String Functions Used Description of Operation
LEFT Get characters from the left side of a string
RIGHT Get characters from the right side of a string
MID Get characters from the middle of a string
LEFT, FIND Get all characters before a symbol
LEFT, FIND Get all characters before a space
RIGHT, LEN, FIND Get all characters after a symbol
MID, FIND Get all characters between two symbols

Excel String Functions: LEFT, RIGHT, MID, LEN and FIND

To start, let’s say that you stored different strings in Excel. These strings may contain a mixture of:

  • Letters
  • Digits
  • Symbols (such as a dash symbol “-“)
  • Spaces

Now, let’s suppose that your goal is to isolate/retrieve only the digits within those strings.

How would you then achieve this goal using the Excel string functions?

Let’s dive into few examples to see how you can accomplish this goal.

Retrieve a specific number of characters from the left side of a string

In the following example, you’ll see three strings. Each of those strings would contain a total of 9 characters:

  • Five digits starting from the left side of the string
  • One dash symbol (“-“)
  • Three letters at the end of the string

As indicated before, the goal is to retrieve only the digits within the strings.

How would you do that in Excel?

Here are the steps:

(1) First, type/paste the table below into Excel, within the range of cells A1 to B4 (to keep things simple across all the examples to come, the tables to be typed/pasted into Excel, should be stored in the range of cells A1 to B4):

Identifier Result
55555-End
77777-End
99999-End

Since the goal is to retrieve the first 5 digits from the left, you’ll need to use the LEFT formula, which has the following structure:

=LEFT(Cell where the string is located, Number of characters needed from the Left)

(2) Next, type the following formula in cell B2:

=LEFT(A2,5)

(3) Finally, drag the LEFT formula from cell B2 to B4 in order to get the results across your 3 records.

This is how your table would look like in Excel after applying the LEFT formula:

Identifier Result
55555-End 55555
77777-End 77777
99999-End 99999

Retrieve a specific number of characters from the right side of a string

Wait a minute! what if your digits are located on the right-side of the string?

Let’s look at the opposite case, where you have your digits on the right-side of a string.

Here are the steps that you’ll need to follow in order to retrieve those digits:

(1) Type/paste the following table into cells A1 to B4:

Identifier Result
ID-55555
ID-77777
ID-99999

Here, you’ll need to use the RIGHT formula that has the following structure:

=RIGHT(Cell where the string is located, Number of characters needed from the Right)

(2) Then, type the following formula in cell B2:

=RIGHT(A2,5)

(3) Finally, drag your RIGHT formula from cell B2 to B4.

This is how the table would look like after applying the RIGHT formula:

Identifier Result
ID-55555 55555
ID-77777 77777
ID-99999 99999

Get a specific number of characters from the middle of a string

So far you have seen cases where the digits are located either on the left-side, or the right-side, of a string.

But what if the digits are located in the middle of the string, and you’d like to retrieve only those digits?

Here are the steps that you can apply:

(1) Type/paste the following table into cells A1 to B4:

Identifier Result
ID-55555-End
ID-77777-End
ID-99999-End

Here, you’ll need to use the MID formula with the following structure:

=MID(Cell of string, Start position of first character needed, Number of characters needed)

(2) Now type the following formula in cell B2:

=MID(A2,4,5)

(3) Finally, drag the MID formula from cell B2 to B4.

This is how the table would look like:

Identifier Result
ID-55555-End 55555
ID-77777-End 77777
ID-99999-End 99999

In the subsequent sections, you’ll see how to retrieve your desired characters from strings of varying lengths.

Gel all characters before a symbol (for a varying-length string)

Ready to get more fancy?

Let’s say that you have your desired digits on the left side of a string, BUT the number of digits on the left side of the string keeps changing.

In the following example, you’ll see how to retrieve all the desired digits before a symbol (e.g., the dash symbol “-“) for a varying-length string.

For that, you’ll need to use the FIND function to find your symbol.

Here is the structure of the FIND function:

=FIND(the symbol in quotations that you'd like to find, the cell of the string)

Now let’s look at the steps to get all of your characters before the dash symbol:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
111-IDAA
2222222-IDB
33-IDCCC

(2) Then, type the following formula in cell B2:

=LEFT(A2,FIND("-",A2)-1)

Note that the “-1” at the end of the formula simply drops the dash symbol from your results (as we are only interested to keep the digits on the left without the dash symbol).

(3) As before, drag your formula from cell B2 to B4. Here are the results:

Identifier Result
111-IDAA 111
2222222-IDB 2222222
33-IDCCC 33

While you used the dash symbol in the above example, the above formula would also work for other symbols, such as $, % and so on.

Gel all characters before space (for a varying-length string )

But what if you have a space (rather than a symbol), and you only want to get all the characters before that space?

That would require a small modification to the formula you saw in the last section.

Specifically, instead of putting the dash symbol in the FIND function, simply leave an empty space within the quotations:

FIND(" ",A2)

Let’s look at the full steps:

(1) To start, type/paste the following table into cells A1 to B4:

Identifier Result
111 IDAA
2222222 IDB
33 IDCCC

(2) Then, type the following formula in cell B2:

=LEFT(A2,FIND(" ",A2)-1)

(3) Finally, drag the formula from cell B2 to B4:

Identifier Result
111 IDAA 111
2222222 IDB 2222222
33 IDCCC 33

Obtain all characters after a symbol (for a varying-length string )

There may be cases where you may need to get all of your desired characters after a symbol (for a varying-length string).

To do that, you may use the LEN function, which can provide you the total number of characters within a string. Here is the structure of the LEN function:

=LEN(Cell where the string is located)

Let’s now review the steps to get all the digits, after the symbol of “-“, for varying-length strings:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
IDAA-111
IDB-2222222
IDCCC-33

(2) Secondly, type the following formula in cell B2:

=RIGHT(A2,LEN(A2)-FIND("-",A2))

(3) Finally, drag your formula from cell B2 to B4:

Identifier Result
IDAA-111 111
IDB-2222222 2222222
IDCCC-33 33

Obtain all characters between two symbols (for a varying-length string)

Last, but not least, is a scenario where you may need to get all of your desired characters between two symbols (for a varying-length string).

In order to accomplish this task, you can apply a mix of some of the concepts we already covered earlier.

Let’s now look at the steps to retrieve only the digits between the two symbols of dash “-“:

(1) First, type/paste the following table into cells A1 to B4:

Identifier Result
IDAA-111-AA
IDB-2222222-B
IDCCC-33-CCC

(2) Then, type the following formula in cell B2:

=MID(A2,FIND("-",A2)+1,FIND("-",A2,FIND("-",A2)+1)-FIND("-",A2)-1)

(3) And finally, drag your formula from cell B2 to B4:

Identifier Result
IDAA-111-AA 111
IDB-2222222-B 2222222
IDCCC-33-CCC 33

Excel String Functions – Summary

Excel string functions can be used to retrieve specific characters within a string.

You just saw how to apply Excel string functions across multiple scenarios. You can use any of the concepts above, or a mixture of the techniques described, in order to get your desired characters within a string.

На чтение 23 мин. Просмотров 18.4k.

VBA String Functions

Содержание

  1. Краткое руководство по текстовым функциям
  2. Введение
  3. Прочитайте это в первую очередь!
  4. Добавление строк
  5. Извлечение части строки
  6. Поиск в строке
  7. Удаление пробелов
  8. Длина строки
  9. Перевернуть текст
  10. Сравнение
  11. Сравнение строк с использованием сопоставления с шаблоном
  12. Заменить часть строки
  13. Преобразовать типы в строку (базовый)
  14. Преобразовать строку в число — CLng, CDbl, Val и т.д.
  15. Генерация строки элементов — функция строки
  16. Преобразовать регистр / юникод — StrConv, UCase, LCase
  17. Использование строк с массивами
  18. Форматирование строки
  19. Заключение

Краткое руководство по текстовым функциям

Текстовые операции Функции
Добавить две или более строки Format or «&»
Построить текст из массива Join
Сравнить StrComp or «=»
Сравнить — шаблон Like
Преобразовать в текст CStr, Str
Конвертировать текст в дату Просто: CDate 
Дополнительно: Format
Преобразовать текст в число Просто: CLng, CInt, CDbl, Val
Дополнительно: Format
Конвертировать в юникод, широкий, узкий StrConv
Преобразовать в верхний / нижний регистр StrConv, UCase, LCase
Извлечь часть текста Left, Right, Mid
Форматировать текст Format
Найти символы в тексте InStr, InStrRev
Генерация текста String
Получить длину строки Len
Удалить пробелы LTrim, RTrim, Trim
Заменить часть строки Replace
Перевернуть строку StrReverse
Разобрать строку в массив Split

Введение

Использование строк является очень важной частью VBA. Есть много типов манипуляций, которые вы можете делать со строками. К ним относятся такие задачи, как:

  • извлечение части строки
  • сравнение строк
  • преобразование чисел в текст
  • форматирование даты для включения дня недели
  • найти символ в строке
  • удаление пробелов
  • парсинг в массив
  • и т. д.  

Хорошей новостью является то, что VBA содержит множество функций, которые помогут вам легко выполнять эти задачи.

Эта статья содержит подробное руководство по использованию строки в VBA. Он объясняет строки в простых терминах с понятными примерами кода. Изложение в статье поможет легко использовать ее в качестве краткого справочного руководства.

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

Прочитайте это в первую очередь!

Следующие два пункта очень важны при работе со строковыми функциями VBA.

Исходная строка не изменяется

Важно помнить, что строковые функции VBA не изменяют исходную строку. Они возвращают новую строку с изменениями, внесенными функцией. Если вы хотите изменить исходную строку, вы просто назначаете результат исходной строке. См. Раздел «Извлечение части строки» для примеров.

Как использовать Compare

Некоторые строковые функции, такие как StrComp (), Instr () и т.д. имеют необязательный параметр Compare. Он работает следующим образом:

vbTextCompare: верхний и нижний регистры считаются одинаковыми

vbBinaryCompare: верхний и нижний регистр считаются разными

Следующий код использует функцию сравнения строк StrComp () для демонстрации параметра Compare.

Sub Comp1()

    ' Печатает 0  : Строки совпадают
    Debug.Print StrComp("АБВ", "абв", vbTextCompare)
    ' Печатает -1 : Строки не совпадают
    Debug.Print StrComp("АБВ", "абв", vbBinaryCompare)

End Sub

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

  • Oпция Compare Text: делает vbTextCompare аргументом сравнения по умолчанию
Option Compare Text

Sub Comp2()
    ' Соответствие строк - использует vbCompareText в качестве 'аргумента сравнения
    Debug.Print StrComp("АБВ", "абв")
    Debug.Print StrComp("ГДЕ", "где")
End Sub
  • Опция Compare Binary: делает vbBinaryCompare аргументом сравнения по умолчанию.
Option Compare Binary

Sub Comp2()
    ' Строки не совпадают - использует vbCompareBinary в качестве 'аргумента сравнения
    Debug.Print StrComp("АБВ", "абв")
    Debug.Print StrComp("ГДЕ", "где")
End Sub

Если Option Compare не используется, то по умолчанию используется Option Compare Binary.

Теперь, когда вы понимаете эти два важных момента о строке, мы можем продолжить и посмотреть на строковые функции индивидуально.

Добавление строк

VBA String Functions - Smaller

Вы можете добавлять строки, используя оператор &. Следующий код показывает несколько примеров его использования.

Sub Dobavlenie()

    Debug.Print "АБВ" & "ГДЕ"
    Debug.Print "Иван" & " " & "Петров"
    Debug.Print "Длинный " & 22
    Debug.Print "Двойной " & 14.99
    Debug.Print "Дата " & #12/12/2015#

End Sub

В примере вы можете видеть, что различные типы, такие как даты и числа, автоматически преобразуются в строки. Вы можете увидеть оператор +, используемый для добавления строк. Разница в том, что этот оператор будет работать только со строковыми типами. Если вы попытаетесь использовать его с другим типом, вы получите ошибку.

 Это даст сообщение об ошибке: «Несоответствие типов»
    Debug.Print "Длинный " + 22

Если вы хотите сделать более сложное добавление строк, вы можете использовать функцию форматирования, описанную ниже.

Извлечение части строки

Функции, обсуждаемые в этом разделе, полезны при базовом извлечении из строки. Для чего-то более сложного можете посмотреть раздел, как легко извлечь любую строку без использования VBA InStr.

Функция Параметры Описание Пример
Left строка, длина Вернуть
символы с
левой стороны
Left(«Иван
Петров»,4)
Right строка, длина Вернуть
символы с
правой
стороны
Right(«Иван
Петров»,5)
Mid строка, начало, длина Вернуть
символы из
середины
Mid(«Иван
Петров»,3,2)

Функции Left, Right и Mid используются для извлечения частей строки. Это очень простые в использовании функции. Left читает символы слева, Right справа и Mid от указанной вами начальной точки.

Sub IspLeftRightMid()

    Dim sCustomer As String
    sCustomer = "Иван Васильевич Петров"

    Debug.Print Left(sCustomer, 4)  '  Печатает: Иван
    Debug.Print Right(sCustomer, 6) '  Печатает: Петров

    Debug.Print Left(sCustomer, 15)  '  Печатает: Иван Васильевич
    Debug.Print Right(sCustomer, 17)  '  Печатает: Васильевич Петров

    Debug.Print Mid(sCustomer, 1, 4) ' Печатает: Иван
    Debug.Print Mid(sCustomer, 6, 10) ' Печатает: Васильевич
    Debug.Print Mid(sCustomer, 17, 6) ' Печатает: Петров

End Sub

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

В следующем примере вы увидите, что строка Fullname не была изменена после использования функции Left.

Sub PrimerIspolzovaniyaLeft()

    Dim Fullname As String
    Fullname = "Иван Петров"

    Debug.Print "Имя: "; Left(Fullname, 4)
    ' Исходная строка не изменилась
    Debug.Print "Полное имя: "; Fullname

 End Sub

Если вы хотите изменить исходную строку, вы просто присваиваете ей возвращаемое значение функции.

Sub IzmenenieStroki()

    Dim name As String
    name = "Иван Петров"

    ' Присвойте возвращаемую строку переменной имени
    name = Left(name, 4)

    Debug.Print "Имя: "; name

 End Sub

Поиск в строке

Функция Параметры Описание Пример
InStr Текст1,
текст2
Находит
положение
текста
InStr(«Иван
Петров»,»в»)
InStrRev Проверка
текста,
соответствие
текста
Находит
позицию
текста с конца
InStrRev(«Иван Петров»,»в»)

InStr и InStrRev — это функции VBA, используемые для поиска текста в тексте. Если текст поиска найден, возвращается позиция (с начала строки проверки) текста поиска. Когда текст поиска не найден, возвращается ноль. Если какой-либо текст имеет значение null, возвращается значение null.

InStr Описание параметров

InStr() Start[Необязат], String1, String2, Compare[Необязат]

  • Start [Необязательно — по умолчанию 1]: это число, указывающее начальную позицию поиска слева
  • String1: текст, в котором будем искать
  • String2: текст, который будем искать
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование InStr и примеры

InStr возвращает первую позицию в тексте, где найден данный текст. Ниже приведены некоторые примеры его использования.

Sub PoiskTeksta()

    Dim name As String
    name = "Иван Петров"

    ' Возвращает 3 - позицию от первой 
    Debug.Print InStr(name, "а")
    ' Возвращает 10 - позиция первого "а", начиная с позиции 4
    Debug.Print InStr(4, name, "а")
    ' Возвращает 8
    Debug.Print InStr(name, "тр")
    ' Возвращает 6
    Debug.Print InStr(name, "Петров")
    ' Возвращает 0 - текст "ССС" не найдет
    Debug.Print InStr(name, "ССС")

End Sub

InStrRev Описание параметров

InStrRev() StringCheck, StringMatch, Start[Необязат], Compare[Необязат]

  • StringCheck: текст, в котором будем искать
  • StringMatch: Текст, который будем искать
  • Start [Необязательно — по умолчанию -1]: это число, указывающее начальную позицию поиска справа
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование InStrRev и примеры

Функция InStrRev такая же, как InStr, за исключением того, что она ищет с конца строки. Важно отметить, что возвращаемая позиция является позицией с самого начала. Поэтому, если существует только один экземпляр элемента поиска, InStr () и InStrRev () будут возвращать одно и то же значение.

В следующем коде показаны некоторые примеры использования InStrRev.

Sub IspInstrRev()

    Dim name As String
    name = "Иван Петров"

    ' Обе возвращают 1 - позицию, только И
    Debug.Print InStr(name, "И")
    Debug.Print InStrRev(name, "И")

    ' Возвращает 11 - вторую в
    Debug.Print InStrRev(name, "в")
    ' Возвращает 3 - первую в с позиции 9
    Debug.Print InStrRev(name, "в", 9)

    ' Returns 1
    Debug.Print InStrRev(name, "Иван")

End Sub

Функции InStr и InStrRev полезны при работе с базовым поиском текста. Однако, если вы собираетесь использовать их для извлечения текста из строки, они могут усложнить задачу. Я написал о гораздо лучшем способе сделать это в своей статье Как легко извлечь любой текст без использования VBA InStr.

Удаление пробелов

Функция Параметры Описание Пример
LTrim Текст Убирает
пробелы слева
LTrim(» Иван «)
RTrim Текст Убирает
пробелы
справа
RTrim(» Иван «)
Trim Текст Убирает
пробелы слева и справа
Trim(» Иван «)

Функции Trim — это простые функции, которые удаляют пробелы в начале или конце строки.

Функции и примеры использования триммера Trim

  • LTrim удаляет пробелы слева от строки
  • RTrim удаляет пробелы справа от строки
  • Trim удаляет пробелы слева и справа от строки
Sub TrimStr()

    Dim name As String
    name = "  Иван Петров  "

    ' Печатает "Иван Петров  "
    Debug.Print LTrim(name)
    ' Печатает "  Иван Петров"
    Debug.Print RTrim(name)
    ' Печатает "Иван Петров"
    Debug.Print Trim(name)

End Sub

Длина строки

Функция Параметры Описание Пример
Len Текст Возвращает
длину строки
Len («Иван Петров»)

Len — простая функция при использовании со строкой. Она просто возвращает количество символов, которое содержит строка. Если используется с числовым типом, таким как long, он вернет количество байтов.

Sub IspLen()

    Dim name As String
    name = "Иван Петров"

    ' Печатает 11
    Debug.Print Len("Иван Петров")
    ' Печатает 3
    Debug.Print Len("АБВ")

    ' Печатает 4 с Long - это размер 4 байта
    Dim total As Long
    Debug.Print Len(total)

End Sub

Перевернуть текст

Функция Параметры Описание Пример
StrReverse Текст Перевернуть
текст
StrReverse
(«Иван
Петров»)

StrReverse — еще одна простая в использовании функция. Он просто возвращает данную строку с обратными символами.

Sub RevStr()

    Dim s As String
    s = "Иван Петров"
    ' Печатает: вортеП навИ
    Debug.Print StrReverse(s)

End Sub

Сравнение

Функция Параметры Описание Пример
StrComp Текст1, текст2 Сравнивает 2
текста
StrComp
(«Иван»,
«Иван»)

Функция StrComp используется для сравнения двух строк. Следующие подразделы описывают, как используется.

Описание параметров

StrComp()  String1, String2, Compare[Необязат]

  • String1: первая строка для сравнения
  • String2: вторая строка для сравнения
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

StrComp Возвращаемые значения

Возвращаемое значение Описание
0 Совпадение строк
-1 строка1 меньше строки2
1 строка1 больше строки2
Null если какая-либо строка равна нулю

Использование и примеры

Ниже приведены некоторые примеры использования функции StrComp.

Sub IspStrComp()

   ' Возвращает  0
   Debug.Print StrComp("АБВ", "АБВ", vbTextCompare)
   ' Возвращает 1
   Debug.Print StrComp("АБВГ", "АБВ", vbTextCompare)
   ' Возвращает -1
   Debug.Print StrComp("АБВ", "АБВГ", vbTextCompare)
   ' Returns Null
   Debug.Print StrComp(Null, "АБВГ", vbTextCompare)

End Sub

Сравнение строк с использованием операторов

Вы также можете использовать знак равенства для сравнения строк. Разница между сравнением equals и функцией StrComp:

  1. Знак равенства возвращает только true или false.
  2. Вы не можете указать параметр Compare, используя знак равенства — он использует настройку «Option Compare».  

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

Option Compare Text

Sub CompareIspEquals()

    ' Возвращает true
    Debug.Print "АБВ" = "АБВ"
    ' Возвращает true, потому что «Сравнить текст» установлен выше
    Debug.Print "АБВ" = "абв"
    ' Возвращает false
    Debug.Print "АБВГ" = "АБВ"
    ' Возвращает false
    Debug.Print "АБВ" = "АБВГ"
    ' Возвращает null
    Debug.Print Null = "АБВГ"

End Sub

Сравнение строк с использованием сопоставления с шаблоном

Функция Параметры Описание Пример
Like Текст, шаблон проверяет, имеет
ли строка
заданный
шаблон
«abX» Like «??X»
«54abc5» Like «*abc#»
Знак Значение
? Любой одиночный символ
# Любая однозначная цифра (0-9)
* Ноль или более символов
[charlist] Любой символ в списке
[!charlist] Любой символ не в списке символов

Сопоставление с шаблоном используется для определения того, имеет ли строка конкретный образец символов. Например, вы можете проверить, что номер клиента состоит из 3 цифр, за которыми следуют 3 алфавитных символа, или в строке есть буквы XX, за которыми следует любое количество символов.

Если строка соответствует шаблону, возвращаемое значение равно true, в противном случае — false.

Сопоставление с образцом аналогично функции формата VBA в том смысле, что его можно использовать практически безгранично. В этом разделе я приведу несколько примеров, которые объяснят, как это работает. Это должно охватывать наиболее распространенные виды использования.

Давайте посмотрим на базовый пример с использованием знаков. Возьмите следующую строку шаблона.

[abc][!def]?#X*

 Давайте посмотрим, как работает эта строка

[abc] — символ, который является или a, b или c
[! def] — символ, который не является d, e или f
? любой символ
# — любая цифра
X — символ X
* следуют ноль или более символов

 Поэтому следующая строка действительна
apY6X

а — один из символов a,b,c
p — не один из символов d, e или f
Y — любой символ
6 — это цифра
Х — это буква Х

В следующих примерах кода показаны результаты различных строк с этим шаблоном.

Sub Shabloni()

    ' ИСТИНА
    Debug.Print 1; "apY6X" Like "[abc][!def]?#X*"
    ' ИСТИНА - любая комбинация символов после x действительна
    Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - символ не из[abc]
    Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - 2-й символ e находится в [def]
    Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - A в позиции 4 не является цифрой
    Debug.Print 5; "apYAX" Like "[abc][!def]?#X*"
    ' ЛОЖЬ - символ в позиции 5 должен быть X
    Debug.Print 1; "apY6Z" Like "[abc][!def]?#X*"

End Sub

Реальный пример сопоставления с образцом

Чтобы увидеть реальный пример использования сопоставления с образцом, ознакомьтесь с Примером 3: Проверьте, допустимо ли имя файла.

Важное примечание о сопоставлении с образцом VBA

Оператор Like использует двоичное или текстовое сравнение на основе параметра Option Compare. Пожалуйста, смотрите раздел Сравнение для более подробной информации.

Заменить часть строки

Функция Параметры Описание Пример
Replace строка, найти, заменить,
начать,
считать,
сравнивать
Заменяет текст Replace
(«Ива»,»а»,»ан»)

Replace используется для замены текста в строке другим текстом. Он заменяет все экземпляры текста, найденные по умолчанию.

Replace описание параметров

Replace()  Expression, Find, Replace, Start[Необязат], Count[Необязат], Compare[Необязат]

  • Expression: текст, в котором нужна замена символов
  • Find: текст для замены в строке выражения
  • Replace: строка для поиска замены текста поиска
  • Start [Необязательно — по умолчанию 1]: начальная позиция в строке
  • Count [Необязательно — по умолчанию -1]: количество замен. По умолчанию -1 означает все.
  • Compare как vbCompareMethod: см. Раздел «Сравнить» для получения более подробной информации.

Использование и примеры

В следующем коде показаны некоторые примеры использования функции замены.

Sub PrimeriReplace()

    ' Заменяет все знаки вопроса (?) на точку с запятой (;)
    Debug.Print Replace("A?B?C?D?E", "?", ";")
    ' Заменить Петров на Иванов
    Debug.Print Replace("Евгений Петров,Артем Петров", "Петров", "Иванов")
    ' Заменить AX на AB
    Debug.Print Replace("ACD AXC BAX", "AX", "AB")

End Sub

На выходе:

A;B;C;D;E
Евгений Иванов,Артем Иванов
ACD ABC BAB

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

Sub ReplaceCount()

    ' Заменяет только первый знак вопроса
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1)
    ' Заменяет первые три знака вопроса
    Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3)

End Sub

На выходе:

A;B?C?D?E
A;B;C;D?E

Необязательный параметр Start позволяет вам вернуть часть строки. Позиция, которую вы указываете с помощью Start, — это место, откуда начинается возврат строки. Он не вернет ни одной части строки до этой позиции, независимо от того, была ли произведена замена или нет.

Sub ReplacePartial()

    ' Использовать оригинальную строку из позиции 4
    Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4)
    ' Используйте оригинальную строку из позиции 8
    Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8)
    ' Элемент не заменен, но по-прежнему возвращаются только последние '2 символа
    Debug.Print Replace("ABCD", "X", "Y", Start:=3)

End Sub

На выходе:

;C;D;E
;E
CD

Иногда вы можете заменить только заглавные или строчные буквы. Вы можете использовать параметр Compare для этого. Он используется во многих строковых функциях. Для получения дополнительной информации об этом проверьте раздел сравнения.

Sub ReplaceCase()

    ' Заменить только заглавные А
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare)
    ' Заменить все А
    Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare)

End Sub

На выходе:

XaXa
XXXX

Многократные замены

Если вы хотите заменить несколько значений в строке, вы можете вкладывать вызовы. В следующем коде мы хотим заменить X и Y на A и B соответственно.

Sub ReplaceMulti()

    Dim newString As String

    ' Заменить А на Х
    newString = Replace("ABCD ABDN", "A", "X")
    ' Теперь замените B на Y в новой строке
    newString = Replace(newString, "B", "Y")

    Debug.Print newString

End Sub

В следующем примере мы изменим приведенный выше код для выполнения той же задачи. Мы будем использовать возвращаемое значение первой замены в качестве аргумента для второй замены.

Sub ReplaceMultiNested()

    Dim newString As String

    ' Заменить A на X, а B на Y
    newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y")

    Debug.Print newString

End Sub

Результатом обоих этих Subs является:
XYCD XYDN

Преобразовать типы в строку (базовый)

Этот раздел о преобразовании чисел в строку. Очень важным моментом здесь является то, что в большинстве случаев VBA автоматически конвертируется в строку для вас. Давайте посмотрим на некоторые примеры:

Sub AutoConverts()

    Dim s As String
    ' Автоматически преобразует число в строку
    s = 12.99
    Debug.Print s

    ' Автоматически преобразует несколько чисел в строку
    s = "ABC" & 6 & 12.99
    Debug.Print s

    ' Автоматически преобразует двойную переменную в строку
    Dim d As Double, l As Long
    d = 19.99
    l = 55
    s = "Значения: " & d & " " & l
    Debug.Print s

End Sub

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

Явное преобразование

Функция Параметры Описание Пример
CStr выражение Преобразует
числовую
переменную
в строку
CStr («45.78»)
Str число Преобразует
числовую
переменную
в строку
Str («45.78»)

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

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

Sub IspStr()

    Dim coll As New Collection
    Dim c As Range

    ' Считать значения ячеек в коллекцию
    For Each c In Range("A1:A10")
        ' Используйте Str для преобразования значения ячейки в строку
        coll.Add Str(c)
    Next

    ' Распечатайте значения и тип коллекции
    Dim i As Variant
    For Each i In coll
        Debug.Print i, TypeName(i)
    Next

End Sub

В приведенном выше примере мы используем Str для преобразования значения ячейки в строку. Альтернативой этому может быть присвоение значения строке, а затем присвоение строки коллекции. Итак, вы видите, что использование Str здесь намного эффективнее.

Multi Region

Разница между функциями Str и CStr заключается в том, что CStr преобразует в зависимости от региона. Если ваши макросы будут использоваться в нескольких регионах, вам нужно будет использовать CStr для преобразования строк.

Хорошей практикой является использование CStr при чтении значений из ячеек. Если ваш код в конечном итоге используется в другом регионе, вам не нужно вносить какие-либо изменения, чтобы он работал правильно.

Преобразовать строку в число — CLng, CDbl, Val и т.д.

Функция Возвращает Пример
CBool Boolean CBool(«True»), CBool(«0»)
CCur Currency CCur(«245.567»)
CDate Date CDate(«1/1/2019»)
CDbl Double CDbl(«245.567»)
CDec Decimal CDec(«245.567»)
CInt Integer CInt(«45»)
CLng Long Integer CLng(«45.78»)
CVar Variant CVar(«»)

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

Sub StrToNumeric()

    Dim l As Long, d As Double, c As Currency
    Dim s As String
    s = "45.923239"

    l = s
    d = s
    c = s

    Debug.Print "Long is "; l
    Debug.Print "Double is "; d
    Debug.Print "Currency is "; c

End Sub

Использование типов преобразования дает большую гибкость. Это означает, что вы можете определить тип во время выполнения. В следующем коде мы устанавливаем тип на основе аргумента sType, передаваемого в функцию PrintValue. Поскольку этот тип может быть прочитан из внешнего источника, такого как ячейка, мы можем установить тип во время выполнения. Если мы объявим переменную как Long, то при выполнении кода она всегда будет длинной.

Sub Test()
    ' Печатает  46
    PrintValue "45.56", "Long"
    ' Печатает 45.56
    PrintValue "45.56", ""
End Sub

Sub PrintValue(ByVal s As String, ByVal sType As String)

    Dim value

    ' Установите тип данных на основе строки типа
    If sType = "Long" Then
        value = CLng(s)
    Else
        value = CDbl(s)
    End If
    Debug.Print "Type is "; TypeName(value); value

End Sub

Если строка не является допустимым числом (т.е. Содержит символы, другие цифры), вы получаете ошибку «Несоответствие типов».

Sub InvalidNumber()

    Dim l As Long

    ' Даст ошибку несоответствия типов
    l = CLng("45A")

End Sub

Функция Val

Функция преобразует числовые части строки в правильный тип числа.

Val преобразует первые встреченные числа. Как только он встречает буквы в строке, он останавливается. Если есть только буквы, то в качестве значения возвращается ноль. Следующий код показывает некоторые примеры использования Val

Sub IspVal()

    ' Печатает 45
    Debug.Print Val("45 Новая улица")

    ' Печатает 45
    Debug.Print Val("    45 Новая улица")

    ' Печатает 0
    Debug.Print Val("Новая улица 45")

    ' Печатает 12
    Debug.Print Val("12 f 34")

End Sub

Val имеет два недостатка

  1. Не мультирегиональный — Val не распознает международные версии чисел, такие как запятые вместо десятичных. Поэтому вы должны использовать вышеуказанные функции преобразования, когда ваше приложение будет использоваться в нескольких регионах.
  2. Преобразует недопустимые строки в ноль — в некоторых случаях это может быть нормально, но в большинстве случаев лучше, если неверная строка вызывает ошибку. Затем приложение осознает наличие проблемы и может действовать соответствующим образом. Функции преобразования, такие как CLng, вызовут ошибку, если строка содержит нечисловые символы.

Генерация строки элементов — функция строки

Функция Параметры Описание Пример
String число, символ Преобразует
числовую
переменную
в строку
String (5,»*»)

Функция String используется для генерации строки повторяющихся символов. Первый аргумент — это количество повторений, второй аргумент — символ.

Sub IspString()

    ' Печатает: AAAAA
    Debug.Print String(5, "A")
    ' Печатает: >>>>>
    Debug.Print String(5, 62)
    ' Печатает: (((ABC)))
    Debug.Print String(3, "(") & "ABC" & String(3, ")")

End Sub

Преобразовать регистр / юникод — StrConv, UCase, LCase

Функция Параметры Описание Пример
StrConv строка,
преобразование, LCID
Преобразует
строку
StrConv(«abc»,vbUpperCase)

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

Sub ConvCase()

    Dim s As String
    s = "У Мэри был маленький ягненок"

    ' верхний
    Debug.Print UCase(s)
    Debug.Print StrConv(s, vbUpperCase)

    ' нижний
    Debug.Print LCase(s)
    Debug.Print StrConv(s, vbLowerCase)

    ' Устанавливает первую букву каждого слова в верхний регистр
    Debug.Print StrConv(s, vbProperCase)

End Sub

На выходе: 

У МЭРИ БЫЛ МАЛЕНЬКИЙ ЯГНЕНОК
У МЭРИ БЫЛ МАЛЕНЬКИЙ ЯГНЕНОК
у мэри был маленький ягненок
у мэри был маленький ягненок
У Мэри Был Маленький Ягненок

Другие преобразования

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

Постоянные Преобразует Значение
vbUpperCase 1 в верхний регистр
vbLowerCase 2 в нижнем регистре
vbProperCase 3 первая буква
каждого слова в
верхнем регистре
vbWide* 4 от узкого к
широкому
vbNarrow* 8 от широкого к
узкому
vbKatakana** 16 из Хираганы в
Катакану
vbHiragana 32 из Катаканы в
Хирагану
vbUnicode 64 в юникод
vbFromUnicode 128 из юникода

Использование строк с массивами

Функция Параметры Описание Пример
Split выражение,
разделитель,
ограничить,
сравнить
Разбирает
разделенную
строку в
массив
arr = Split(«A;B;C»,»;»)
Join исходный
массив,
разделитель
Преобразует
одномерный
массив в
строку
s = Join(Arr, «;»)

Строка в массив с использованием Split

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

Sub StrToArr()

    Dim arr() As String
    ' Разобрать строку в массив
    arr = Split("Иван,Анна,Павел,София", ",")

    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

На выходе:

Иван
Анна
Павел
София

Если вы хотите увидеть некоторые реальные примеры использования Split, вы найдете их в статье Как легко извлечь любую строку без использования VBA InStr.

Массив в строку, используя Join

Если вы хотите построить строку из массива, вы можете легко это сделать с помощью функции Join. По сути, это обратная функция Split. Следующий код предоставляет пример использования Join

Sub ArrToStr()

    Dim Arr(0 To 3) As String
    Arr(0) = "Иван"
    Arr(1) = "Анна"
    Arr(2) = "Павел"
    Arr(3) = "София"

    ' Построить строку из массива
    Dim sNames As String
    sNames = Join(Arr, ",")

    Debug.Print sNames

End Sub

На выходе:

Иван, Анна, Павел, София

Форматирование строки

Функция Параметры Описание Пример
Format выражение,
формат,
firstdayofweek,
firstweekofyear
Форматирует
строку
Format(0.5, «0.00%»)

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

Sub FormatDate()

    Dim s As String
    s = "31/12/2019 10:15:45"

    ' Печатает: 31 12 19
    Debug.Print Format(s, "DD MM YY")
    ' Печатает: Thu 31 Dec 2019
    Debug.Print Format(s, "DDD DD MMM YYYY")
    ' Печатает: Thursday 31 December 2019
    Debug.Print Format(s, "DDDD DD MMMM YYYY")
    ' Печатает: 10:15
    Debug.Print Format(s, "HH:MM")
    ' Печатает: 10:15:45 AM
    Debug.Print Format(s, "HH:MM:SS AM/PM")

End Sub

В следующих примерах представлены некоторые распространенные способы форматирования чисел.

Sub FormatNumbers()

    ' Печатает: 50.00%
    Debug.Print Format(0.5, "0.00%")
    ' Печатает: 023.45
    Debug.Print Format(23.45, "00#.00")
    ' Печатает: 23,000
    Debug.Print Format(23000, "##,000")
    ' Печатает: 023,000
    Debug.Print Format(23000, "0##,000")
    ' Печатает: $23.99
    Debug.Print Format(23.99, "$#0.00")

End Sub

Функция «Формат» — довольно обширная тема, и она может самостоятельно занять всю статью. Если вы хотите получить больше информации, то страница формата MSDN предоставляет много информации.

Полезный совет по использованию формата

Быстрый способ выяснить используемое форматирование — использовать форматирование ячеек на листе Excel. Например, добавьте число в ячейку. Затем щелкните правой кнопкой мыши и отформатируйте ячейку так, как вам нужно. Если вы довольны форматом, выберите «Пользовательский» в списке категорий слева. При выборе этого вы можете увидеть строку формата в текстовом поле типа. Это формат строки, который вы можете использовать в VBA.

VBA Format Function

Заключение

Практически в любом типе программирования вы потратите много времени на манипулирование строками. В этой статье рассматриваются различные способы использования строк в VBA.

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

Если вы новичок в строках в VBA, то я предлагаю вам ознакомиться с разделом «Прочтите это в первую очередь» перед использованием любой из функций.

For the convenience of working with text in Excel, there are text functions. They make it easy to process hundreds of lines at once. Let’s consider some of them on examples.



Examples with TEXT function in Excel

This function converts numbers to string in Excel. Syntax: value (numeric or reference to a cell with a formula that gives a number as a result); Format (to display the number in the form of text).

The most useful feature of the TEXT function is the formatting of numeric data for merging with text data. Excel «doesn’t understand» how to display numbers without using the function. The program just converts them to a basic format.

Let’s see an example. Let’s say you need to combine text in string with numeric values:

text in string with numeric.

Using an ampersand without a function TEXT produces an inadequate result:

inadequate result.

Excel returned the sequence number for the date and the general format instead of the monetary. The TEXT function is used to avoid this. It formats the values according to the user’s request.

TEXT.

The formula «for a date» now looks like this:

The second argument to the function is the format. Where to take the format line? Right-click on the cell with the value. Click on «Format Cells». In the opened window select «Custom». Copy the required «Type:» in the line. We paste the copied value in the formula.

Format Cells.

Let’s consider another example where this function can be useful. Add zeros at the beginning of the number. Excel will delete them if you enter it manually. Therefore, we introduce the formula:

introduce.

If you want to return the old numeric values (without zeros), then use the «—» operator:

operator.

Note that the values are now displayed in numerical format.



Text splitting function in Excel

Individual functions and their combinations allow you to distribute words from one cell to separate cells:

  • LEFT (Text, number of characters) displays the specified number of characters from the beginning of the cell;
  • RIGHT (Text, number of characters) returns a specified number of characters from the end of the cell;
  • SEARCH (Search text, range to search, start position) shows the position of the first occurrence of the searched character or line while viewing from left to right.

The line takes into account the position of each character when dividing the text. Spaces show the beginning or the end of the name you are looking for.

We will split the name, surname and patronymic name into different columns using the functions.

split.

The first line contains only the first and last names separated by a space. Formula for retrieving the name:

The function SEARCH is used to determine the second argument of the LEFT function (the number of characters). It finds a space in cell A2 starting from the left.

For a name, we use the same formula:

use the same formula.

Excel determines the number of characters for the RIGHT function using the SEARCH function. The LEN function «counts» the total length of the text. Then the number of characters up to the first space (found by SEARCH) is subtracted.

The formula for extracting the surname:

extracting.

Next formulas for extracting the surname is a bit different:

example.

These are five signs on the right. Embedded SEARCH functions search for the second and third spaces in a string. SEARCH («»;A7;1) finds the first space on the left (before the patronymic name). Add one (+1) to the result. We get the position with which we will search for the second space.

Part of the formula SEARCH(» «;A7;SEARCH(» «;A7;1)+1) finds the second space. This will be the final position of the patronymic.

Then the number of characters from the beginning of the line to the second space is subtracted from the total length of the line. The result is the number of characters to the right that you need to return.

Function for merging text in Excel

Use the ampersand (&) operator or the CONCATENATE function to combine values from several cells into one line.

For example, the values are located in different columns (cells):

example.

Put the cursor in the cell where the combined three values will be. Enter «=». Select the first cell and click on the keyboard «&» sign. Then enter the space character enclosed in quotation marks (» «). Enter again «&». Therefore, sequentially connect cells with symbols and spaces.

We get the combined values in one cell:

combined values in one cell.

Using the CONCATENATE function:

CONCATENATE.

You can add any sign or string to the final expression using quotation marks in the formula.

Text SEARCH function in Excel

The SEARCH function returns the starting position of the searched text (not case sensitive). For example:

SEARCH.

The SEARCH returned to position 8 because the word «Drew» begins with the tenth character in the line. Where can this be useful?

The SEARCH function determines the position of the character in the string line. And the MID function returns symbols values (see the example above). Alternatively, you can replace the found text with the REPLACE.

syntax.

Download example TEXT functions

The syntax of the SEARCH function:

  • «Find_text» is what you need to find;
  • «Withing_text» is where to look;
  • «Start_num» is from which position to start searching (by default it is 1).

Use the FIND if you need to take into account the case (lower and upper).

Понравилась статья? Поделить с друзьями:
  • Excel and show formulas
  • Excel and sheet name
  • Excel and select all
  • Excel and runtime error
  • Excel and round function