Excel format all as number

Convert numbers stored as text to numbers

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

Numbers that are stored as text can cause unexpected results, like an uncalculated formula showing instead of a result. Most of the time, Excel will recognize this and you’ll see an alert next to the cell where numbers are being stored as text. If you see the alert, select the cells, and then click Excel Error Alert button to choose a convert option. 

Check out Format numbers to learn more about formatting numbers and text in Excel.

Cells with numbers stored as text with green triangles

If the alert button is not available, do the following:

1. Select a column

Selected column

Select a column with this problem. If you don’t want to convert the whole column, you can select one or more cells instead. Just be sure the cells you select are in the same column, otherwise this process won’t work. (See «Other ways to convert» below if you have this problem in more than one column.)

2. Click this button

Data tab, Text to Columns button

The Text to Columns button is typically used for splitting a column, but it can also be used to convert a single column of text to numbers. On the Data tab, click Text to Columns.

3. Click Apply

The rest of the Text to Columns wizard steps are best for splitting a column. Since you’re just converting text in a column, you can click Finish right away, and Excel will convert the cells.

4. Set the format

Currency format selected

Press CTRL + 1 (or Image of the MAC Command button icon + 1 on the Mac). Then select any format.

Note: If you still see formulas that are not showing as numeric results, then you may have Show Formulas turned on. Go to the Formulas tab and make sure Show Formulas is turned off.

Other ways to convert:

You can use the VALUE function to return just the numeric value of the text.

1. Insert a new column

New column next to text numbers

Insert a new column next to the cells with text. In this example, column E contains the text stored as numbers. Column F is the new column.

2. Use the VALUE function

Cell F23 with formula: =VALUE(E23) and result of 107.71

In one of the cells of the new column, type =VALUE() and inside the parentheses, type a cell reference that contains text stored as numbers. In this example it’s cell E23.

3. Rest your cursor here

Cursor resting on lower-right corner of cell

Now you’ll fill the cell’s formula down, into the other cells. If you’ve never done this before, here’s how to do it: Rest your cursor on the lower-right corner of the cell until it changes to a plus sign.

4. Click and drag down

Cursor dragged down, cells filled with formula

Click and drag down to fill the formula to the other cells. After that’s done, you can use this new column, or you can copy and paste these new values to the original column. Here’s how to do that: Select the cells with the new formula. Press CTRL + C. Click the first cell of the original column. Then on the Home tab, click the arrow below Paste, and then click Paste Special > Values.

If the steps above didn’t work, you can use this method, which can be used if you’re trying to convert more than one column of text.

  1. Select a blank cell that doesn’t have this problem, type the number 1 into it, and then press Enter.

  2. Press CTRL + C to copy the cell.

  3. Select the cells that have numbers stored as text.

  4. On the Home tab, click Paste > Paste Special.

  5. Click Multiply, and then click OK. Excel multiplies each cell by 1, and in doing so, converts the text to numbers.

  6. Press CTRL + 1 (or Image of the MAC Command button icon + 1 on the Mac). Then select any format.

Connect with an expert. Learn from live instructors.

Related topics

Replace a formula with its result

Top ten ways to clean your data

CLEAN function

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.

This post is going to show you all the ways you can convert text to numbers in Microsoft Excel.

An issue that comes up quite often in Excel is numbers that have been entered or formatted as text values.

This can cause many headaches when trying to troubleshoot why a formula like a SUM is not giving the correct answer.

Even though the data looks like a number, it can actually be a text value and will be ignored from any numerical calculations like a sum.

In this post, I will show you how you can identify such numbers which are stored as text values, and 7 ways you can use to convert the text into a proper number value.

How to Indentify Numbers Entered as Text

How can you tell if your number data has been entered as text?

There are quite a few easy ways to tell!

Left Aligned

The first way you might be able to tell if you have text values instead of numerical values is the way the data is aligned in the cell.

By default text is left aligned and numbers are right aligned.

Unless the alignment formatting has been changed from the default, this will be an easy way to spot numbers that have been formatted as text.

Green Triangle Error Checking

If you don’t realize you have numbers entered as text values, it can potentially cause some serious errors. This is why it’s flagged by Excel’s built-in error checker.

Any cells that are flagged with an error will show a small green triangle in the left of the cell to visually indicate an error.

When you select such a cell a small warning icon will appear.

When you click on this, it will show you what the error is. In this case, you can see the error is Number Stored as Text.

You can turn off this error checking entirely, or customize which errors are flagged.

Go to the File tab and then select Options at the bottom. This will open up the Excel Options menu.

In the Formula section of the Excel Options menu ➜ Error Checking.

Uncheck the Enable background error checking option to disable this feature. You can also customize the color used to indicate errors here.

Text Format Applied

One way that numbers get entered as text is when the cell has been formatted as text. This causes values to be entered as text values regardless of whether they are numerical.

There is a quick way to determine whether or not a cell has had text formatting applied.

Select the cell and go to the Home tab. You will be able to see if Text is the selected formatting in the dropdown menu found in the Number section of the ribbon.

Preceding Apostrophe

Another way that numbers can be entered as text is by using a preceding apostrophe.

When you enter an apostrophe ' as the first character in a cell, anything after will be regarded as a text value by Excel.

This means if you see a leading apostrophe in the formula bar, you know the data is a text value.

Use the ISTEXT Function

Excel has a function you can use to test if a value is a text value or not.

ISTEXT ( input )
  • input is the value, cell or range which you want to test if it is text.

The ISTEXT function will return TRUE if the value is text and FALSE otherwise.

= ISTEXT ( B3 )

Here you can see the ISTEXT function being used to determine if the cells contain text. The function returns TRUE when it finds a text value.

ISNUMBER ( input )
  • input is the value, cell or range which you want to test if it is a number.

Similarly, you can test if a value is a number using the ISNUMBER function. It takes a single input and returns TRUE when the value is a number and FALSE otherwise.

Here the same data is tested using the ISNUMBER function. The function returns FALSE when it does not find a number.

Status Bar Only Shows a Count

Another way to quickly test a range of cells to see if they are all text is by using the status bar.

When you select a range of numerical values, Excel will show you some basic statistics like the sum, min, max, and average in the status bar.

If they are all numbers entered as text values, then these basic statistics won’t be calculated. Instead, you will only see the count of the cells in the status bar.

Note: If just one of the cells is a numerical value, you will see the full set of statistics in the status bar.

Convert Text to Number with Error Checking

You have already seen that you can use error checking to spot numbers entered as text.

The error checking will also allow you to convert these text values into proper numbers.

Click on the Error icon and choose Convert to Number from the options. Excel will then convert each cell in the selected range into a number.

Note: This option can be very slow when you have a large number of cells to convert.

Convert Text to Number with Text to Column

Usually, Text to Columns is for splitting data into multiple columns. But with this trick, you can use it to convert text format into the general format.

Text to Column will let you choose a delimiter character to split your data based on. If you deselect this option and don’t pick any delimiter then it won’t split your data.

You are then able to choose how to format the results, and this is where you can choose a general format for the output.

Follow these steps to use the text to column feature to convert text to numbers.

  1. Select the cells that contain the text which you want to convert into number.
  2. Go to the Data tab.
  3. Click on the Text to Column command found in the Data Tools tab.

  1. Select Delimited in the Original data type options.
  2. Press the Next button.

  1. Press the Next button again in step 2 of the Convert Text to Columns wizard. You can keep the default options.

  1. Select General from the Column data format option.
  2. Select a Destination if you want to place the converted values in a new location. Otherwise you can keep the default value which should be the active cell, this will replace the text with numeric values.
  3. Press the Finish button.

This will convert your text values into numerical values.

The Text to Column command is usually used to split comma-separated or other delimiter separated data into multiple columns.

Any delimited data will be text data, so when Excel splits the data into multiple columns it also converts numerical data into numbers for added convenience.

This is also true even if there is nothing to split!

So the Text to Column wizard can be used to converts numerical text values to numbers.

Convert Text to Number with Multiply by 1

Even when values are stored as text you can still perform certain numerical calculations with them and the results of these calculations will also be numerical values.

You can use this to convert the text into numbers by multiplying them by 1. Since you are multiplying by 1, it won’t change the numbers but it will convert them.

= B3 * 1

You can use the above formula in an adjacent cell and copy and paste it down to convert an entire column.

