Working with strings in excel

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

Содержание

  1. VBA Strings in Excel
  2. Declaration of String
  3. Assigning String value
  4. Concatenation
  5. String Manipulation
  6. LCase()
  7. UCase()
  8. Replace()
  9. StrReverse()
  10. Substring Functions
  11. Right()
  12. Length and Position
  13. InStr()
  14. Excel string functions: An introduction
  15. Using functions on strings
  16. Save an hour of work a day with these 5 advanced Excel tricks
  17. Excel String (Text) Functions
  18. 1. LEN Function
  19. Syntax
  20. Arguments
  21. Example
  22. 2. FIND Function
  23. Syntax
  24. Arguments
  25. Example
  26. 3. SEARCH Function
  27. Syntax
  28. Arguments
  29. Example
  30. 4. LEFT Function
  31. Syntax
  32. Arguments
  33. Example
  34. 5. RIGHT Function
  35. Syntax
  36. Arguments
  37. Example
  38. Arguments
  39. 6. MID Function
  40. Syntax
  41. Arguments
  42. Example
  43. 7. LOWER Function
  44. Syntax
  45. Arguments
  46. Example
  47. 8. PROPER Function
  48. Syntax
  49. Arguments
  50. Example
  51. 9. UPPER Function
  52. Syntax
  53. Arguments
  54. Example
  55. 10. REPT Function
  56. Syntax
  57. Example

VBA Strings in Excel

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

Declaration of String

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

Assigning String value

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

Concatenation

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

String Manipulation

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

LCase()

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

Syntax of the function: LCase(input_string)

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

UCase()

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

Syntax of the function: UCase(input_string)

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

Replace()

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

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

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

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

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

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

StrReverse()

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

Syntax of the function: StrReverse(input_string)

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

Substring Functions

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

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

Syntax of the function: Left(input_string, number)

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

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

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

Right()

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

Syntax of the function: Right(input_string, number)

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

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

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

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

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

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

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

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

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

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

Length and Position

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

Syntax of the function: Len(input_string)

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

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

InStr()

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

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

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

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

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

Источник

Excel string functions: An introduction

«String functions» refers to the category of functions in Excel that allow you to manipulate blocks of text in various ways. But before we dive into what string functions are and how they operate, let’s define what we mean by «string».

In Excel, there are three types of inputs that we can use within formulas:

  • Numbers are digits typed in directly on the keyboard. You can type numbers directly into the formula bar and use them as part of calculations, like the simple calculation =4+6 , which outputs the number 10 .
  • Strings are blocks of text that appear in Excel, like names of people, names of cities, e-mail addresses, or names of items sold in a store. When we type strings into Excel, we always use quotation marks around them to tell Excel that what it’s about to read is one coherent block of text. For example, if we want to use the name «Sarah Smith» in a formula, we enclose it in quotes ( «Sarah Smith» ).
  • Cell references point to the contents of other cells (which contain numbers or strings). Cell references come in the format [ column_letter ][ row_number ], like C5 . If a cell reference points to a cell containing a string, the cell reference can be used as a string in a formula. Likewise, if a cell reference points to a cell containing a number, the cell reference can be used as a number in a formula.

We enclose strings in quotes to differentiate between strings and cell references; Excel needs to know which of these two different input types we are dealing with when it reads our formulas.

Also, note that we only need to enclose strings in quotes if they come in a formula led by an equals sign ( = ). If you type a static string — one that is not used in a larger formula — into Excel, the program is smart enough to realize that you are inputting a string and treat it as such.

Using functions on strings

Now that we know what a string is, we have a better idea of what a «string function» is: a function designed to manipulate strings in various ways. There are numerous useful string functions, but they all take strings as one or more arguments to accomplish a variety of goals. Using string functions, you can:

  • Combine two strings together into one larger string (e.g., put a user’s name and domain together to form an e-mail address);
  • Pull out important details of a string into a separate cell (e.g., isolate just the state abbreviation in a city, state combination);
  • Split up strings based on a common delimiter (e.g., separate out a user’s e-mail prefix from his or her domain name);
  • Cut down a string so that only the important parts are passed on to another function (e.g., pull out just a user’s last name based on an input cell containing his or her full name);
  • And much more.

Check out our complete list of string functions to start learning about these useful tools.

Save an hour of work a day with these 5 advanced Excel tricks

