All text functions in excel

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

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

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

Function

Description

ARRAYTOTEXT function

Office 365 button

Returns an array of text values from any specified range

ASC function

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

BAHTTEXT function

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

CHAR function

Returns the character specified by the code number

CLEAN function

Removes all nonprintable characters from text

CODE function

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

CONCAT function

Excel 2016

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

CONCATENATE function

Joins several text items into one text item

DBCS function

Excel 2013

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

DOLLAR function

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

EXACT function

Checks to see if two text values are identical

FIND, FINDB functions

Finds one text value within another (case-sensitive)

FIXED function

Formats a number as text with a fixed number of decimals

LEFT, LEFTB functions

Returns the leftmost characters from a text value

LEN, LENB functions

Returns the number of characters in a text string

LOWER function

Converts text to lowercase

MID, MIDB functions

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

NUMBERVALUE function

Excel 2013

Converts text to number in a locale-independent manner

PHONETIC function

Extracts the phonetic (furigana) characters from a text string

PROPER function

Capitalizes the first letter in each word of a text value

REPLACE, REPLACEB functions

Replaces characters within text

REPT function

Repeats text a given number of times

RIGHT, RIGHTB functions

Returns the rightmost characters from a text value

SEARCH, SEARCHB functions

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

SUBSTITUTE function

Substitutes new text for old text in a text string

T function

Converts its arguments to text

TEXT function

Formats a number and converts it to text

TEXTAFTER function

Office 365 button

Returns text that occurs after given character or string

TEXTBEFORE function

Office 365 button

Returns text that occurs before a given character or string

TEXTJOIN function

Office 365 button

Combines the text from multiple ranges and/or strings

TEXTSPLIT function

Office 365 button

Splits text strings by using column and row delimiters

TRIM function

Removes spaces from text

UNICHAR function

Excel 2013

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

UNICODE function

Excel 2013

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

UPPER function

Converts text to uppercase

VALUE function

Converts a text argument to a number

VALUETOTEXT function

Office 365 button

Returns text from any specified value

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

See Also

Excel functions (by category)

Excel functions (alphabetical)

Need more help?

Want more options?

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

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

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



Examples with TEXT function in Excel

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

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

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

text in string with numeric.

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

inadequate result.

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

TEXT.

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

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

Format Cells.

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

introduce.

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

operator.

Note that the values are now displayed in numerical format.



Text splitting function in Excel

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

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

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

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

split.

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

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

For a name, we use the same formula:

use the same formula.

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

The formula for extracting the surname:

extracting.

Next formulas for extracting the surname is a bit different:

example.

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

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

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

Function for merging text in Excel

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

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

example.

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

We get the combined values in one cell:

combined values in one cell.

Using the CONCATENATE function:

CONCATENATE.

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

Text SEARCH function in Excel

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

SEARCH.

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

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

syntax.

Download example TEXT functions

The syntax of the SEARCH function:

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

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

Excel not only is good with numbers. Excel has many text functions. It is the most useful app for working with cleaning text from a database. 


Text Capitalization Functions

Function Description
LOWER converts all letters to lowercase
PROPER changes first letters to uppercase
and other letters as lowercase
UPPER converts all letters to uppercase

LOWER

Converts all letters in a text string to lowercase.

=LOWER(text)

  • Text – is the text you want to convert to lowercase. Characters that are not letters are not changed.

PROPER

Converts a text string to proper case; the first letter in each word to uppercase, and all other letters to lowercase.

=PROPER(text)

  • Text – is text enclosed in quotation marks, a formula that returns text, or a reference to a cell containing text to partially capitalize.

UPPER

Converts a text string to all uppercase letters.

=UPPER(text)

  • Text – is the text you want converted to uppercase, a reference or a text string.

Text Edit Functions

Function Description
CLEAN removes all nonprintable characters
TRIM removes spaces from a text string except for
single spaces between words
LEFT extracts a given number of characters
from the left
LEN counts characters in a cell
MID extracts from the middle given a starting
point and the number of characters needed
RIGHT extracts a given number of characters
from the right
TEXT converts a value to text in a specific
number format

CLEAN

The CLEAN function removes all nonprintable characters from a text string.

=CLEAN(text)

  • text – The text to search for nonprintable characters.


TRIM

The Excel TRIM function strips extra spaces from text, leaving only a single space between words and no space characters at the start or end of the text.