If you want to remove the formula after, you can copy and paste them as values.

Convert Text to Number with Paste Special Multiply

Multiplying by 1 is a great trick for converting text to values, but you might not want to use a formula for this.

The great news is there is an easy way to multiply your text by 1 without using a formula.

This means you can convert your text in place and you don’t need to copy and paste formulas as values in an additional step.

You can use Paste Special Multiply to convert your text values. Follow these steps to multiply by 1 using Paste Special.

  1. Enter 1 into a cell elsewhere in the sheet. The 1 doesn’t even need to be a number value and can be a text value.
  2. Copy the cell which contains 1 using Ctrl + C on your keyboard or right click and choose Copy.
  3. Select the cells with the text values to convert.

  1. Press Ctrl + Alt + V on your keyboard or right click and choose Paste Special. This will open up the Paste Special menu.
  2. Select Values under the Paste options and select Multiply under the Operation options.
  3. Press the OK button.

This will multiply all the values by 1 which was the value in the copied cell. As a result, the text is converted into values, but since you are multiplying by 1 the numbers won’t change.

Convert Text to Number with VALUE Function

There is actually a dedicated function you can use for converting text to numerical values.

The VALUE function takes a text value and returns the text value as a number.

= VALUE ( text )
  • text is the text value you want to convert into a numerical value.

If the text contains any non-numerical characters, then the VALUE function will return a #VALUE! error. It doesn’t extract numbers from text, it can only convert numbers entered as text into numbers.

= VALUE ( B3 )

You can use the above formula to convert the text in cell B3 into a number and then copy and paste the formula to convert the entire column.

Convert Text to Number with Power Query

Power Query is an amazing tool for any type of data transformation required. It can certainly be used to convert text into numbers as well.

Power Query is strongly typed. This means calculations with incompatible data types will result in an error. So you won’t be able to multiply text values by 1 to convert them into numbers.

But Power Query does come with an easy way to convert data types, including text to numbers.

Follow these steps once your data has been imported into Power Query.

Click on the data type icon to the left side of the column heading for the values you want to convert.

Each column in the Power Query editor has a data type icon that displays the current data type of the column. If the column has not been assigned a data type, then the icon shown will be ABC123.

There are several numeric data types available in Power Query and which one you choose will depend on the level of decimal precision you need.

In this case, you can select the Whole Number option from the menu.

Notice the values in the column are now right-aligned and the data type icon has changed? These are visual indicators that the data type is now whole numbers instead of text.

= Table.TransformColumnTypes(Source,{{"Text", Int64.Type}})

You will see a new Changed Type step has been applied to the query and it will use the above M code formula.

You can then press the Close & Load button in the Home tab to save the results and load the data into Excel.

You might not even need to apply this data type conversion step to your query. When you first import data into Power Query, it will usually guess the data type and apply the conversion for you!

Convert Text to Number with Power Pivot

If you want to analyze or summarize your data after you convert it from text to numbers, then you might want to do the conversion in Power Pivot.

Power Pivot is an add-in that allows you to efficiently analyze millions of rows in the data model with Pivot Tables.

With Power Pivot, you can build row-level calculations using the DAX formula language to create new columns in your datasets. You can then access these new columns in your pivot tables connected to the data model.

In this case, the DAX formula you can use to convert text to numbers is the exact same as the formula in the grid.

Follow these steps inside the Power Pivot add-in to create a new calculated column that converts the text to numbers.

Select any cell under the Add Column heading.

=VALUE(TextNumbers[Text])

Insert the above formula. TextNumbers is the name of the table of data in Power Pivot and Text is the name of the column you want to convert.

Double click on the column heading to change the name.

Press the Save icon and close the Power Pivot add-in.

Now you can create a pivot table from the data model and this new column will be available for use inside the pivot table just like any other field.

  1. Go to the Insert tab.
  2. Click on the PivotTable button.
  3. Choose From Data Model in the available options.

The calculated column will be available in your pivot table fields list and you will be able to use it like any other number field.

Conclusions

There are many reasons why you might have data that contains numbers formatted as text.

If you want to freely use these values in your calculations, you will need to convert them into numbers.

Thankfully, there are many easy options to convert text to numbers such as error checking, paste special, basic multiplication, and the VALUE function. These are all easy ways to convert text inside the grid.

If you’re importing your data using Power Query or Power Pivot, you can perform the conversion inside each of these tools. Both have methods available to convert text to numbers.

Do you use any of these methods to change your text values to numbers? Do you know any other interesting ways to perform this action? Let me know in the comments below!

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

It’s common to find numbers stored as text in Excel. This leads to incorrect calculations when you use these cells in Excel functions such as SUM and AVERAGE (as these functions ignore cells that have text values in it). In such cases, you need to convert cells that contain numbers as text back to numbers.

Now before we move forward, let’s first look at a few reasons why you may end up with a workbook that has numbers stored as text.

  1. Using ‘ (apostrophe) before a number.
    • A lot of people enter apostrophe before a number to make it text. Sometimes, it’s also the case when you download data from a database. While this makes the numbers show up without the apostrophe, it impacts the cell by forcing it to treat the numbers as text.
  2. Getting numbers as a result of a formula (such as LEFT, RIGHT, or MID)
    • If you extract the numerical part of a text string (or even a part of a number) using the TEXT functions, the result is a number in the text format.

Now, let’s see how to tackle such cases.

Convert Text to Numbers in Excel

In this tutorial, you’ll learn how to convert text to numbers in Excel.

The method you need to use depends on how the number has been converted into text. Here are the ones that are covered in this tutorial.

  • Using the ‘Convert to Number’ option.
  • Change the format from Text to General/Number.
  • Using Paste Special.
  • Using Text to Columns.
  • Using a Combination of VALUE, TRIM, and CLEAN function.

Convert Text to Numbers Using ‘Convert to Number’ Option

When an apostrophe is added to a number, it changes the number format to text format. In such cases, you’ll notice that there is a green triangle at the top left part of the cell.

Convert Text to Numbers in Excel - Green Triangle

In this case, you can easily convert numbers to text by following these steps:

  • Select all the cells that you want to convert from text to numbers.Convert Text to Numbers in Excel - Select Cells Green Triangle
  • Click on the yellow diamond shape icon that appears at the top right. From the menu that appears, select ‘Convert to Number’ option.

This would instantly convert all the numbers stored as text back to numbers. You would notice that the numbers get aligned to the right after the conversion (while these were aligned to the left when stored as text).

Convert Text to Numbers by Changing Cell Format

When the numbers are formatted as text, you can easily convert it back to numbers by changing the format of the cells.

Here are the steps:

  • Select all the cells that you want to convert from text to numbers.
  • Go to Home –> Number. In the Number Format drop-down, select General.

This would instantly change the format of the selected cells to General and the numbers would get aligned to the right. If you want, you can select any of the other formats (such as Number, Currency, Accounting) which will also lead to the value in cells being considered as numbers.

Also read: How to Convert Serial Numbers to Dates in Excel

Convert Text to Numbers Using Paste Special Option

To convert text to numbers using Paste Special option:

Convert Text to Numbers Using Text to Column

This method is suitable in cases where you have the data in a single column.

Here are the steps:

  • Select all the cells that you want to convert from text to numbers.
  • Go to Data –> Data Tools –> Text to Columns.Convert Text to Numbers in Excel - text to column
  • In the Text to Column Wizard:

While you may still find the resulting cells to be in the text format, and the numbers still aligned to the left, now it would work in functions such as SUM and AVERAGE.

Convert Text to Numbers Using the VALUE Function

You can use a combination of VALUE, TRIM and CLEAN function to convert text to numbers.

  • VALUE function converts any text that represents a number back to a number.
  • TRIM function removes any leading or trailing spaces.
  • CLEAN function removes extra spaces and non-printing characters that might sneak in if you import the data or download from a database.

Suppose you want convert cell A1 from text to numbers, here is the formula:

=VALUE(TRIM(CLEAN(A1)))

If you want to apply this to other cells as well, you can copy and use the formula.

Finally, you can convert the formula to value using paste special.

