Text code in excel

The TEXT function lets you change the way a number appears by applying formatting to it with format codes. It’s useful in situations where you want to display numbers in a more readable format, or you want to combine numbers with text or symbols.

Note: The TEXT function will convert numbers to text, which may make it difficult to reference in later calculations. It’s best to keep your original value in one cell, then use the TEXT function in another cell. Then, if you need to build other formulas, always reference the original value and not the TEXT function result.

Syntax

TEXT(value, format_text)

The TEXT function syntax has the following arguments:

Argument Name

Description

value

A numeric value that you want to be converted into text.

format_text

A text string that defines the formatting that you want to be applied to the supplied value.

Overview

In its simplest form, the TEXT function says:

  • =TEXT(Value you want to format, «Format code you want to apply»)

Here are some popular examples, which you can copy directly into Excel to experiment with on your own. Notice the format codes within quotation marks.

Formula

Description

=TEXT(1234.567,«$#,##0.00»)

Currency with a thousands separator and 2 decimals, like $1,234.57. Note that Excel rounds the value to 2 decimal places.

=TEXT(TODAY(),«MM/DD/YY»)

Today’s date in MM/DD/YY format, like 03/14/12

=TEXT(TODAY(),«DDDD»)

Today’s day of the week, like Monday

=TEXT(NOW(),«H:MM AM/PM»)

Current time, like 1:29 PM

=TEXT(0.285,«0.0%»)

Percentage, like 28.5%

=TEXT(4.34 ,«# ?/?»)

Fraction, like 4 1/3

=TRIM(TEXT(0.34,«# ?/?»))

Fraction, like 1/3. Note this uses the TRIM function to remove the leading space with a decimal value.

=TEXT(12200000,«0.00E+00»)

Scientific notation, like 1.22E+07

=TEXT(1234567898,«[<=9999999]###-####;(###) ###-####»)

Special (Phone number), like (123) 456-7898

=TEXT(1234,«0000000»)

Add leading zeros (0), like 0001234

=TEXT(123456,«##0° 00′ 00»»)

Custom — Latitude/Longitude

Note: Although you can use the TEXT function to change formatting, it’s not the only way. You can change the format without a formula by pressing CTRL+1 (or Image of the MAC Command button icon+1 on the Mac), then pick the format you want from the Format Cells > Number dialog.

Download our examples

You can download an example workbook with all of the TEXT function examples you’ll find in this article, plus some extras. You can follow along, or create your own TEXT function format codes.

Download Excel TEXT function examples

Other format codes that are available

You can use the Format Cells dialog to find the other available format codes:

  1. Press Ctrl+1 (Image of the MAC Command button icon+1 on the Mac) to bring up the Format Cells dialog.

  2. Select the format you want from the Number tab.

  3. Select the Custom option,

  4. The format code you want is now shown in the Type box. In this case, select everything from the Type box except the semicolon (;) and @ symbol. In the example below, we selected and copied just mm/dd/yy.

  5. Press Ctrl+C to copy the format code, then press Cancel to dismiss the Format Cells dialog.

  6. Now, all you need to do is press Ctrl+V to paste the format code into your TEXT formula, like: =TEXT(B2,»mm/dd/yy«). Make sure that you paste the format code within quotes («format code»), otherwise Excel will throw an error message.

Example of using the Format > Cells > Number > Custom dialog to have Excel create format strings for you.

Format codes by category

Following are some examples of how you can apply different number formats to your values by using the Format Cells dialog, then use the Custom option to copy those format codes to your TEXT function.

Why does Excel delete my leading 0’s?

Excel is trained to look for numbers being entered in cells, not numbers that look like text, like part numbers or SKU’s. To retain leading zeros, format the input range as Text before you paste or enter values. Select the column, or range where you’ll be putting the values, then use CTRL+1 to bring up the Format > Cells dialog and on the Number tab select Text. Now Excel will keep your leading 0’s.

If you’ve already entered data and Excel has removed your leading 0’s, you can use the TEXT function to add them back. You can reference the top cell with the values and use =TEXT(value,»00000″), where the number of 0’s in the formula represents the total number of characters you want, then copy and paste to the rest of your range.

Examples of using TEXT to format leading zeros.  =TEXT(A2,"00000")

If for some reason you need to convert text values back to numbers you can multiply by 1, like =D4*1, or use the double-unary operator (—), like =—D4.

Excel separates thousands by commas if the format contains a comma (,) that is enclosed by number signs (#) or by zeros. For example, if the format string is «#,###», Excel displays the number 12200000 as 12,200,000.

A comma that follows a digit placeholder scales the number by 1,000. For example, if the format string is «#,###.0,», Excel displays the number 12200000 as 12,200.0.

Examples of the TEXT function using the Thousands separator

Notes: 

  • The thousands separator is dependent on your regional settings. In the US it’s a comma, but in other locales it might be a period (.).

  • The thousands separator is available for the number, currency and accounting formats.

Following are examples of standard number (thousands separator and decimals only), currency and accounting formats. Currency format allows you to insert the currency symbol of your choice and aligns it next to your value, while accounting format will align the currency symbol to the left of the cell and the value to the right. Note the difference between the currency and accounting format codes below, where accounting uses an asterisk (*) to create separation between the symbol and the value.

Examples of the TEXT function with Number, Currency and Accounting formats

To find the format code for a currency symbol, first press Ctrl+1 (or Image of the MAC Command button icon+1 on the Mac), select the format you want, then choose a symbol from the Symbol drop-down:

Currency Symbol selection from the Format Cells dialog

Then click Custom on the left from the Category section, and copy the format code, including the currency symbol.

TEXT function - Custom currency with symbol

Note: The TEXT function does not support color formatting, so if you copy a number format code from the Format Cells dialog that includes a color, like this: $#,##0.00_);[Red]($#,##0.00), the TEXT function will accept the format code, but it won’t display the color.

You can alter the way a date displays by using a mix of «M» for month, «D» for days, and «Y» for years.

Month, Day and Year format codes

Format codes in the TEXT function aren’t case sensitive, so you can use either «M» or «m», «D» or «d», «Y» or «y».

You can alter the way time displays by using a mix of «H» for hours, «M» for minutes, or «S» for seconds, and «AM/PM» for a 12-hour clock.

Time formats for hours, minutes and seconds

If you leave out the «AM/PM» or «A/P», then time will display based on a 24-hour clock.

Format codes in the TEXT function aren’t case sensitive, so you can use either «H» or «h», «M» or «m», «S» or «s», «AM/PM» or «am/pm».

You can alter the way decimal values display with percentage (%) formats.

Format codes for Percent

You can alter the way decimal values display with fraction (?/?) formats.

Format codes for Fractions

Scientific notation is a way of displaying numbers in terms of a decimal between 1 and 10, multiplied by a power of 10. It is often used to shorten the way that large numbers display.

Format codes for Scientific notation

Excel provides 4 special formats:

  • Zip Code — «00000»

  • Zip Code + 4 — «00000-0000»

  • Phone Number — «[<=9999999]###-####;(###) ###-####»

  • Social Security Number — «000-00-0000»

Special formats for the TEXT function

Special formats will be different depending on locale, but if there aren’t any special formats for your locale, or if these don’t meet your needs then you can create your own through the Format Cells > Custom dialog.

Common scenario

The TEXT function is rarely used by itself, and is most often used in conjunction with something else. Let’s say you want to combine text and a number value, like “Report Printed on: 03/14/12”, or “Weekly Revenue: $66,348.72”. You could type that into Excel manually, but that defeats the purpose of having Excel do it for you. Unfortunately, when you combine text and formatted numbers, like dates, times, currency, etc., Excel doesn’t know how you want to display them, so it drops the number formatting. This is where the TEXT function is invaluable, because it allows you to force Excel to format the values the way you want by using a format code, like «MM/DD/YY» for date format.

In the following example, you’ll see what happens if you try to join text and a number without using the TEXT function. In this case, we’re using the ampersand (&) to concatenate a text string, a space (» «), and a value with =A2&» «&B2.

Example of joining text without the TEXT function

As you can see, Excel removed the formatting from the date in cell B2. In the next example, you’ll see how the TEXT function lets you apply the format you want.

Example of joining text with the TEXT function

Our updated formula is:

  • Cell C2:=A2&» «&TEXT(B2,»mm/dd/yy») — Date format

Frequently Asked Questions

Yes, you can use the UPPER, LOWER and PROPER functions. For example, =UPPER(«hello») would return «HELLO».

Yes, but it takes a few steps. First, select the cell or cells where you want this to happen and use Ctrl+1 to bring up the Format > Cells dialog, then Alignment > Text control > check the Wrap Text option. Next, adjust your completed TEXT function to include the ASCII function CHAR(10) where you want the line break. You might need to adjust your column width depending on how the final result aligns.

Example of using TEXT with CHAR(10) to insert a line break. ="Today is: "&CHAR(10))&TEXT(TODAY(),"MM/DD/YY")

In this case, we used: =»Today is: «&CHAR(10)&TEXT(TODAY(),»mm/dd/yy»)

This is called Scientific Notation, and Excel will automatically convert numbers longer than 12 digits if a cell(s) is formatted as General, and 15 digits if a cell(s) is formatted as a Number. If you need to enter long numeric strings, but don’t want them converted, then format the cells in question as Text before you input or paste your values into Excel.

See Also

Create or delete a custom number format

Convert numbers stored as text to numbers

All Excel functions (by category)

Текст — это функция рабочего листа в Excel, но ее также можно использовать в VBA при использовании свойства диапазона. Эта функция похожа на функцию Worksheet и принимает такое же количество аргументов, которые представляют собой значения, которые необходимо преобразовать, и указанный числовой формат.

Оглавление

  • Текстовая функция Excel VBA
    • Примеры текстовой функции VBA в Excel
      • Пример №1
      • Пример #2
    • Применить форматирование к ячейкам
    • Рекомендуемые статьи

Текстовая функция Excel VBA

ТЕКСТ — это функция, доступная на рабочем листе, но, к сожалению, это не встроенная функция в Excel VBA. Вместо этого нам нужно использовать объект класса функции рабочего листа в VBA для доступа к этой функции. Текст функция в экселе преобразует значение в указанный числовой формат.

Одна из проблем с этой функцией — аргументы. Всякий раз, когда мы используем функцию рабочего листа VBAФункция рабочего листа VBAФункция рабочего листа в VBA используется, когда нам нужно сослаться на конкретный рабочий лист. Когда мы создаем модуль, код запускается на текущем активном листе рабочей книги, но мы можем использовать функцию рабочего листа для запуска кода в определенном классе рабочего листа.Читать далее, мы не видим четкого синтаксиса. как в нашем рабочем листе. Вместо этого он просто говорит «Arg1» и «Arg2».

текстовая функция vba

Примеры текстовой функции VBA в Excel

Ниже приведены примеры функций Excel VBA TEXT.

.free_excel_div{фон:#d9d9d9;размер шрифта:16px;радиус границы:7px;позиция:относительная;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before{content:»»;фон:url(центр центр без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;верх:50%;margin-top:-35px;слева:-35px;граница:5px сплошная #fff;граница-радиус:50%} Вы можете скачать этот текстовый шаблон VBA Excel здесь — Текстовый шаблон VBA Excel

Пример №1

Позвольте мне показать вам простой пример TEXT в VBA Excel. Но сначала взгляните на приведенный ниже код в Visual BasicCode. В Visual Basic код VBA относится к набору инструкций, написанных пользователем на языке программирования приложений Visual Basic в редакторе Visual Basic (VBE) для выполнения определенной задачи. Подробнее.

Код:

Sub Text_Example1() Dim FormattingValue As String Dim FormattingResult As String FormattingValue = 0,564 FormattingResult = WorksheetFunction.Text(FormattingValue, «hh:mm:ss AM/PM») MsgBox FormattingResult End Sub

пример текста vba 1.1

Во-первых, мы объявили две переменные в виде строки в VBA.

Dim FormattingValue As String Dim FormattingResult As String

Для первой переменной мы присвоили номер форматирования, который нам нужно отформатировать.

Значение форматирования = 0,564

Теперь для другой переменной мы назначили функцию ТЕКСТ.

FormattingResult = WorksheetFunction.Text(FormattingValue, «чч:мм:сс AM/PM»)

Если вы заметили, мы применили форматирование времени, то есть «чч:мм:сс AM/PM».

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

MsgBox ФорматированиеРезультат

Когда мы запустим функцию кода ТЕКСТ, мы применим формат времени к числу 0,564 и отобразим результат ниже.

пример текста vba 1.3

Итак, мы получили время как «13:32:10».

Пример #2

Как и в примере с форматом даты, в этом примере мы внесли небольшие изменения. Ниже приведен код.

Код:

Sub Text_Example2() Dim FormattingValue As String Dim FormattingResult As String FormattingValue = 43585 FormattingResult = WorksheetFunction.Text(FormattingValue, «DD-MMM-YYYY») MsgBox FormattingResult End Sub

пример текста vba 2.1

Из предыдущего кода мы изменили значение форматирования с 0,565 на 43585 и изменили стиль форматирования на «ДД-МММ-ГГГГ».

Он применит форматирование к числу 43585 в качестве даты, и результат будет следующим.

пример 2.2

Применить форматирование к ячейкам

Мы видели простые примеры. Теперь посмотрим, как работать с ячейками на листе. Для этого примера посмотрите на данные ниже.

пример 3.1

Для всех этих чисел нам нужно применить формат времени. Этот код применит форматирование.

Код:

Sub Text_Example3() Dim k As Integer For k = 1 To 10 Cells(k, 2).Value = WorksheetFunction.Text(Cells(k, 1).Value, «hh:mm:ss AM/PM») Next k End Саб

пример 3.2

Этот код будет проходить через 10 ячеек и применять форматирование ниже.

пример 3.3

Используя функцию VBA TEXT, мы можем применить форматирование чисел к ячейкам.

Рекомендуемые статьи

Эта статья была руководством по текстовой функции VBA. Мы обсудили использование функции «Текст» в Excel VBA и несколько практических примеров. Кроме того, вы можете узнать больше о VBA из следующих статей:

  • Объект коллекции VBA
  • Текстовое поле в VBA
  • Функция InStr в VBA

The CODE function in Excel is used to find out the character’s code in the string. It finds out the code for the first character only, so if we use this formula as =CODE(“Anand”) and =CODE(“An”), we will get the same result as 65 as the code for character A is 65.

For example, suppose we have data with characters such as A, a, 0, and -11. In this case, the CODE function under the Excel Text functions will return the result as ANSII code for A, a, and 0. Whereas, for -11, it will provide the  ANSII code for – and ignore 11.

Table of contents
  • CODE Function in Excel
    • Syntax
    • How to Use CODE Function in Excel? (with Examples)
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • CODE Function in Excel Video
    • Recommended Articles

Syntax

code formula

Parameters

  • text: The text parameter is only a mandatory parameter of the CODE function. This parameter could be a single character, a string, or function that returns a text.

How to Use the CODE Function in Excel? (with Examples)

In this section, we will understand the use of the CODE function and look at a few examples with the help of actual data.

You can download this CODE Function Excel Template here – CODE Function Excel Template

Example #1

CODE Function Example 1

As we can see in the output section, the CODE function returns the ASCII value of the corresponding characters written in the first column. For example, the ASCII value of “A” is 65, and “a” is 97. We can easily verify the ASCII values of every keyboard character from the internet.

Example #2

Example 2

In the above example, we have applied the CODE function on cells containing strings. So as we can see in the output column, the CODE function returns the ASCII value of the first character of the sentence.

Example #3

Example 3

For example, we have used another two functions- LOWER and UPPER, to use their return value as a parameter of the CODE function. The lower function returns, the lowercase of the character passed as a parameter. Similarly, the UPPER function returns the uppercase of a character passed as a parameter.

Things to Remember

  1. The primary purpose of the CODE function is to return the ASCII code of a character of the first character in any cell.
  2. The CODE function is not popular among the Excel community. Still, we should be aware of it as an Excel expert, as we might find it handy in VBA CodingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
  3. It was first introduced in Excel 2000 and is available in all subsequent versions of Excel.
  4. The parameter “text” in the CODE function is mandatory. If left blank, the function will return a #VALUE! Error, which we can quickly resolve by providing an actual character or string as a parameter to the function.
  5. The return type of the CODE function is a numeric value.
  6. It is the inverse of the CHAR function in ExcelThe character function in Excel, also known as the char function, identifies the character based on the number or integer accepted by the computer language. For example, the number for character «A» is 65, so if we use =char(65), we get A.read more.  The CHAR function returns the corresponding character from a numeric ASCII value.
  7. We might observe a different output than the one shown in our examples on a Mac OS because Mac OS uses the Macintosh character set while Windows uses the ANSI character set.

CODE Function in Excel Video

Recommended Articles

This article is a guide to CODE in Excel. We discuss how to use the Excel CODE function and Excel examples, and downloadable Excel templates. You may also look at these useful functions in Excel: –

  • MAX Excel Function
  • FREQUENCY Function
  • TEXT Function in Excel
  • PROPER in Excel |Examples
  • Pivot Table Field Name Is Not Valid

What is the Text Function in Excel?

The TEXT function in Excel converts numbers from the numerical format to text format by using formatting codes. We can use it to display numbers as words, including symbols, while maintaining the numeric value. The TEXT function also helps concatenate numbers to formatted text strings or symbols.
Example, =TEXT(A6,”dd mmmm, yyyy”) converts the numerical Date 27-01-2023 into the text format 27 January, 2023

Text Function in Excel

Key Highlights

  • We use the TEXT function in Excel to convert Dates into a specific format.
  • It does not support a fractional format.
  • We use the TEXT function to combine numbers with characters or text.
  • We cannot combine the time, Date, #, and 0 in the TEXT function formula.
  • Excel gives an error #Name if there are no quotation marks around the argument ‘format_text’.

The Syntax for TEXT Function in Excel

The syntax for the TEXT function is

Text Function in Excel syntax

  • Value (required): It indicates the numeric value we want to convert to text. The value can be a number, Date, reference to a cell containing a numeric value, or any other function that returns a number or Date.
  • format_text (required): It is a format you want to apply. We must provide the argument as format code enclosed in quotation marks, g., “mm/dd/yy”.

How to Use the TEXT Function in Excel?

Consider the following examples to understand the use of the TEXT function:

You can download this TEXT Function Excel Template here – TEXT Function Excel Template

Example #1

Consider the below table, which shows a Date in “dd-mm-yyyy” format. We want to convert it into – “mmmm d, yyyy” using the TEXT function.

Text Function example 1

Solution:

Step 1: Place the cursor in cell C6 and enter the formula,

=TEXT(B6,”mmmm d,yyyy”)

example 1 sol step 1

Explanation:

  • B6: It is the cell containing an unformatted parameter (Date)
  • “mmmm d,yyyy”: The open and closed double quotes indicate the output in text format.
  • mmmm: Four times m indicates the month in complete spelling, i.e., January; To write month as only Jan, we need to put it three times, i.e., mmm (refer to the below image)

example 1 explanation

  • d: A single d indicates Dates in single digits, i.e., 2
  • yyyy: Four times y indicate the year in four digits, i.e., 2019

Step 2: Press Enter key to get the below result

example 1 sol step 2

Example #2

The table below shows the time and Dates in columns B and C, respectively. We want the values of the time and Date columns to appear together in column C.

Text Function in Excel Example 2

Solution:

Step 1: Place the cursor in cell D6

Note: If we use the CONCATENATE function to combine the values of columns B and C, it gives time in an incorrect format, as seen in the image below. Therefore, we need to use the TEXT function to provide the values in a proper form.

Eg step 1

Step 2: Enter the TEXT formula,

=TEXT(B6,”h:mm:ss AM/PM”)& ” “&TEXT(C6,”m/d/yyyy”)

eg 2 step 2

Explanation:

  • h:mm:ss AM/PM: It indicates the desired time format
  • &” “&: It acts as a separator between the two text
  • m/d/yyyy: It indicates the desired Date format

Step 3: Press Enter key to get the below result

Eg 2 step 3

The result is combined time and Date values in single cell D6.

Step 4: Drag the formula in other cells to get the below result

eg 2 step 4

Example #3

The below table shows the scientific notation of a list of mobile numbers with their country codes. We want to use the TEXT function to convert the mobile numbers into the correct and readable format.

Text Function in Excel example 3

Important: In a Microsoft Excel worksheet, when we enter a value with the number of digits greater than 11, Excel converts that value into a scientific notation in a non-readable format. We can use the TEXT function to convert it into a readable format.

Follow these steps to understand this-

Step 1: Place the cursor in cell D6 and enter the formula,

=TEXT(C6,”############”)

eg 3 step 1

Explanation:

  • C6: It is the cell containing the mobile number
  • ############: The 12-digit # codes convert numbers in scientific notation into readable format.

Step 2:  Press Enter key to get the below result

Eg 3 step 2

Step 3: Drag the formula in other cells to get the below result

eg 3 step 3

Tip: We can differentiate the country code from the mobile number by inserting a hyphen (-) at the desired location in the Text Formula

So,

Step 4: Modify the formula by inserting a hyphen (-) after two digits in the formula, as shown below,

Eg 3 step 4

Step 5: Drag the formula in other cells to get the below result

Eg 3 step 5

Using Concatenate and Text Function in Excel Together

We want to display the present day and Date using the TEXT function.

Solution:

Place the cursor in cell B5 and enter the formula,

=CONCATENATE(“Today is”,” “, TEXT(TODAY(),”dddd d mmm, yyy”))

Using Concatenate and Text Function in Excel

Explanation:

  • TODAY(): Indicates the present day of the week
  • dddd d mmm, yyy: Indicates the current Date with the day.

The formula combines (concatenates) the text Today is with the present day to give the result- Today is Wednesday 25 Jan, 2023.

How to Get the Format Codes for Text Function in Excel?

Format Codes for Text Function in Excel

To locate the format codes for time:

Right-click the desired cell > Go To Format Cells > Number > Custom > Select the desired time Type from list > OK.

Format Codes for Text Function in Excel 2

To locate the format codes for the Date:

Right-click the desired cell > Go To Format Cells > Number > Custom > Select the desired Date Type from the list > OK.

Format Codes for Text Function in Excel 3

Shortcut: To open Format Cells,

  1. Press CTRL+1 in windows, and
  2. +1 in Mac

List of Format Codes for TEXT Function in Excel

The Text function accepts most format codes used in Excel number formats. Below is a table with the most common and frequently used format codes.

Format Codes for TEXT Function in Excel 1

*In addition, we can include any of the below characters in the format code, and they will be displayed as entered.

Format Codes for TEXT Function

Format Codes used in Excel while dealing with Dates

Format Codes used in Excel while dealing with Dates

List of Built-in Excel Text Functions

Below is a list of built-in Text functions in Excel with their uses

Text excel function

Things to Remember

  • The Text function in Excel cannot convert numbers from 123 formats to One Two Three. To do so, we have to use Visual Basics (VBA).
  • The Text function converts a numeric value to a formatted text; therefore, we cannot use the result for calculation purposes.
  • The ‘format_text’ argument in the text function formula cannot contain an asterisk character (*).
  • TEXT function is available in the following versions of Microsoft Excel- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, and Excel 2000.

Frequently Asked Questions (FAQs)

Q1) What are the arguments of text function?

Answer: The TEXT function takes two arguments- value and format_text.

Value: It is the number we need to format as text. The function will not apply a format code if the argument is already text.

format_text: It is a text string (format) that we want to apply to the value. We must provide the argument in quotation marks to give the correct result.

Q2) How do you use the text function in sheets?

 Answer: To use the TEXT function in Google sheets, consider the below example

  1. Place the cursor in the cell where you want the result
  2. Type the formula,

=TEXT(A4,”HH mm”)

The formula will convert the time format from 12 Hrs format (4:15:00 PM) to 24 Hrs Format (16 15)

Q2

Q3) What is the use of text functions in Excel?

Answer: The TEXT function lets you convert numbers into a more readable format. We can change the appearance of numbers to the desired forms by applying the format codes in Excel.

Q4) How to use text function in excel?

Answer: To understand using the TEXT function, consider the below example,

  1. Place the cursor in cell B6
  2. Type the formula,

=TEXT(A6,”0%”)

The formula will convert the decimal 0.565 to the percentage format as 57%.

Q4

Recommended Articles

The above article is a guide to using Text Function in Excel. To learn about more Excel-related concepts, EDUCBA recommends the below-given articles.

  1. Excel Text with Formula
  2. Formatting Text in Excel
  3. Search For Text in Excel
  4. VBA Text

Работа с текстом в коде VBA Excel. Функции, оператор & и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

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

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


Понравилась статья? Поделить с друзьями:
  • Text file open in excel
  • Text boxes move in word
  • Text boxes in word online
  • Text boxes in word document
  • Text boxes in excel