Work smarter, not harder. Sign up for our 5-day mini-course to receive must-learn lessons on getting Excel to do your work for you.

  • How to create beautiful table formatting instantly.
  • Why to rethink the way you do VLOOKUPs.
  • Plus, we’ll reveal why you shouldn’t use PivotTables and what to use instead.

Источник

Excel String (Text) Functions

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

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.

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

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

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

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

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.

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

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.

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.

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

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.

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.

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

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.

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

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.

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

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.

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

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

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.

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

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.

Источник

More on the Excel String Functions

Excel has an array of string functions which are helpful in managing data. In this article we will look at how to extract strings from other strings:

So in the above we want to extract the middle word in each string e.g BLUE in the phrase “BIG BLUE SHIRT”. Once again we will go step by step . The key to this to find the position of the two spaces either side of the middle word.

The FIND function can be used to Find a position of a string within another string:

FIND(Search String, Source String, Starting Position)

So if we are looking for the space in the phrase “BIG BLUE SHIRT” (which is in cell A5) we enter the following in Cell C5:

C5 = FIND(“ “,A5,1)

And copying this down over all the strings we have:

Now we can use the position of first space to as an argument in another FIND function –

E5 = FIND(“ “,A5,C5+1)

Where we have added 1 to the value in the position of the first space so that we start at the next character:

The function MID allows us to extract a substring – providing we specify how many characters we want and the starting position:

G5 = MID(String, Starting Position, No of Characters)

So if we wanted to extract the 4-6th characters from the word “wonderful” -we would have:

MID(“Wonderful”,4,3)

So the now we have position of the first and second spaces we have:

G5 = MID(A5,C5+1,E5-C5-1)

Where we have added 1 to the position of the first space as we want the next character. The formulae E5-C5-1 ensures that we grab the relevant characters from the string:

02 Oct Working with Strings in Excel VBA

Posted at 02:54h
in Excel VBA
0 Comments

Howdee! If you’ve ever written any VBA code, you’ve likely had to edit strings in Excel VBA. It can be challenging and more than a little frustrating, especially if you’re not familiar with the tools available to you within the framework. Have you ever had to transform a string of last name comma first name to a traditional full name field in code? Ever had to pull a piece of information out of a string of dozens of characters? Then this article is for you. With that done, let’s dive right in!

VBA InStr & InStrRev Functions

These two functions are, in my opinion, the most crucial text functions to understand when it comes to getting data from inside a string of text in Excel. Once you understand these, you can begin to combine them with other functions to write truly powerful text parsing code.

The Instr function returns the starting position, as a number, of a string within a string of text. For example, we could search the string “I owe you 25 dollars on September 25th” for the literal string “25”. Depending on which function you use you would get different results! Let’s examine the below code:

Sub Instr_InstrRev_Example()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox InStr(1, stringExample, "25") 'returns 11

MsgBox InStrRev(stringExample, "25") 'returns 35

End Sub

The first message box will display “11” and the second will display “35”. This is important to think about when writing your code, if you need the first or last occurrence of a string within a string, then these functions will serve you very well. In the interest of being thorough, here is the syntax for both functions:

InStr( [start], string, substring, [compare] )

Start is an optional parameter that tells the function which character to begin searching. If you omit it, the compiler will start at the first character. String represents the string you’re searching while substring is the string you’re searching for. The compare parameter is also optional and I’ve rarely had need to use it so I won’t confuse you with it now but you’ll almost always use text compare.

InStrRev (StringCheck, StringMatch, [Start], [Compare])

StringCheck is the string you’re searching while StringMatch is the string you’re searching for. The start variable is optional as it was in InStr. The difference is it starts at the end of the string if omitted. Compare is the same as from the previous function also.

You might be asking yourself what use the VBA Instr and InstrRev functions are if they only return the starting position of a first or last occurrence of a substring. Once we introduce the next function, it will begin to make more sense.

VBA Mid Function

The Mid VBA function extracts a substring from a string based on a starting position and length that you specify. Before diving into examples, let’s look at the syntax:

Mid(text, start_position, number_of_characters)

Text is the full string of text from which you want to remove a substring. Start_position is an integer that represents the starting position of the first character of the string you wish to remove. Finally, number_of_characters is an integer representing the number of characters you wish to return.

Continuing with the sentence we used in the prior example, let’s examine the following code:

Sub MidExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Mid(stringExample, 1, 5)

End Sub

In this example, our Mid VBA function would return the string “I owe”. That’s because we have told the function to start at the first character in the string and return 5 characters from that point, including the starting character. Combining this function with the two InStr functions from the prior example, you can dynamically tell your Mid function where to start returning text from within a string. Using these functions together is how I primarily handle working with strings in Excel VBA.

VBA Left & Right Functions

If you’ve been using Excel for any period of time, you’ve probably either seen or used the Left and Right worksheet functions. Both of these functions exist in VBA and the syntax is the exact same. So, if you’re familiar with these functions, you can probably skip ahead to the next section but, in the interest of thoroughness, I want to cover these functions for folks who may not have used them before.

By their names, you can probably infer what these two functions do. The Left function returns a specific number of characters from the beginning of a string, while the Right function returns a specified number of characters form the end of a string. The syntax for them looks like this:

Left(text, number_of_characters)

Right(text, number_of_characters)

In both functions, the text input is the string you’re wanting to return a portion of, while the number_of_characters input is an integer representing the number of characters you wish to return. Let’s use our $25 sentence to examine the results in the following code:

Sub LeftRightExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Left(stringExample, 5)
MsgBox Right(stringExample, 5)

End Sub

In this example, the left function would return “I owe” while the Right example would return “ 25th”. The VBA functions Left & Right are very useful when you need to return the beginning X number of characters or the ending X number of characters from a string. It can also be used to return the beginning/ending portions of substrings when other functions are nested inside the text input. While I use these less than the previous two, they’re incredibly useful when just grabbing the beginning or ends of strings in Excel VBA.

VBA Replace Function

The last function I want to cover in depth is the VBA Replace function. As you might expect from its name, the Replace function replaces a sequence of characters with another sequence of characters. This can be useful when you’re preparing data and need to remove invalid characters from a string, performing what if analysis and need to alter a string based on inputs, etc. Let’s take our sentence we’ve been using and assume we need to change the 25th due date to the 30th. First, let’s examine the syntax to figure out how to do that.

Replace(string1, find, replacement, [start], [count], [compare])

String1 represents the string you want search. For us, this is our entire sentence. Find represents the string we are searching string1 for to perform the replace. The last required field, replacement, is the sequence of characters you want to replace string1 with. Start, an optional parameter, tells the search where to start. If you omit this, it starts at the beginning of the string. Count determines the number of replacements to make. If you leave this blank, it will perform the replace for every occurrence of find. Lastly, compare determines how to compare the strings. As before, you’ll almost always leave this to it’s default of text compare. The code for our example looks like this:

Sub ReplaceExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Replace(stringExample, "25th", "30th")

End Sub

Other Useful Functions to Edit Strings in Excel VBA

Len(text)

The Len VBA function accepts a string input and returns the number of characters in that string.

UCase(text) & LCase(text)

Both of these functions accept a string input and the UCase function will return the string converted to all upper-case characters while the LCase function returns the string with all characters converted to lower-case. This is very useful when doing string comparisons in VBA.

Str(number)

Str is a useful function that will accept a number from your code and return it as a string so you can then use string and text VBA functions on the number.

Split(expression, [delimiter], [limit], [compare])

Split is a very useful function that will split out substrings based on a delimiter. Expression is the text input. The optional parameter delimiter will default to a space delimiter but you can assign a comma, semi-colon, etc. Limit is also optional and determine the number of strings to split out. This will default to all strings if left blank. Compare, as with other formulas can be almost always be omitted from your function.

Real World Examples

The above functions, while good for explanation purposes, don’t always tell the full story since they aren’t real world examples of how to use these functions. I thought I would toss out a couple of examples of how to use VBA text functions to manipulate strings in Excel VBA with a couple of problems I’ve run into over the years.

The most common issue I run into with data sets, is that there is no universally accepted way to export full names. Almost every database stores names as first and last name fields. The issue is that many systems concatenate these fields together on export but may do it differently. For example, your time tracking system might export names in the format “FirstName LastName” while your payroll system exports names in the format “LastName, FirstName”. If you’re trying to match these names up on a weekly basis for payroll, this can get annoying quickly. Writing a macro to transform one or the other can save you a lot of time over the course of the year.