You May Also Like the Following Excel Tutorials:

  • Multiply in Excel Using Paste Special.
  • How to Convert Text to Date in Excel (8 Easy Ways)
  • How to Convert Numbers to Text in Excel
  • Convert Formula to Values Using Paste Special.
  • Excel Custom Number Formatting.
  • Convert Time to Decimal Number in Excel
  • Change Negative Number to Positive in Excel
  • How to Capitalize First Letter of a Text String in Excel
  • Convert Scientific Notation to Number or Text in Excel
  • How To Convert Date To Serial Number In Excel?

When importing files or copying of the data with numeric values, you can often meet the problem: a number is converted to a text. As a result, formulas do not work and calculations become impossible. How you can fix this problem quickly? At the beginning we will see how to fix the error without macros.



How to convert the text in the number in Excel

Excel helps to an user to determine immediately, whether the values in the cells are formatted as the numbers or as the text. Numeric formats are aligned on the right, text — to the left.

When importing files or crashing in Excel to the numeric format becomes text, the green triangle appears in the upper left corner of the cells. This is the sign of error. The error occurs also if you put the apostrophe before the number.

before the number.

There are several methods of converting text to a number. So let`s consider the most simple and convenient methods.

  1. Use the button «Error» in the menu. When you highlight any cell with an error on the left, the corresponding icon appears. That`s what it is the button «Error». If you hover over it, the drop-down menu will appear (the black triangle). You need to select the column with numbers in text format. We open the menu of the button «Error» and click «Convert to Number».
  2. Convert to Number.

  3. You can apply any mathematical actions now. The simplest operations, that do not change the result (multiplication / division by one, adding / subtracting zero, raising to the first power, etc.) will do.
  4. simplest operations.

  5. You need to add to the special insert. You can also put into practice the simple arithmetic operation, but you do not need to create an auxiliary column here, but you do not need to create an auxiliary column. In the separate cell, to write the number 1 and to copy the cell in the clipboard (using the «Copy» button or the keyboard shortcut Ctrl + C). To highlight to the column with editable numbers. In the context menu of the «Paste» button, you need to click «Paste Special» and in the window that has opened to check the box next to «Multiply». After clicking OK, the text format is converted to a numeric format.
  6. Paste Special.

  7. Removing of non-printable symbols. Sometimes the numeric format is not recognized by the program because of invisible characters. We delete its using the formula that we enter into the auxiliary column. The CLEAN function removes to the unprintable characters, TRIM – are extra spaces, and the VALUE function converts a text format to a numeric one.
  8. CLEAN function.

  9. Using the «Text by Columns» tool, you need to select the column with the text arguments, that you want to convert in numbers. On the «DATA» tab we find the «Data Tools»-«Text by Columns» button, and after the « Convert Text to Columns Wizard» window opening, you need to click «Next». In the step-3, we pay attention to the column data format.

step-3.

The last method is suitable, if the values are in the same column.



The «Text-number» macro

You can convert to the numbers are saved as the text into the numbers with helping the macro.

There is the set of values stored in text format:

values stored in text format.

For inserting the macro, on the «DEVELOPER» tab we find the Visual Basic editor (ALT+F11). The editor window opens. For adding of the code, you need to press F7 and to paste the following code:

DEVELOPER.

To make it work, you need to save it, but the Excel workbook must be saved in the format that supports macros.

Now we come back to the page with the numbers: to select the column with the data and press the button «Macros». In the opened window – there is the list of available macros for this book, chose: «DEVELOPER»-«CODE»-«MACROS» the right one and click «Run».

Sub Conv()
    With ActiveSheet.UsedRange
        .Replace ",","."        
        arr = .Value
        .NumberFormat = "General"
        .Value = arr
    End With
End Sub

Macros.

The symbols moved to the right.

symbols to right.

Consequently, the values in the cells are «became» by the numbers.

Download example transformation text to number in Excel.

If in the column we can see the arguments with the certain number of decimal places (for example, 3.45), you may use to another macro.

Read also: How to translate the number and amount in words in Excel.

In this way, when you import or copy to the numeric data error you can easy to eliminate. To convert the text in a number you may in many ways (with and without macros) and to make it simple and fast. And subsequently with numerical arguments all necessary operations are performed.

Introduction

Number formats control how numbers are displayed in Excel. The key benefit of number formats is that they change how a number looks without changing any data. They are a great way to save time in Excel because they perform a huge amount of formatting automatically. As a bonus, they make worksheets look more consistent and professional.

Video: What is a number format

What can you do with custom number formats?

Custom number formats can control the display of numbers, dates, times, fractions, percentages, and other numeric values. Using custom formats, you can do things like format dates to show month names only, format large numbers in millions or thousands, and display negative numbers in red.

Sample custom number formats

Where can you use custom number formats?

Many areas in Excel support number formats. You can use them in tables, charts, pivot tables, formulas, and directly on the worksheet.

  • Worksheet — format cells dialog
  • Pivot Tables — via value field settings
  • Charts — data labels and axis options
  • Formulas — via the TEXT function

What is a number format?

A number format is a special code to control how a value is displayed in Excel. For example, the table below shows 7 different number formats applied to the same date, January 1, 2019:

Input Code Result
1-Jan-2019 yyyy 2019
1-Jan-2019 yy 19
1-Jan-2019 mmm Jan
1-Jan-2019 mmmm January
1-Jan-2019 d 1
1-Jan-2019 ddd Tue
1-Jan-2019 dddd Tuesday

The key thing to understand is that number formats change the way numeric values are displayed, but they do not change the actual values.

Where can you find number formats?

On the home tab of the ribbon, you’ll find a menu of build-in number formats. Below this menu to the right, there is a small button to access all number formats, including custom formats:

Number format menu on Home tab of Ribbon

This button opens the Format Cells dialog box. You’ll find a complete list of number formats, organized by category, on the Number tab:

Format Cells dialog box on Number tab

Note: you can open Format Cells dialog box with the keyboard shortcut Control + 1.

General is default

By default, cells start with the General format applied. The display of numbers using the General number format is somewhat «fluid». Excel will display as many decimal places as space allows, and will round decimals and use scientific number format when space is limited. The screen below shows the same values in column B and D, but D is narrower and Excel makes adjustments on the fly.

General number format in narrow column

How to change number formats

You can select standard number formats (General, Number, Currency, Accounting, Short Date, Long Date, Time, Percentage, Fraction, Scientific, Text) on the home tab of the ribbon using the Number Format menu.

Note: As you enter data, Excel will sometimes change number formats automatically. For example if you enter a valid date, Excel will change to «Date» format. If you enter a percentage like 5%, Excel will change to Percentage, and so on.

Shortcuts for number formats

Excel provides a number of keyboard shortcuts for some common formats:

Format Shortcut
General format Ctrl Shift ~
Currency format Ctrl Shift $
Percentage format Ctrl Shift %
Scientific format Ctrl Shift ^
Date format Ctrl Shift #
Time format Ctrl Shift @
Custom formats Control + 1

See also: 222 Excel Shortcuts for Windows and Mac

Where to enter custom formats

At the bottom of the predefined formats, you’ll see a category called custom. The Custom category shows a list of codes you can use for custom number formats, along with an input area to enter codes manually in various combinations.

Custom category in format cells dialog box

When you select a code from the list, you’ll see it appear in the Type input box. Here you can modify existing custom code, or to enter your own codes from scratch. Excel will show a small preview of the code applied to the first selected value above the input area.

Note: Custom number formats live in a workbook, not in Excel generally. If you copy a value formatted with a custom format from one workbook to another, the custom number format will be transferred into the workbook along with the value.

How to create a custom number format

To create custom number format follow this simple 4-step process:

  1. Select cell(s) with values you want to format
  2. Control + 1 > Numbers > Custom
  3. Enter codes and watch preview area to see result
  4. Press OK to save and apply 

Tip: if you want base your custom format on an existing format, first apply the base format, then click the «Custom» category and edit codes as you like.

How to edit a custom number format

You can’t really edit a custom number format per se. When you change an existing custom number format, a new format is created and will appear in the list in the Custom category. You can use the Delete button to delete custom formats you no longer need.

Warning: there is no «undo» after deleting a custom number format!

Structure and Reference

Excel custom number formats have a specific structure. Each number format can have up to four sections, separated with semi-colons as follows:

Custom number format structure

This structure can make custom number formats look overwhelmingly complex. To read a custom number format, learn to spot the semi-colons and mentally parse the code into these sections:

  1. Positive values
  2. Negative values
  3. Zero values
  4. Text values