=TRIM (text)

  • text – The text from which to remove extra space.

LEFT

The LEFT function extracts a given number of characters from the left side of a supplied text string. For example, LEFT(“apple”,3) returns “app”.

=LEFT (text, [num_chars])

  • text – The text from which to extract characters.
  • num_chars – [optional] The number of characters to extract, starting on the left side of text. Default = 1.

LEN

Returns the number of characters in a text string. A cell containing John Smith would return a length of 10. A cell containing Nashville, TN returns a length of 13.

=LEN(text)

  • Text – is the text whose length you want to find. Spaces count as characters.

MID

The Excel MID function extracts a given number of characters from the middle of a supplied text string. For example, =MID(“apple”,2,3) returns “ppl”.

=MID (text, start_num, num_chars)

  • text – The text to extract from.
  • start_num – The location of the first character to extract.
  • num_chars – The number of characters to extract.

RIGHT

The Excel RIGHT function extracts a given number of characters from the right side of a supplied text string. For example, RIGHT(“apple”,3) returns “ple”.

=RIGHT (text, [num_chars])

  • text – The text from which to extract characters on the right.
  • num_chars – [optional] The number of characters to extract, starting on the right. Optional, default = 1.

TEXT Function

Converts a value to text in a specific number format.

=TEXT(value,format_text)

Value – is a number, a formula that evaluates to a numeric value, or a reference to a cell containing a numeric value.

format_text – is a number format in text form from the Category box on the Number tab in the Format Cells dialog box (not General).

The TEXT function is useful to format text in many different ways. The following table shows examples.


TEXT Function Examples