Sub LastNameFirstNameExample()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    Cells(i, 2) = Mid(str, InStr(1, str, ",") + 2, Len(str) - InStr(1, str, ",") + 2) & " " & _
        Left(str, InStr(1, str, ",") - 1)
Next i

End Sub

working with strings in excel vba

This subroutine is an example of how to turn the “LastName, FirstName” format into the “FirstName LastName” format, as seen in the gif above. First, we define the range we want to perform the conversion on and loop through those cells. While looping, we use a combination of the Mid, InStr, Len, and Left functions to reorder the names. Since all names are separate by a comma, it becomes very easy to find the splitting point between the last name and first name and, by using the Len & InStr functions, we can determine exactly how many characters we need to return. Alternatively, we could have used the Split function like this:

Sub LastNameFirstNameExampleTwo()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String
Dim nameArray() As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    nameArray = Split(str, ",")
    Cells(i, 2) = LTrim(nameArray(1) & " " & nameArray(0))
Next i

End Sub

The nuts and bolts of this are the same, but this example uses a string array and the Split function inside the loop. You can easily split a string of delimited text into a string array and then reorder it. It’s important to remember that it will return all of the string around the split so we need to use the LTrim function in this case to remove the leading space at the beginning of our end result. Both examples are fine but I prefer the split and array example as it is a bit easier to read.

I hope you enjoyed this brief introduction to working with strings in Excel VBA. As always, the example code is available for download for all subscribers. It’s quick and easy to sign up and I won’t ever spam you with unwanted ads and emails. Let me know in the comments if you have any questions on the above.

Cheers,

R

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

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.6k.

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, то я предлагаю вам ознакомиться с разделом «Прочтите это в первую очередь» перед использованием любой из функций.

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

«String functions» refers to the category of functions in Excel that allow you to manipulate blocks of text in various ways. But before we dive into what string functions are and how they operate, let’s define what we mean by «string».

In Excel, there are three types of inputs that we can use within formulas:

  • Numbers are digits typed in directly on the keyboard. You can type numbers directly into the formula bar and use them as part of calculations, like the simple calculation =4+6, which outputs the number 10.
  • Strings are blocks of text that appear in Excel, like names of people, names of cities, e-mail addresses, or names of items sold in a store. When we type strings into Excel, we always use quotation marks around them to tell Excel that what it’s about to read is one coherent block of text. For example, if we want to use the name «Sarah Smith» in a formula, we enclose it in quotes («Sarah Smith»).
  • Cell references point to the contents of other cells (which contain numbers or strings). Cell references come in the format [column_letter][row_number], like C5. If a cell reference points to a cell containing a string, the cell reference can be used as a string in a formula. Likewise, if a cell reference points to a cell containing a number, the cell reference can be used as a number in a formula.

We enclose strings in quotes to differentiate between strings and cell references; Excel needs to know which of these two different input types we are dealing with when it reads our formulas.

Also, note that we only need to enclose strings in quotes if they come in a formula led by an equals sign (=). If you type a static string — one that is not used in a larger formula — into Excel, the program is smart enough to realize that you are inputting a string and treat it as such.

Using functions on strings

Now that we know what a string is, we have a better idea of what a «string function» is: a function designed to manipulate strings in various ways. There are numerous useful string functions, but they all take strings as one or more arguments to accomplish a variety of goals. Using string functions, you can:

  • Combine two strings together into one larger string (e.g., put a user’s name and domain together to form an e-mail address);
  • Pull out important details of a string into a separate cell (e.g., isolate just the state abbreviation in a city, state combination);
  • Split up strings based on a common delimiter (e.g., separate out a user’s e-mail prefix from his or her domain name);
  • Cut down a string so that only the important parts are passed on to another function (e.g., pull out just a user’s last name based on an input cell containing his or her full name);
  • And much more.

Check out our complete list of string functions to start learning about these useful tools.

Save an hour of work a day with these 5 advanced Excel tricks

Work smarter, not harder. Sign up for our 5-day mini-course to receive must-learn lessons on getting Excel to do your work for you.

  • How to create beautiful table formatting instantly…
  • Why to rethink the way you do VLOOKUPs
  • Plus, we’ll reveal why you shouldn’t use PivotTables and what to use instead…

Comments

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?

Понравилась статья? Поделить с друзьями:
  • Worksheets cells vba excel
  • Working with sheets in excel
  • Worksheets cell excel vba
  • Working with microsoft excel
  • Worksheets add vba excel