Not all sections required

Although a number format can include up to four sections, only one section is required. By default, the first section applies to positive numbers, the second section applies to negative numbers, the third section applies to zero values, and the fourth section applies to text.

  • When only one format is provided, Excel will use that format for all values.
  • If you provide a number format with just two sections, the first section is used for positive numbers and zeros, and the second section is used for negative numbers.
  • To skip a section, include a semi-colon in the proper location, but don’t specify a format code.

Characters that display natively

Some characters appear normally in a number format, while others require special handling. The following characters can be used without any special handling:

Character Comment
$ Dollar
+- Plus, minus
() Parentheses
{} Curly braces
<> Less than, greater than
= Equal
: Colon
^ Caret
Apostrophe
/ Forward slash
! Exclamation point
& Ampersand
~ Tilde
  Space character

Escaping characters

Some characters won’t work correctly in a custom number format without being escaped. For example, the asterisk (*), hash (#), and percent (%) characters can’t be used directly in a custom number format – they won’t appear in the result. The escape character in custom number formats is the backslash (). By placing the backslash before the character, you can use them in custom number formats:

Value Code Result
100 #0 #100
100 *0 *100
100 %0 %100

Placeholders

Certain characters have special meaning in custom number format codes. The following characters are key building blocks:

Character Purpose
0 Display insignificant zeros
# Display significant digits
? Display aligned decimals
. Decimal point
, Thousands separator
* Repeat following character
_ Add space
@ Placeholder for text

Zero (0) is used to force the display of insignificant zeros when a number has fewer digits than zeros in the format. For example, the custom format 0.00 will display zero as 0.00, 1.1 as 1.10 and .5 as 0.50.

Zero placeholder examples

Pound sign (#) is a placeholder for optional digits. When a number has fewer digits than # symbols in the format, nothing will be displayed. For example, the custom format #.## will display 1.15 as 1.15 and 1.1 as 1.1.

Pound placeholder examples

Question mark (?) is used to align digits. When a question mark occupies a place not needed in a number, a space will be added to maintain visual alignment. 

Question mark placeholder examples

Period (.) is a placeholder for the decimal point in a number. When a period is used in a custom number format, it will always be displayed, regardless of whether the number contains decimal values.

Comma (,) is a placeholder for the thousands separators in the number being displayed.  It can be used to define the behavior of digits in relation to the thousands or millions digits.

Comma placeholder examples

Asterisk (*) is used to repeat characters. The character immediately following an asterisk will be repeated to fill remaining space in a cell.

Asterisk placeholder examples

Underscore (_) is used to add space in a number format. The character immediately following an underscore character controls how much space to add. A common use of the underscore character is to add space to align positive and negative values when a number format is adding parentheses to negative numbers only. For example, the number format «0_);(0)» is adding a bit of space to the right of positive numbers so that they stay aligned with negative numbers, which are enclosed in parentheses.

Underscore placeholder examples

At (@) — placeholder for text. For example, the following number format will display text values in blue:

0;0;0;[Blue]@

See below for more information about using color.

Automatic rounding

It’s important to understand that Excel will perform «visual rounding» with all custom number formats. When a number has more digits than placeholders on the right side of the decimal point, the number is rounded to the number of placeholders. When a number has more digits than placeholders on the left side of the decimal point, extra digits are displayed. This is a visual effect only; actual values are not modified.

Number formats for TEXT

To display both text along with numbers, enclose the text in double quotes («»).  You can use this  approach to append or prepend text strings in a custom number format, as shown in the table below.

Value Code Result
10 General» units» 10 units
10 0.0″ units» 10.0 units
5.5 0.0″ feet» 5.5 feet
30000 0″ feet» 30000 feet
95.2 «Score: «0.0 Score: 95.2
1-Jun «Date: «mmmm d Date: June 1

Number formats for DATES

Dates in Excel are just numbers, so you can use custom number formats to change the way they display. Excel has many specific codes you can use to display components of a date in different ways. The screen below shows how Excel displays the date in D5, September 3, 2018, with a variety of custom number formats:

Number format codes for dates

Number formats for TIME

Times in Excel are fractional parts of a day. For example, 12:00 PM is 0.5, and 6:00 PM is 0.75. You can use the following codes in custom time formats to display components of a time in different ways. The screen below shows how Excel displays the time in D5, 9:35:07 AM, with a variety of custom number formats:

Number format codes for times

Note: m and mm can’t be used alone in a custom number format since they conflict with the month number code in date format codes.

Number formats for ELAPSED TIME

Elapsed time is a special case and needs special handling. By using square brackets, Excel provides a special way to display elapsed hours, minutes, and seconds. The following screen shows how Excel displays elapsed time based on the value in D5, which represents 1.25 days:

Number format codes for elapsed time

Number formats for COLORS

Excel provides basic support for colors in custom number formats. The following 8 colors can be specified by name in a number format: [black] [white] [red][green] [blue] [yellow] [magenta] [cyan]. Color names must appear in brackets.

Custom number format with colors

Colors by index

In addition to color names, it’s also possible to specify colors by an index number (Color1,Color2,Color3, etc.) The examples below are using the custom number format: [ColorX]0″▲▼», where X is a number between 1-56:

[Color1]0"▲▼" // black
[Color2]0"▲▼" // white
[Color3]0"▲▼" // red
[Color4]0"▲▼" // green
etc.

The triangle symbols have been added only to make the colors easier to see. The first image shows all 56 colors on a standard white background. The second image shows the same colors on a gray background. Note the first 8 colors shown correspond to the named color list above.

Custom number format colors on white

Custom number format colors on gray background

Apply number formats in a formula

Although most number formats are applied directly to cells in a worksheet, you can also apply number formats inside a formula with the TEXT function. For example, with a valid date in A1, the following formula will display the month name only:

=TEXT(A1,"mmmm")

The result of the TEXT function is always text, so you are free to concatenate the result of TEXT to other strings:

="The contract expires in "&TEXT(A1,"mmmm")

The screen below shows the number formats in column C being applied to numbers in column B using the TEXT function:

Applying number formats with the TEXT function

One quirk of the TEXT function relates to double quotes («») that are part of certain custom number formats. Because the format_text is entered as a text string, Excel won’t allow you to enter the formula without removing the quotes or adding more quotes. For example, to display a large number in thousands, you can use a custom number format like this:

0, "k"

Notice k appears in quotes («k»). To apply the same format with the TEXT function, you can use simply:

=TEXT(A1,"0, k")

Notice the k is not surrounded by quotes. Alternately, you can add extra double quotes as below, which returns the same result:

=TEXT(A1,"0,""K""")

This behavior only occurs when you are hardcoding a format inside TEXT. If you are applying a format entered elsewhere on the worksheet (as in cells C6 and C9 in the worksheet above) you can use a standard number format.

Measurements

You can use a custom number format to display numbers with an inches mark («) or a feet mark (‘). In the screen below, the number formats used for inches and feet are:

0.00 ' // feet
0.00 " // inches

Number formats for feet and inches

These results are simplistic, and can’t be combined in a single number format. You can however use a formula to display feet together with inches.

Conditionals

Custom number formats also up to two conditions, which are written in square brackets like [>100] or [<=100]. When you use conditionals in custom number formats, you override the standard [positive];[negative];[zero];[text] structure. For example, to display values below 100 in red, you can use:

[Red][<100]0;0

To display values greater than or equal to 100 in blue, you can extend the format like this:

[Red][<100]0;[Blue][>=100]0

Conditions with custom number formats

To apply more than two conditions, or to change other cell attributes, like fill color, etc. you’ll need to switch to Conditional Formatting, which can apply formatting with much more power and flexibility using formulas.

Plural text labels

You can use conditionals to add an «s» to labels greater than zero with a custom format like this:

[=1]0″ day»;0″ days»

Custom number format for plural text

Telephone numbers

Custom number formats can also be used for telephone numbers, as shown in the screen below:

Custom number format for telephone numbers

Notice the third and fourth examples use a conditional format to check for numbers that contain an area code. If you have data that contains phone numbers with hard-coded punctuation (parentheses, hyphens, etc.) you will need to clean the telephone numbers first so that they only contain numbers.

Hide all content

You can actually use a custom number format to hide all content in a cell. The code is simply three semi-colons and nothing else ;;;

To reveal the content again, you can use the keyboard shortcut Control + Shift + ~, which applies the General format.

Other resources

  • Developer Bryan Braun built a nice interactive tool for building custom number formats

If you used Excel in any shape or form, there is a pretty good chance that you’ve used the formatting and number formatting features. Formatting options like number, currency, percentage, date and time values are easily accessible to users. However, that’s not all there is in the world of text and number formatting. Going down the rabbit hole, custom formatting can help you fully configure Excel’s built-in settings for formatting.

The main advantage of this approach is that you can alter the look of your data without changing the actual values. This means that you do not need to use additional spaces or formulas to create the layout you want and preserve the raw data.

If you want to modify your data anyways, or need to change a value inside a formula, you can use the TEXT function with all custom formatting syntax we are going to cover in this article. It should be noted that the TEXT function returns a text, and the return value cannot be used in mathematical calculations. If you do, you will receive a #VALUE! error. In this article we’re going to be using a workbook template. You can download it below.

How to create a custom number format in Excel

  1. Select the cell to be formatted and press Ctrl+1 to open the Format Cells dialog. An alternative way to do is by right-clicking the cell and then going to Format Cells > Number Tab.
  2. Under Category, select Custom.
  3. Type in the format code into the Type
  4. Click OK to save your changes.

Note: In Format Cells dialog you can modify the built-in format codes by selecting the format you want to modify in its own category (i.e. Currency > ($1,234.10)) and then selecting Custom Category. Don’t worry, Excel will not let you delete built-in formats.

Number Formatting in Excel - All You Need to Know

Basics

Syntax

The format code has 4 sections separated by semicolons.

POSITIVE; NEGATIVE; ZERO; TEXT

These sections are optional,

  • If a code contains only 1 section, the format is applied to all number types — positive, negative and zero.
  • If a code contains 2 sections, the first section is used for positive and zero values, while the second section is applied to negative values.
  • If a code contains 3 sections, the first is for positive, the second is for negative, and the third is for zero.
  • A code only affects text values if all sections exist.

Default format type in Excel is called General. You can type General for sections you don’t want formatted. Make sure you use a minus sign (-) with General if you want to skip negative values.

If you want to completely hide a type, leave it blank after the semicolon. For example; to hide 0 values, General;-General;;General

Placeholders and the Cheat Sheet

Placeholder Description Raw Value Format Code Formatted Value
General Default format 1234.567 General 1234.567
# Placeholder for digits (numbers) and does not add any leading zeroes. 1234.567 #####.#### 1234.567
0 Placeholder for digits (numbers) and add any leading zeroes. 1234.567 00000.0000 01234.5670
? Placeholder for digits (numbers) and add space characters. 1234.567 ?????.????  1234.567
. Placeholder for the decimal place. 1234.567 0.00 1234.57
_ Adds a blank space, to the width of the following character. You can use in combination with parentheses to add left and right indents, _( and _) respectively. 99 _(#_);(#)  99
-25 (25)
58  58
12  12
-71 (71)
36  36
* Repeats the character after asterisk until the width of the cell is filled. 66 0 *! 66 !!!!!!!!!!!!!!!
Full Name @ *_ Full Name ____
% Convert value to a percentage with % sign 0.12 % 12%
, Thousands separator 1234.567 #, 1
12345678 #, 12,346
12345678 #,###, 12,346
12345678 #,, 12
E Scientific notation format. Requires a ‘+’ symbol after, and a digit placeholder before and after. 1234.567 0.00E+00 1.23E+03
/ Represents fractions 1.234 # ##/## 1 11/47
1.234 # 000/000 1 117/500
1.234 ##/## 58/47
«» Text placeholder for multiple characters 1234.567 #,##0 «km/h» 1,235 km/h
Good «Result is: «@ Result is: Good
Text placeholder for single character 1234 #.00, K 1.23 K
1234567 #.00,, M 1.23 M
@ Placeholder for text Bad «Result is: «@ Result is: Bad
[color] Change Color of value. Options: [Black], [Green], [White], [Blue], [Magenta], [Yellow], [Cyan], [Red] 1234.567 [Green]#,##0.00_);
[Red](#,##0.00);
[Blue]0.00_);
[Magenta]@
1,234.57
-1234.567 (1,234.57)
0 0.00
This is a text This is a text

Common Practices

Display and control of the first digit and decimals

Decimal places in the code are indicated with a period (.). Number of zeroes after the period (.) define the number of decimal places. For example,

  • 0 — display 1 decimal place
  • 00 — display 2 decimal places

If the number has more decimals than the decimal placeholders defined, the number will be rounded to the nearest number of placeholders.

Raw Value Format Code Formatted Value
123.4 0.0 123.4
123.4 0.00 123.40
123.45 0.00 123.45
123.45 0.00 123.46
123.456 0.0 123.5

Alternatively, hash (#) and question mark (?) symbols can be used as decimal places. However, because any missing decimal places will be filled with zeroes, using zeroes instead will be easier to read.

Raw Value Format Code Formatted Value
0.25 0.00 0.25
0.25 #.## .25
123 0.00 123.0
123 #.?? 123.00
123 #.## 123.

Add text to numbers

Custom text can be added to the beginning or the end of a value. Text and characters should be added inside quotes («») and backslashes (). You can use backslash () to add single character.

Raw Value Format Code Formatted Value
123.4 0.0 «ft.» 123.4 ft.
123.4 0.00 l 123.40 l
123.45 «Approx.» 0 Approx. 123
123.45 «Result:» 0.00 C Result: 123.46 C
Bad «Result is: «@ Result is: Bad

Quotation marks or backslashes are not necessary for spaces ( ) and some special characters.

Symbol Description
+ and — Plus and minus signs
( ) Left and right parenthesis
: Colon
^ Caret
Apostrophe
{ } Curly brackets
< > Less-than and greater than signs
= Equal sign
/ Forward slash
! Exclamation point
& Ampersand
~ Tilde
Space character

Below are some special characters you can use by copying or typing in the numerical code while pressing down Alt button.

Symbol Code Description
Alt+0153 Trademark
© Alt+0169 Copyright symbol
° Alt+0176 Degree symbol
± Alt+0177 Plus-Minus sign
µ Alt+0181 Micro sign

Hide value

If you leave any number of sections blank, the value of those sections will be hidden. A section should always be separated (defined) by a semicolon (;). Here are some examples,

Raw Value Format Code Formatted Value
1 0;;0; 1
-2 0;;0;
0 0;;0; 0
Some text 0;;0;
1 ;(0);;@
-2 ;(0);;@ (2)
0 ;(0);;@
Some text ;(0);;@ Some Text
1 ;;;
-2 ;;;
0 ;;;
Some text ;;;

Replace zeroes with dashes

Zeroes can make data tables look more complicated than they actually are. You can hide them completely by using the previous method, or replace them with any character of your choice. Dash (-) is a common example. All you need to is place a dash into the ‘Zero section’.

Raw Value Format Code Formatted Value
0 General;-General;»-«;General
3487 General;-General;»-«;»-«
12 #,##0.00;(#,##0.00);»-«;

Start with zeroes

If try to enter a ZIP number that starts with 0, the leading zeroes will be removed automatically by Excel. To keep the leading zeros, use zero (0) placeholder for whole numbers.

Raw Value Format Code Formatted Value
10010 00000 10010
3487 00000 03487
12 00000 00012
0 00000 00000
123456 00000 123456

Dealing with thousands, millions, and more

You may have noticed that ‘0.0’ or other simple formats do not separate thousands or millions. Adding a comma into the code will insert commas to separate numbers.

Raw Value Format Code Formatted Value
1234 #,##0 1,234
123456 #,##0 123,456
12345678 #,##0 12,345,678
123456.789 #,##0 123,457
123456.789 #,##0.0 123,456.8

There must be placeholders for numbers smaller than one thousand, otherwise such values will be hidden. This behavior allows us to round and format our value to show only thousands or millions.

Raw Value Format Code Formatted Value
1234 #, 1
123456 #, 123
12345678 #, 12345
12345678 #,, 12
123456 #.0, K 123.5 K
12345678 #.0,, M 12.3 M

Display numbers as phone numbers

Phone numbers can be hard to read without any separators. Custom Number Format Codes is perfect for this job. The hash (#) character should be your best bet to avoid any redundancy of placeholders (0, ?)

Raw Value Format Code Formatted Value
1234567890 (###) ###-#### (123) 456-7890
12345678900 (###) #### #### (123) 4567 8900
1234567890 (##) #### #### (12) 3456 7890

Showing Month and Weekday Names

Date and time values are stored as numbers in Excel. When you enter a date, Excel automatically converts it into a numerical value, and then formats the cell.

Before jumping into the code, let’s review some basics. Formatting code has special placeholders for date and time formatting that behave a bit differently. For example, while m and mm will show month as a number, mmm and mmmm will show as a text string. Below are some examples.

Raw Value Format Code Formatted Value
4/1/2018 m 4
4/1/2018 mm 04
4/1/2018 mmm Apr
4/1/2018 mmmm April
4/1/2018 mmmmm A
4/1/2018 d 1
4/1/2018 dd 01
4/1/2018 ddd Sun
4/1/2018 dddd Sunday
4/1/2018  11:59:31 PM dddd, mmmm dd, yyyy h:mm AM/PM;@ Sunday, April 01, 2018 11:59 PM

Here is the full list of options for the date 4/1/2018 23:59:31 ,

Format Code Description Example (4/1/2018 23:59:31)
yyyy Displays the year as a four-digit number. 2018
yy Displays the year as a two-digit number. 18
m Displays the month as a number without a leading zero. 4
mm Displays the month with a leading zero. 04
mmm Displays the month as text, as an abbreviation. Apr
mmmm Displays the month as text. April
mmmmm Displays the month as a single character A
d Displays the day as a number, without a leading zero. 1
dd Displays the day as a number, with a leading zero. 01
ddd Displays the day as a day of the week, as an abbreviation. Sun
dddd Displays the day as a day of the week, without abbreviation Sunday
h Displays the hour without a leading zero. 23
hh Displays the hour with a leading zero. 23
[h] Displays elapsed time in hours (to be used when the time value exceeds 24 hours). 1036607
m Displays the minute without a leading zero. 4
mm Displays the minute with a leading zero. 04
[m] Displays elapsed time in minutes (to be used when the time value exceeds 60 minutes). 62196479
s Displays the second without a leading zero. 31
ss with a leading zero. 31
[s] Displays elapsed time in seconds (to be used when the time value exceeds 60 seconds). 3731788771
AM/PM Converts to 12-hour time. Displays either AM/am/A/a or PM/pm/P/p depending on the time of day. PM
am/pm pm
A/P P
a/p p

Come in Colors Everywhere

Number Formatting can be used color sections of a code. A common example is using the color red for negative numbers. Color code must be placed inside square brackets (i.e. [color]), and entered at the beginning of a section. Here are some available colors,

  • [Black]
  • [Blue]
  • [Cyan]
  • [Green]
  • [Magenta]
  • [Red]
  • [White]
  • [Yellow]
Raw Value Format Code Formatted Value
1234.567 [Green]#,##0.00_);[Red](#,##0.00);[Blue]0.00);[Magenta]@ 1,234.57
-1234.567 (1,234.57)
0 0.00
This is a text This is a text

Conditions

Although Excel has conditional formatting menu, basic conditions can be applied through code. Condition should be placed inside square brackets (i.e. [condition]) just like colors. Conditions are similar to the conditions in some functions (i.e. SUMIF). First add a logical operator, and then a value. For example, “[>=1000000]” means “if value of cell is greater than or equal to 1,000,000 apply the following format”. Conditions should come before the actual code, again, just like with colors. If you want to a color as well, the color code should come first.

Another important thing to note here is, that section structure changes from Positive, Negative, Zero, Text to First Condition, Second Condition (if exists), if previous conditions are not applied. There should be at least two sections for conditions.

If you enter only one condition code and then save the format, Excel will automatically add the second section with «;General». This means that if the condition is not met, General format will be used.

Raw Value Format Code Formatted Value
1234567890 [>=1000000]#,##0,,»M»;[>=1000]#,##0,»K»;0 1,235M
12345 12K
1 [=1]0″ apple»;0″ apples» 1 apple
10 10 apples
25 [Green][>=85]»PASSED»;[Blue][>=60]»RE-CHECK»;[Red]»FAILED» FAILED
72 RE-CHECK
91 PASSED

Skip to content

Как преобразовать текст в число в Excel — 10 способов.

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

Иногда значения в ваших таблицах Excel выглядят как числа, но их нельзя сложить или перемножить, они приводят к ошибкам в формулах. Общая причина этого — числа, записанные как текст. Во многих случаях Microsoft Excel достаточно умен, чтобы автоматически преобразовывать цифровые символы, импортированные из других программ, в обычные числа. Но иногда числа остаются отформатированными в виде текста, что вызывает множество проблем в ваших электронных таблицах.

Перестает правильно работать сортировка данных, поскольку числовые и текстовые значения упорядочиваются по-разному. Функции поиска, подобные ВПР, также не могут найти нужные значения (подробнее об этом читайте – Почему не работает ВПР?). Подсчет по условиям СУММЕСЛИ и СЧЁТЕСЛИ даст неверные результаты. Если они находятся среди «нормальных» чисел, то функция СУММ их проигнорирует, а вы этого даже не заметите. В результате – неверные расчеты.

  • Как выглядят числа-как текст?
  • Используем индикатор ошибок.
  • Изменение формата ячейки может преобразовать текст в число
  • Специальная вставка
  • Инструмент «текст по столбцам»
  • Повторный ввод
  • Формулы для преобразования текста в число
  • Как можно использовать математические операции
  • Удаление непечатаемых символов
  • Использование макроса VBA
  • Как извлечь число из текста при помощи инструмента Ultimate Suite

Из этого материала вы узнаете, как преобразовать строки в «настоящие» числа.

Как определить числа, записанные как текст?

В Excel есть встроенная функция проверки ошибок, которая предупреждает вас о возможных проблемах со значениями ячеек. Это выглядит как маленький зеленый треугольник в верхнем левом углу ячейки. При выборе ячейки с таким индикатором ошибки отображается предупреждающий знак с желтым восклицательным знаком (см. Скриншот ниже). Наведите указатель мыши на этот знак, и Excel сообщит вам о потенциальной проблеме: в этой ячейке число сохранено как текст или перед ним стоит апостроф .

индикатор ошибки

В некоторых случаях индикатор ошибки не отображается для чисел, записанных в виде текста. Но есть и другие визуальные индикаторы текстовых чисел:

Число

Строка (текстовое значение)

    • По умолчанию с выравниванием по правому краю.
    • Если выбрано несколько ячеек, в строке состояния отображается «Среднее», «Количество» и «Сумма» .
    • По умолчанию с выравниванием по левому краю.
    • Если выбрано несколько ячеек, строка состояния показывает только Количество .
    • В поле Числовой формат отображается текстовый формат (во многих случаях, но не всегда).
    • В строке формул может быть виден начальный апостроф.
    • Зелёный треугольник в левом верхнем углу.

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

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

Используем индикатор ошибок.

Если в ваших клетках отображается индикатор ошибки (зеленый треугольник в верхнем левом углу), преобразование выполняется одним щелчком мыши:

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

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

Смена формата ячейки.

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

Итак, первый быстрый способ видоизменения заключается в следующем:

  1. Выберите ячейки с цифрами в текстовом формате.
  2. На вкладке «Главная » в группе «Число» выберите « Общий» или « Числовой» в раскрывающемся списке «Формат» .

применяем числовой формат

Или же можно воспользоваться контекстным меню, вызвав его правым кликом мышки.

как изменить формат

Последовательность действий в этом случае показана на рисунке. В любом случае, нужно применить числовой либо общий формат.

Этот способ не слишком удобен и достался нам «в наследство» от предыдущих версий Excel, когда еще не было индикатора ошибки в виде зелёного уголка.

Примечание. Этот метод не работает в некоторых случаях. Например, если вы примените текстовый формат, запишете несколько цифр, а затем измените формат на «Числовой». Тут ячейка все равно останется отформатированной как текст.

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

Совет. Если зеленых уголков нет совсем, то проверьте — не выключены ли они в настройках вашего Excel (Файл — Параметры — Формулы — Числа, отформатированные как текст или с предшествующим апострофом).

Специальная вставка.

По сравнению с предыдущими методами этот метод требует еще нескольких дополнительных шагов, но работает почти на 100%.

Чтобы исправить числа, отформатированные как текст с помощью специальной вставки, выполните следующие действия:

  1. Выделите клетки таблицы с текстовым номером и установите для них формат «Общий», как описано выше.
  2. Скопируйте какую-нибудь пустую ячейку. Для этого либо установите в нее курсор и нажмите Ctrl + C, либо щелкните правой кнопкой мыши и выберите «Копировать» в контекстном меню.
  3. Выберите клетки таблицы, которые вы хотите трансформировать, щелкните правой кнопкой мыши и выберите «Специальная вставка». В качестве альтернативы, нажмите комбинацию клавиш Ctrl + Alt + V.
  4. В диалоговом окне «Специальная вставка» выберите «Значения» в разделе «Вставить» и затем «Сложить» в разделе «Операция».
  5. Нажмите ОК.

конвертируем в число при помощи специальной вставки

Если все сделано правильно, то ваши значения изменят выравнивание слева на правую сторону. Excel теперь воспринимает их как числа.

Инструмент «текст по столбцам».

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

  1. Выберите позиции (можно и весь столбец), которые вы хотите конвертировать, и убедитесь, что их формат установлен на Общий.
  2. Перейдите на вкладку «Данные», группу «Инструменты данных» и нажмите кнопку «Текст по столбцам» .
  3. На шаге 1 мастера распределения выберите «С разделителями» в разделе «Формат исходных данных» и сразу чтобы завершить преобразование, нажмите «Готово» .

преобразуем столбец в цифры при помощи инструмента «Текст по столбцам»

Это все, что нужно сделать!

Повторный ввод.

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

Для этого сначала установите их формат на «Обычный». Затем в каждую из них введите цифры заново.

Думаю, вы знаете, как корректировать ячейку — либо двойным кликом мышки, либо через клавишу F2.

Но это, конечно, если таких «псевдо-чисел» немного. Иначе овчинка не стоит выделки. Есть много других менее трудоемких способов.

Преобразовать текст в число с помощью формулы

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

В Microsoft Excel есть специальная функция — ЗНАЧЕН (VALUE в английском варианте). Она обрабатывает как текст в кавычках, так и ссылку на элемент таблицы, содержащий символы для трансформирования.

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

Например, распознает цифры, записанные с разделителем тысяч в виде пробела:

=ЗНАЧЕН(«1 000»)

Конвертируем число, введенное с символом валюты и разделителем тысяч:

=ЗНАЧЕН(«1 000 $»)

Обе эти формулы возвратят число 1000.

Точно так же она расправляется с пробелами перед цифрами.

функция VALUE ЗНАЧЕН

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

Функция ЗНАЧЕН также пригодится, когда вы извлекаете что-либо из символьной строки с помощью одной из текстовых функций, таких как ЛЕВСИМВ, ПРАВСИМВ и ПСТР.

Например, чтобы получить последние 3 символа из A2 и вернуть результат в виде цифр, используйте следующее:

=ЗНАЧЕН(ПРАВСИМВ(A2;3))

На приведенном ниже рисунке продемонстрирована формула трансформации:

конвертируем при помощи формулы

Если вы не обернете функцию ПРАВСИМВ в ЗНАЧЕН, результат будет возвращен в виде набора символов, что делает невозможным любые вычисления с извлеченными значениями.

Этот метод подходит, когда вы точно знаете, сколько символов и откуда вы желаете получить, а затем превратить их в число.

Математические операции.

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

Что это может быть? Например, сложение с нулём, умножение или деление на 1.

=A2+0

=A2*1

=A2/1

простейшие математические операции для превращения текста в числа

Важно, чтобы эти действия не изменили величины чисел. Выше вы видите пример таких операций: двойное умножение на минус 1, умножение на 1, сложение с 0. Наиболее элегантно и просто для ввода выглядит «двойное отрицание»: ставим два минуса перед ссылкой, то есть дважды умножаем на минус 1. Результат расчета не изменится, а записать такую формулу очень просто.

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

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

Удаление непечатаемых символов.

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

Эту напасть можно удалить программным путем при помощи формулы. Аналогично предыдущему примеру, в С2 можно записать примерно такое выражение:

=ЗНАЧЕН(СЖПРОБЕЛЫ(ПЕЧСИМВ(A2)))

Поясню, как это работает. Функция ПЕЧСИМВ удаляет непечатаемые знаки. СЖПРОБЕЛЫ – лишние пробелы. Функция ЗНАЧЕН, как мы уже говорили ранее, преобразует текст в число.

Макрос VBA.

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

Нажмите сочетание клавиш Alt+F11 или откройте вкладку Разработчик (Developer) и нажмите кнопку Visual Basic. В появившемся окне редактора добавьте новый модуль через меню Insert — Module и скопируйте туда следующее небольшое выражение:

Sub Текст_в_число()   
   Dim rArea As Range
   On Error Resume Next
   ActiveWindow.RangeSelection.SpecialCells(xlCellTypeConstants).Select
   If Err Then Exit Sub
   With Application: .ScreenUpdating = False: .EnableEvents = False: .Calculation = xlManual: End With
   For Each rArea In Selection.Areas
   rArea.Replace ",", "."
   rArea.FormulaLocal = rArea.FormulaLocal
   Next rArea
   With Application: .ScreenUpdating = True: .EnableEvents = True: .Calculation = xlAutomatic: End With
End Sub

После этого закрываем редактор, выполнив нажатие стандартной кнопки закрытия в верхнем правом углу окна.

Что делает этот макрос?

Вы можете выделить несколько областей данных для конвертации (можно использовать мышку при нажатой клавише CTRL). При этом, если в ваших числах в качестве разделителя десятичных разрядов используется запятая, то она будет автоматически заменена на точку. Ведь в Windows чаще всего именно точка отделяет целую и дробную части числа. А при экспорте данных из других программ запятая в этой роли встречается почему-то очень часто.

Чтобы использовать этот код, выделяем область на рабочем листе, которую нужно преобразовать. Жмем на значок «Макросы», который расположен на вкладке «Разработчик» в группе «Код». Или нам поможет комбинация клавиш ALT+F8.

Открывается окно имеющихся макросов. Находим «Текст_в_число», указываем на его и жмем на кнопку «Выполнить».

Извлечь число из текстовой строки с помощью Ultimate Suite

Как вы уже убедились, не существует универсальной формулы Excel для извлечения числа из текстовой строки. Если у вас возникли трудности с пониманием формул или их настройкой для ваших наборов данных, вам может понравиться этот простой способ получить число из строки в Excel.

Надстройка Ultimate Suite предоставляет множество инструментов для работы с текстовыми значениями: удалить лишние пробелы и ненужные символы, изменить регистр текста, подсчитать символы и слова, добавить один и тот же текст в начало или конец всех ячеек в диапазоне, преобразовать текст в числа, разделить его по отдельным ячейкам, заменить ошибочные символы с правильными.

Вот как вы можете быстро получить число из любой буквенно-цифровой строки:

  1. Перейдите на вкладку Ablebits Data > Текст и нажмите Извлечь (Extract) :

  1. Выделите все ячейки с нужным текстом.
  2. На панели инструмента установите переключатель «Извлечь числа (Extract numbers.
  3. В зависимости от того, хотите ли вы, чтобы результаты были формулами или значениями, выберите переключатель «Вставить как формулу (Insert as formula или оставьте его неактивным (по умолчанию).

Я советую активировать эту возможность, если вы хотите, чтобы извлеченные числа обновлялись автоматически, как только в исходные строки вносятся какие-либо изменения. 

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

  1. Нажмите кнопку «Вставить результаты (Insert results. Вот и всё!

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

В этом примере мы решили вставить результаты как формулы , и надстройка сделала именно то, что было запрошено:

=ЕСЛИ(МИН(НАЙТИ({0;1;2;3;4;5;6;7;8;9},A2&»_0123456789″))>ДЛСТР(A2), «»,СУММПРОИЗВ(ПСТР(0&A2,НАИБОЛЬШИЙ(ИНДЕКС(ЕЧИСЛО(—ПСТР(A2,СТРОКА(ДВССЫЛ(«$1:$»&ДЛСТР(A2))),1))*СТРОКА(ДВССЫЛ(«$1:$»&ДЛСТР(A2))),0),СТРОКА(ДВССЫЛ(«$1:$»&ДЛСТР(A2))))+1,1)*10^СТРОКА(ДВССЫЛ(«$1:$»&ДЛСТР(A2)))/10))

Сложновато самому написать такую формулу, не правда ли?

Если отсутствует флажок «Вставить как формулу», вы увидите число в строке формул. 

Любопытно попробовать? Просто скачайте пробную версию Ultimate Suite и убедитесь сами :)

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

Вот как вы можете преобразовать текст в число Excel с помощью формул и встроенных функций. Более сложные случаи, когда в ячейке находятся одновременно и буквы, и цифры, мы рассмотрим в отдельной статье. Я благодарю вас за чтение и надеюсь не раз еще увидеть вас в нашем блоге!

Также рекомендуем:

Как быстро посчитать количество слов в Excel В статье объясняется, как подсчитывать слова в Excel с помощью функции ДЛСТР в сочетании с другими функциями Excel, а также приводятся формулы для подсчета общего количества или конкретных слов в…
Как быстро извлечь число из текста в Excel В этом кратком руководстве показано, как можно быстро извлекать число из различных текстовых выражений в Excel с помощью формул или специального инструмента «Извлечь». Проблема выделения числа из текста возникает достаточно…
Как умножить число на процент и прибавить проценты Ранее мы уже научились считать проценты в Excel. Рассмотрим несколько случаев, когда известная нам величина процента помогает рассчитать различные числовые значения. Чему равен процент от числаКак умножить число на процентКак…
Как считать проценты в Excel — примеры формул В этом руководстве вы познакомитесь с быстрым способом расчета процентов в Excel, найдете базовую формулу процента и еще несколько формул для расчета процентного изменения, процента от общей суммы и т.д.…
Функция ПРАВСИМВ в Excel — примеры и советы. В последних нескольких статьях мы обсуждали различные текстовые функции. Сегодня наше внимание сосредоточено на ПРАВСИМВ (RIGHT в английской версии), которая предназначена для возврата указанного количества символов из крайней правой части…
Функция ЛЕВСИМВ в Excel. Примеры использования и советы. В руководстве показано, как использовать функцию ЛЕВСИМВ (LEFT) в Excel, чтобы получить подстроку из начала текстовой строки, извлечь текст перед определенным символом, заставить формулу возвращать число и многое другое. Среди…
5 примеров с функцией ДЛСТР в Excel. Вы ищете формулу Excel для подсчета символов в ячейке? Если да, то вы, безусловно, попали на нужную страницу. В этом коротком руководстве вы узнаете, как использовать функцию ДЛСТР (LEN в английской версии)…

Преобразование чисел-как-текст в нормальные числа

Если для каких-либо ячеек на листе был установлен текстовый формат (это мог сделать пользователь или программа при выгрузке данных в Excel), то введенные потом в эти ячейки числа Excel начинает считать текстом. Иногда такие ячейки помечаются зеленым индикатором, который вы, скорее всего, видели:

Число как текст в Excel

Причем иногда такой индикатор не появляется (что гораздо хуже).

В общем и целом, появление в ваших данных чисел-как-текст обычно приводит к большому количеству весьма печальных последствий:

Особенно забавно, что естественное желание просто изменить формат ячейки на числовой — не помогает. Т.е. вы, буквально, выделяете ячейки, щелкаете по ним правой кнопкой мыши, выбираете Формат ячеек (Format Cells), меняете формат на Числовой (Number), жмете ОК — и ничего не происходит! Совсем!

Возможно, «это не баг, а фича», конечно, но нам от этого не легче. Так что давайте-к рассмотрим несколько способов исправить ситуацию — один из них вам обязательно поможет.

Способ 1. Зеленый уголок-индикатор

Если на ячейке с числом с текстовом формате вы видите зеленый уголок-индикатор, то считайте, что вам повезло. Можно просто выделить все ячейки с данными и нажать на всплывающий желтый значок с восклицательным знаком, а затем выбрать команду Преобразовать в число (Convert to number):

Преобразование в число

Все числа в выделенном диапазоне будут преобразованы в полноценные.

Если зеленых уголков нет совсем, то проверьте — не выключены ли они в настройках вашего Excel (Файл — Параметры — Формулы — Числа, отформатированные как текст или с предшествующим апострофом).

Способ 2. Повторный ввод

Если ячеек немного, то можно поменять их формат на числовой, а затем повторно ввести данные, чтобы изменение формата вступило-таки в силу. Проще всего это сделать, встав на ячейку и нажав последовательно клавиши F2 (вход в режим редактирования, в ячейке начинает мигаеть курсор) и затем Enter. Также вместо F2 можно просто делать двойной щелчок левой кнопкой мыши по ячейке.

Само-собой, что если ячеек много, то такой способ, конечно, не подойдет.

Способ 3. Формула

Можно быстро преобразовать псевдочисла в нормальные, если сделать рядом с данными дополнительный столбец с элементарной формулой:

Преобразование текста в число формулой

Двойной минус, в данном случае, означает, на самом деле, умножение на -1 два раза. Минус на минус даст плюс и значение в ячейке это не изменит, но сам факт выполнения математической операции переключает формат данных на нужный нам числовой.

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

Способ 4. Специальная вставка

Этот способ использовали еще в старых версиях Excel, когда современные эффективные менеджеры под стол ходили  зеленого уголка-индикатора еще не было в принципе (он появился только с 2003 года). Алгоритм такой:

  • в любую пустую ячейку введите 1
  • скопируйте ее
  • выделите ячейки с числами в текстовом формате и поменяйте у них формат на числовой (ничего не произойдет)
  • щелкните по ячейкам с псевдочислами правой кнопкой мыши и выберите команду Специальная вставка (Paste Special) или используйте сочетание клавиш Ctrl+Alt+V
  • в открывшемся окне выберите вариант Значения (Values) и Умножить (Multiply)

Преобразование текста в число специальной вставкой

По-сути, мы выполняем то же самое, что и в прошлом способе — умножение содержимого ячеек на единицу — но не формулами, а напрямую из буфера.

Способ 5. Текст по столбцам

Если псеводчисла, которые надо преобразовать, вдобавок еще и записаны с неправильными разделителями целой и дробной части или тысяч, то можно использовать другой подход. Выделите исходный диапазон с данными и нажмите кнопку Текст по столбцам (Text to columns) на вкладке Данные (Data). На самом деле этот инструмент предназначен для деления слипшегося текста по столбцам, но, в данном случае, мы используем его с другой целью.

Пропустите первых два шага нажатием на кнопку Далее (Next), а на третьем воспользуйтесь кнопкой Дополнительно (Advanced). Откроется диалоговое окно, где можно задать имеющиеся сейчас в нашем тексте символы-разделители:

Преобразование текста в число через инструмент Текст по столбцам

После нажатия на Готово Excel преобразует наш текст в нормальные числа.

Способ 6. Макрос

Если подобные преобразования вам приходится делать часто, то имеет смысл автоматизировать этот процесс при помощи несложного макроса. Нажмите сочетание клавиш Alt+F11 или откройте вкладку Разработчик (Developer) и нажмите кнопку Visual Basic. В появившемся окне редактора добавьте новый модуль через меню Insert — Module и скопируйте туда следующий код:

Sub Convert_Text_to_Numbers()
    Selection.NumberFormat = "General"
    Selection.Value = Selection.Value
End Sub

Теперь после выделения диапазона всегда можно открыть вкладку Разрабочик — Макросы (Developer — Macros), выбрать наш макрос в списке, нажать кнопку Выполнить (Run) — и моментально преобразовать псевдочисла в полноценные.

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

P.S.

С датами бывает та же история. Некоторые даты тоже могут распознаваться Excel’ем как текст, поэтому не будет работать группировка и сортировка. Решения — те же самые, что и для чисел, только формат вместо числового нужно заменить на дату-время.

Ссылки по теме

  • Деление слипшегося текста по столбцам
  • Вычисления без формул специальной вставкой
  • Преобразование текста в числа с помощью надстройки PLEX

Понравилась статья? Поделить с друзьями:
  • Excel for windows что это
  • Excel for windows 8 скачать торрент
  • Excel for windows 7 64 bit
  • Excel for win 10
  • Excel for web page