Formula Description
=TEXT(1234.567,“$#,##0.00”) Currency with a thousands separator
and 2 decimals: $1,234.57
=TEXT(TODAY(),“MM/DD/YY”) Today’s date in MM/DD/YY format: 10/29/19
=TEXT(TODAY(),“DDDD”) Today’s day of the week: Monday
=TEXT(NOW(),“H:MM AM/PM”) Current time: 1:29 PM
=TEXT(0.285,“0.0%”) Percentage: 28.5%
=TEXT(4.40 ,“# ?/?”) Fraction: 4 2/5
=TRIM(TEXT(0.75,“# ?/?”)) Fraction: 3/4. Note this uses the TRIM
function to remove the leading space
with a decimal value.
=TEXT(12200000,“0.00E+00”) Scientific notation: 1.22E+07
=TEXT(1234567898,“[<=9999999]
###-####;(###) ###-####”)
Phone number: (123) 456–7898
=TEXT(1234,“0000000”) Add leading zeros (0): 0001234

Joining Text Functions

Function Description
CONCAT joins values together,
can be a range of cells
CONCATENATE joins up to 30 text
items together
TEXTJOIN joins values with a given
delimiter, can ignore
empty cells

CONCATENATE

The Excel CONCATENATE function joins up to 30 text items together and returns the result as text. The CONCAT function replaces CONCATENATE in newer versions of Excel.

=CONCATENATE (text1, text2, [text3], …)

  • text1 – The first text value to join together.
  • text2 – The second text value to join together.
  • text3 – [optional] The third text value to join together.

CONCAT

The CONCAT function joins values supplied as references or constants. Unlike the CONCATENATE function (which CONCAT replaces), CONCAT allows you to supply a range of cells to join, in addition to individual cell references.

=CONCAT (text1, [text2], …)

  • text1 – First text value, cell reference, or range.
  • text2 – [optional] Second text value, cell reference, or range

TEXTJOIN

The Excel TEXTJOIN function joins values with a given delimiter. Unlike the CONCAT function, TEXTJOIN allows you to supply a range of cells, and has a setting to ignore empty values.

=TEXTJOIN (delimiter, ignore_empty, text1, [text2], …)

  • delimiter – Separator between each text.
  • ignore_empty – Whether to ignore empty cells or not.
  • text1 – First text value or range.
  • text2 – [optional] Second text value or range.

Search Text Functions

Function Description
FIND get the location of text in a string
(case sensitive and no wildcards)
REPLACE replaces part of a text string with
text specified, given starting number
and number of characters
SEARCH get the location of text in a string
SUBSTITUTE finds some text and replaces
it with some different text

FIND

The Excel FIND function returns the position (as a number) of one text string inside another. When the text is not found, FIND returns a #VALUE error.

=FIND (find_text, within_text, [start_num])

  • find_text – The text to find.
  • within_text – The text to search within.
  • start_num – [optional] The starting position in the text to search. Optional, defaults to 1.

SEARCH

The Excel SEARCH function returns the location of one text string inside another. SEARCH returns the position of the first character of find_text inside within_text. Unlike FIND, SEARCH allows wildcards and is not case-sensitive.

=SEARCH (find_text, within_text, [start_num])

  • find_text – The text to find.
  • within_text – The text to search within.
  • start_num – [optional] Starting position in the text to search. Optional, defaults to 1.

Date Functions

Excel has several functions using dates, days, weeks, months, and years.

Function Description
DATE returns the serial number date
DATEVALUE converts a text date into the
serial number date
TODAY current date
NOW current date and time
WEEKDAY given a date, returns a number 1–7
with the default where Sunday = 1
MONTH given a date, returns the
month from 1–12
YEAR given a date, returns the year
as a four digit number
YEARFRAC returns a decimal value that represents
fractional years between two dates
ROMAN converts Arabic numerals to
Roman numerals
ARABIC converts Roman numerals to
Arabic numerals

DATE

Returns the Excel serial number date

=DATE(year,month,day)

  • Year – is a number from 1900 to 9999.
  • Month – is a number from 1 to 12 representing the month of the year.
  • Day – is a number from 1 to 31 representing the day of the month.

DATEVALUE

Converts a text date to an Excel serial date.

=DATEVALUE(date_text)

  • Date_text – text that represents a date in Excel date format, between 1/1/1900 and 12/31/9999.

TODAY

TODAY function returns the current date. TODAY is updated continuously when a worksheet is changed or opened. The TODAY function takes no arguments. You can format the value returned by TODAY using any standard date format. If you need the current date and time, use the NOW function.

=TODAY ()

The TODAY function requires no parameters but you must use parentheses. 

To enter the current date without a function, use ⌃ ; for macOS or Ctrl ; for Windows.


NOW

The Excel NOW function returns the current date and time. It is updated continuouslywhen a worksheet is changed or opened. The NOW function takes no arguments. You can format the value returned by NOW as a date, or as a date with time by applying a number format.

=NOW ()

The NOW function requires no parameters but you must use parentheses. 

To enter the current time without a function, use ⌘ ; for macOS or Ctrl Shift : for Windows.


WEEKDAY

The Excel WEEKDAY takes a date and returns a number between 1–7 representing the day of week. By default, WEEKDAY returns 1 for Sunday and 7 for Saturday. You can use the WEEKDAY function inside other formulas to check the day of week and react as needed. 

=WEEKDAY (serial_number, [return_type])

  • serial_number – The date for which you want to get the day of week.
  • return_type – [optional] A number representing day of week mapping scheme. Default is 1.

The available schemes are as follows:

  • 1: Numbers 1 (Sunday) through 7 (Saturday)) – default
  • 2: Numbers 1 (Monday) through 7 (Sunday)
  • 3: Numbers 0 (Monday) through 6 (Sunday)
  • 11: Numbers 1 (Monday) through 7 (Sunday)
  • 12: Numbers 1 (Tuesday) through 7 (Monday)
  • 13: Numbers 1 (Wednesday) through 7 (Tuesday)
  • 14: Numbers 1 (Thursday) through 7 (Wednesday)
  • 15: Numbers 1 (Friday) through 7 (Thursday)
  • 16: Numbers 1 (Saturday) through 7 (Friday)
  • 17: Numbers 1 (Sunday) through 7 (Saturday)

MONTH

The Excel MONTH function returns the month portion of a date as number between 1 to 12 when given a date. You can use the MONTH function to extract a month number from a date into a cell. You can also use the MONTH function to feed a month number to another formula, like the DATE function.

=MONTH (date)

  • date – any date

YEARFRAC

YEARFRAC function returns a decimal value that represents fractional years between two dates. You can use YEARFRAC for formulas that do things like calculating age in years using a birthdate.

=YEARFRAC (start_date, end_date, [basis])

  • start_date – The start date.
  • end_date – The end date.
  • basis – [optional] The type of day count basis to use.

The type of day count basis to use:

  • Basis 0: US (NASD) 30/360 – default
  • Basis 1: Actual/actual
  • Basis 2: Actual/360
  • Basis 3: Actual/365
  • Basis 4: European 30/360

YEAR

The Excel YEAR function returns the year component of a date as a 4-digit number. You can use the YEAR function to extract a year number from a date into a cell. You can also use the YEAR function to extract and feed a year value into another formula, like the DATE function.

=YEAR (date)


ROMAN

Converts an Arabic numeral to Roman numeral. The Roman numeral is text.

=ROMAN(number, [form])

  • Number – the Arabic numeral you want to convert.
  • Form – the number or logic (0–4, TRUE, or FALSE) specifying the type of Roman numeral.
  • 0 or omitted – Classic
  • 1 – More concise
  • 2 – More concise
  • 3 – More concise
  • 4 – Simplified
  • TRUE – Classic
  • FALSE – Simplified

ARABIC

Converts a Roman numeral to an Arabic numeral. (Roman numerals are text.)

=ARABIC(text)

  • text – Roman numeral you want to convert


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

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

VBA String Functions

Содержание

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

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

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

Введение

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sub Comp1()

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

End Sub

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

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

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

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

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

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

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

VBA String Functions - Smaller

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

Sub Dobavlenie()

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

End Sub

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

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

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

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

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

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

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

Sub IspLeftRightMid()

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

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

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

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

End Sub

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

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

Sub PrimerIspolzovaniyaLeft()

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

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

 End Sub

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

Sub IzmenenieStroki()

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

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

    Debug.Print "Имя: "; name

 End Sub

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

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

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

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

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

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

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

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

Sub PoiskTeksta()

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

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

End Sub

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

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

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

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

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

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

Sub IspInstrRev()

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

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

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

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

End Sub

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

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

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

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

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

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

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

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

End Sub

Длина строки

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

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

Sub IspLen()

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

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

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

End Sub

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

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

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

Sub RevStr()

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

End Sub

Сравнение

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

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

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

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

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

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

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

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

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

Sub IspStrComp()

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

End Sub

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

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

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

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

Option Compare Text

Sub CompareIspEquals()

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

End Sub

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

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

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

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

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

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

[abc][!def]?#X*

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

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

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

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

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

Sub Shabloni()

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

End Sub

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

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

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

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

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

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

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

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

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

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

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

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

Sub PrimeriReplace()

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

End Sub

На выходе:

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

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

Sub ReplaceCount()

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

End Sub

На выходе:

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

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

Sub ReplacePartial()

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

End Sub

На выходе:

;C;D;E
;E
CD

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

Sub ReplaceCase()

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

End Sub

На выходе:

XaXa
XXXX

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

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

Sub ReplaceMulti()

    Dim newString As String

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

    Debug.Print newString

End Sub

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

Sub ReplaceMultiNested()

    Dim newString As String

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

    Debug.Print newString

End Sub

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

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

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

Sub AutoConverts()

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

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

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

End Sub

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

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

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

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

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

Sub IspStr()

    Dim coll As New Collection
    Dim c As Range

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

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

End Sub

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

Multi Region

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

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

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

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

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

Sub StrToNumeric()

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

    l = s
    d = s
    c = s

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

End Sub

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

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

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

    Dim value

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

End Sub

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

Sub InvalidNumber()

    Dim l As Long

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

End Sub

Функция Val

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

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

Sub IspVal()

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

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

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

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

End Sub

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

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

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

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

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

Sub IspString()

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

End Sub

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

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

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

Sub ConvCase()

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

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

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

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

End Sub

На выходе: 

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

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

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

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

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

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

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

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

Sub StrToArr()

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

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

End Sub

На выходе:

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

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

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

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

Sub ArrToStr()

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

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

    Debug.Print sNames

End Sub

На выходе:

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

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

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

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

Sub FormatDate()

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

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

End Sub

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

Sub FormatNumbers()

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

End Sub

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

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

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

VBA Format Function

Заключение

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

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

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

April 20 2019 Written By: EduPristine

How to use Text Functions in Excel

Excel is mostly about the numerical data, but at times you can come across the data which has too much text and that is the time when Text Functions in Excel will help you to simplify the things easily.

Here are few text functions you should know
 

1.Left()

You can use the Left function when you want to extract the leftmost characters from a string. Syntax =left(text, num_char)

Text Functions in Excel

Similarly, you can also use the Right function to extract the rightmost characters from a string.

 Text Functions in Excel

2.  Len ()

Len function in Excel helps you to know the length of a string that is number of characters in a string. Syntax = LEN(text)

Note – Spaces are included while calculating length.

Len function in Excel

3.  Mid ()

Mid function in Excel is used to extract the characters from the middle of a string. Syntax = MID(text, start_char, num_chars)

Mid function in Excel

4.  Find ()

Find function in Excel is used when you want to know the position of certain characters in a particular string. Syntax =FIND(find_text, within_text,[start_num])

Find function in Excel

5.  Proper ()

Proper function in Excel capitalizes each word in the string that is, it converts the case into proper case. Syntax =PROPER(Text)

Proper function in Excel

6.  Rept ()

Rept function in Excel is used when you want a certain text to be repeated certain number of times. Syntax =REPT(Text, number_times)

Repeat function in Excel

7. Trim()

Trim function in Excel removes the unnecessary spaces from a particular string.
Syntax =TRIM(Text )

Trim function in Excel

8.  Upper()

Upper function in Excel converts the text into Upper case from lower case. Syntax =UPPER(Text )

Upper function in Excel

9.  Substitute ()

Substitute function in Excel helps to replace existing text with a new text in a particular string. Syntax =SUBSTITUTE(text, old_text, new_text, instance number)

Substitute function in Excel

10.  Concatenate ()

Concatenate function in Excel helps to join the text of two or more cells. Syntax =CONCATENATE(text1, text2….)

Concatenate function in Excel

If you have any doubts or suggestions for us, then do let us know in the comments section below and we shall get back to you at the earliest.

How to manipulate text and clean up your data like a pro

On larger spreadsheets, it is important and necessary to be able to manipulate text, especially when you import it from another system and the formatting is all over the shop.

In this post I give you 9 text functions that hand you complete control over your data.

Clickable Table of Contents

Cheat Sheet - 9 powerful Excel TEXT functions

FEATURE DOWNLOAD

Grab the free Text Functions cheat sheet

1. Why are text functions so useful?

Have you ever downloaded a report or some stats from the web and found that the data is a mess?

In particular, people often enter names, addresses and place names all in lower case or all in upper case (capital letters) — LIKE THEY’RE SHOUTING AT YOU.

So what can you do?

Well, there is a whole category of TEXT functions in Excel that manipulate text.

2. Setting The Correct Case

 — Text functions used: UPPER, LOWER, PROPER

Let’s start with 3 of the simpler text functions.

Say you have the name ‘joe bloggs’ in cell A1.

To convert cell A1 to uppercase, type

=UPPER(A1)

To switch it back to lower case, type

=LOWER(A1)

To convert the name to Title Case (where only the first letter of each word – in this case, each name – is capitalised), type

=PROPER(A1)

3. Concatenating (joining) data

 — Text functions used: CONCATENATE

If you had ‘joe’ in cell A1 and ‘BLOGGS’ in cell A2, you can join them together using concatenation. There are 2 ways to do this:

Method 1:

=A1 & » » & A2

Method 2:

=CONCATENATE(A1,» «,A2)

With the first method, a concatenation character (‘&’) is used to connect one item to the next.

With the second method, the CONCATENATE function is used, and all the items to be joined together are listed inside the brackets.

Notice that with both methods, the 2 names are connected with a space to separate them.

You could also fix up the case errors by combining PROPER with either method, such as

=CONCATENATE(PROPER(A1),» «, PROPER(A2))

or

=PROPER(CONCATENATE(A1,» «,A2))

4. Removing leading and trailing spaces

 — Text functions used: TRIM

Often, when you import data from systems like SAP, a lot of the data has to be manually fixed before it can be used by Excel.

A common occurrence is leading and training spaces which affect everything from text length to no matches being found when using functions like VLOOKUP.

Leading spaces can often be seen, whereas training spaces often cannot be seen. Either way, manually fixing them is NOT the way to go.

Instead, a trim function removes any leading or trailing spaces on cell content. But don’t worry, spaces between words are not removed.

If cell A1 contained <space>Joe Bloggs<space> then …

=TRIM(A1)

removes the spaces to leave ‘Joe Bloggs’.

5. Separating a full name into first name and last name

 — Text functions used: LEFT, RIGHT, SEARCH, LEN

The LEFT and RIGHT functions extract a set number of characters from the left or right end of a string (the technical name for a block of text). So …

=LEFT(A1,5)

extracts the 5 leftmost characters from the text in cell A1, and

=RIGHT(A1,10)

extracts the 10 rightmost characters from the text in cell A1.

However, if you want a formula to work for any name, we need to employ a slightly more sophisticated technique to calculate how many characters to extract.

I am going to use 2 additional functions – SEARCH and LEN.

SEARCH finds the position of string A within string B, so …

=SEARCH(» «, A1)

returns the position of the first space within the text in cell A1. Once we know this we can subtract 1 to calculate the number of characters to extract from the left side of a ‘full name’ call.

For example, if cell A1 contains ‘Joe Bloggs”, then

=SEARCH(» «, A1)

returns 4

The space between the names is in position 4.

Therefore …

=LEFT(A1, SEARCH(» «, A1)-1)

extracts ‘Joe’.

The reason the formula subtracts 1 is because the position of the space is 4, therefore the number of characters to extract is 3.

To obtain the surname, we need to also use LEN. The LEN function calculates the total length of a string, so if we continue to use our example where cell A1 contains ‘Joe Bloggs’, then

=LEN(A1)

returns 10.

If we subtract the position of the space (4) from the total length of the text (10) then we have the length of the surname (6), which is the number of characters we need to extract using the RIGHT function.

Here is the complete formula to extract the surname from a full name:

=RIGHT(LEN(A1) – SEARCH(» «, A1))

If you want to fix up any case issues at the same time, then wrap the whole formula above inside a PROPER function, like this:

=PROPER(RIGHT(LEN(A1) – SEARCH(» «, A1)))

Here’s how it works.

The SEARCH finds the position of the space (char 4), then subtracts this from the length of the whole name (10 chars) for an answer of 6. It then extracts the 6 right most characters from the full name, before using the PROPER function to apply the correct capitalisation.

Here’s how it works.

The SEARCH finds the position of the space (char 4), then subtracts this from the length of the whole name (10 chars) for an answer of 6. It then extracts the 6 right most characters from the full name, before using the PROPER function to apply the correct capitalisation.

 — Alternatively …

I can hear some of you jumping up and down shouting “What about Text To Columns!?” so I wanted to address that quickly.

The Text To Columns feature (on the Data tab) allows you to take a large block of data, normally imported, and break it into separate columns, either based on a fixed length of text or using a separator like a space, tab character or hyphen.

You’re right! In this scenario, the Text to Columns feature is the best tool to use. It’s easy and quick. However, make sure you trial it on a small sample size first before committing completely.

You might also want to try Flash Fill — introduced in Excel 2013. It’s super easy but has some limitations.

The functions I’ve discussed in this post allow you to make up your own rules and they give you a much finer element of control.

6. What next?

This is just a sample of the text function that Excel offers you. To see a complete list, click the Formulas tab, then click the TEXT
FUNCTIONS icon. 

I hope you found plenty of value in this post. I’d love to hear your biggest takeaway in the comments below together with any questions you may have.

Have a fantastic day.

Jason Morrell blog signature

About Jason Morrell

About the author

Jason Morrell

Jason loves to simplify the hard stuff, cut the fluff and share what actually works. Things that make a difference. Things that slash hours from your daily work tasks. He runs a software training business in Queensland, Australia, lives on the Gold Coast with his wife and 4 kids and often talks about himself in the third person!

SHARE

Text Functions in Excel help you to simplify handling text strings easily. In this article, we’ll learn some of the text functions in Excel.

Also read: Top 10 Logical Functions in Excel – A Quick Reference

Let’s get started with the top text functions present in Excel. We’ll cover the basic use cases along with the function names.

1. CHAR function

When provided a valid character code, the Excel CHAR function returns a character. The numbers returned by the CHAR function come from ANSI. ANSI stands for American National Standards Institute which is a set of 8-bit characters. These include numbers 0 to 9, lowercase a-z, uppercase A-Z, punctuations, and special characters.

Syntax: CHAR(number), where “number” is an integer between 0-255 and returns a text value. The following example shows the use of CHAR function:

  • Select the cell where you want to display the result.
  • Type =CHAR(100).
char formula
  • Press the Enter key to display the result.
char result

2. CLEAN function

All nonprintable characters are removed from the text by the CLEAN function. It also removes line breaks.

Syntax: CLEAN(text), where text is the string that has to be cleaned of line breaks and other non-printable characters. The following example shows the use of CLEAN function:

  • Select the cell where you want to display the result.
  • Type =CLEAN(, select the cell containing the text and complete the formula with ).
clean formula
  • Press the Enter key to display the result.
clean result

3. CODE function

The CODE function returns the first character in a text string as a number code. The character set used by your machine is represented by the ANSI code returned.

Syntax: CODE(text), where text is the character for which the ANSI code is to be returned. The following example shows the use of CODE function:

  • Select the cell where you want to display the result.
  • Type =CODE(, select the cell containing the text and complete the formula with ).
code formula
  • Press the Enter key to display the result.
code result

4. CONCAT function

The CONCAT function joins text from various ranges and/or strings into a single string. CONCAT function that replaces CONCATENATE in Excel 2016 and above. The CONCATENATE function, on the other hand, will remain accessible for compatibility with older Excel versions.

Syntax: CONCAT(text1, [text2],…), where text1, text2, text3… are the string items to be joined. The following example shows the use of the CONCAT function:

  • Select the cell where you want to display the result.
  • Type =CONCAT(“Excel”,” “,”2019).
concat formula
  • Press the Enter key to display the result.
concat result

5. DOLLAR function

The DOLLAR function in Microsoft Excel transforms a number to text in $ currency format.

Syntax: DOLLAR(number, [decimals]), where number is a reference to a cell containing a number, or a formula that evaluates to a number and decimals is the number of digits to the right of the decimal. The following example shows the use of DOLLAR function:

  • Select the cell where you want to display the result.
  • Type =DOLLAR(A1,2), where cell A1 contains the number.
dollar function
  • Press the Enter key to display the result.
dollar result

6. EXACT function

The EXACT function analyses two text strings and returns TRUE if they are identical, otherwise FALSE. The EXACT function is case-sensitive but overlooks formatting variations.

Syntax: EXACT(text1,text2), where text1 is the first string and text2 is the second string to be compared. The following example shows the use of the EXACT function:

  • Select the cell where you want to display the result.
  • Type =EXACT(A1,B1), where cells A1 and B1 contain the strings to be compared.
exact formula
  • Press the Enter key to display the result.
exact result

7. LEN function

the LEN function returns the number of characters in a string including white spaces in between.

Syntax: LEN(text), where text is the string whose length you wish to find or the cell reference of the cell contains the string. The following example shows the use of LEN function:

  • Select the cell where you want to display the result.
  • Type =LEN(, select the cell containing the text and complete the formula with ).
len formula
  • Press the Enter key to display the result.
len result

The text string “MS Excel” contains 7 characters and 1 blank space.

8. FIND function

The FIND function in Excel returns the starting position of one text string within another text string.

Syntax: FIND(find_text, within_text, [start_num]), where find_text is the text you wish to find, within_text is the text within which you want to find for a particular string. start_num is an optional parameter that specifies the position from which to start the search. The following example shows the use of the FIND function:

  • Select the cell where you want to display the result.
  • Type =FIND(“x”,A1), where cell A1 contains the string to be searched for character “x”.
find formula
  • Press the Enter key to display the result.
find result

The character “x” is located at the 5th index position in the string “MS Excel”.

9. REPLACE function

The REPLACE function replaces a portion of a text string with a different text string based on the number of characters you specify.

Syntax: REPLACE(old_text, start_num, num_chars, new_text), where:

  • old_text is the text from which you wish to replace a portion
  • start_num is the position in old_text of the character you want to replace with new_text
  • num_chars is the number of characters you want REPLACE to replace in old_text with new_text
  • new_text is the text that will be used to replace the characters in old_text.

The following example shows the use of REPLACE function:

  • Select the cell where you want to display the result.
  • Type =REPLACE(A1,7,1,”e”), where cell A1 contains the old_text, 7 is the index position of the character to be replaced, 1 is the length of the new_text, and “e” is the character to be placed.
replace formula 1
  • Press the Enter key to display the result.
replace result

Conclusion

In this article, we learned about some of the most commonly used text functions in Excel.

References

  • CHAR function (microsoft.com)
  • CLEAN function (microsoft.com)
  • CODE function (microsoft.com)
  • CONCAT function (microsoft.com)
  • DOLLAR function (microsoft.com)
  • EXACT function (microsoft.com)
  • LEN, LENB functions (microsoft.com)
  • FIND, FINDB functions (microsoft.com)
  • REPLACE, REPLACEB functions (microsoft.com)

Понравилась статья? Поделить с друзьями:
  • All word file convert to pdf
  • All word family worksheet
  • All word family words in the square and write them
  • All word family word search
  • All word family wheel