What is a cell in excel 2013

Last update on August 19 2022 21:50:55 (UTC/GMT +8 hours)

What is a cell ?

The worksheet of a workbook in Excel 2013 are made up of thousands of rectangles, are called cells. A cell is the intersection of a row and a column. Columns are identified by letters (A, B, C…), whereas rows are identified by numbers (1, 2, 3…). Here is the picture below to explain the rows and columns.

rows-columns

Each cell has its own name, or cell address, a combination of column and row. Here in the example below, the selected cell is the intersection or column B and row 4, so the cell address is B4. The cell address will also appear in the Name box. The another way to understand the selected row and column that, a cell’s column and row headings are highlighted when the cell is selected.

excel-cell

Multiple cells can also be selected at the same time. A group of cells is known as a cell range. A range of cells can be referred by using the cell addresses of the first and last cells and separated by a colon. Here in the picture below a cell range that included cells B1, B2, B3, B4, and B5 would be written as B1:B5.

cell-range.

Select a cell:

To input new data into a cell or edit cell content, you have to select the desired cell and click the mouse into your desired cell to select it.

A border will appear around the selected cell, and the column and row heading associated with the selected will be highlighted. The cell will remain selected until you click another cell in the worksheet.

excel-selected-cell

A cell can also be selected using the arrow keys on your keyboard.

Select a range of cells:

Sometimes we need to select a range of cells, then you need to press and hold the left mouse button, and drag the mouse until all of the adjoining cells you wish to select are highlighted and release the mouse.

The cells will remain selected until you click another cell in the worksheet.

cell-range1

Merge Cells:

Two or more cells can be merged in one depends on your requirement.

Merge multi Cells:

You can selecte multi cells, and then click Merge & Center in the alignment group of ribbon menu. Then choose from the option.

merge-cells

Here in the example above select B3 to D3 and click on Merge & Center. Three cells merge and make one cell. Here is the picture below.

or-merge-cells

Delete a cell:

There is an important different between deleting the content of a cell and deleting the cell itself. If you want to delete a cell or cells , the cells below and right of the selected cell(s) will shift up or left and replace the deleted cells.

Select the cell(s) which you want to delete.Then select the Delete command under cell group from the Home tab of the Ribbon, and click on Delete Cells. Here is the example below.

delete-cells
delete-cells

The picture below shows that the, cells below have been shifted up.

delete-cells

Here is another example

delete-cells
delete-cells

The picture below shows that the, cells right have been shifted left.

delete-cells

As a cell is associated with a row and column, so at the time of deletion of a cell or cells the four option may come. These are —

A cell may be deleted by replacing the below cell to up or by replacing the right cell to left.

The entire row or rows associated with the cell or cells may be deleted.

The entire column or columns associated with the cell or cells may be deleted.

Here is the picture below.

delete-cells

The above picture shows that, the C2 cell is selected and this cell is associated with column C and row 2. So the C2 cell can be deleted by C3 up or by shifting the D2 cell left or the entire C column can be deleted or entire 2 row can be deleted.

Cell content

Information entered into a spreadsheet will be stored in a cell. Each cell can contain several different kinds of content, including text, formatting, formulas, and functions.

Text type data

Cells can contain text, such as letters, numbers, and dates.

data

Insert content into cell

Click a cell to select it.

select-cell

Type content into the selected cell, then press Enter on your keyboard. The content will appear in the cell and the formula bar. You can also input and edit cell content in the formula bar.

content

Copy and paste cell content

Excel allows you to copy content that is already entered into the spreadsheet and paste that content into other cells.

Select the cell(s) that you want to copy. Then click the Copy command under the Home tab or press Ctrl+C on the keyboard.

cell-copy

The copied cells will now have a dashed box around them. Here is the picture below after click the copy command.

cell-copy

Now select the cell where you wish to paste the content and click on paste command. Here is the picture below.

cell-paste

Click the arrow of the Paste command under the Home tab, or press Ctrl+V on the keyboard.

cell-paste1

Select the cell or cells you want to cut then click the Cut command under the Home tab, or press Ctrl+X on the keyboard. The cells will now have a dashed box around them.

cut

Select the cells where you wish to paste the content.

Click the Paste command under Home tab, or press Ctrl+V on the keyboard. The content from the cells which you have selected for cut will move to the desired location. See the picture below.

cut1

To access more paste options:

To get various types of paste options, click the drop-down arrow on the Paste command. Here is the picture below.

cut1

Instead of choosing commands from the Ribbon, you can get the options quickly by right-clicking the mouse on the cell where you want to paste the copied or cut content.

Drag and drop cells:

Another way to move the content instead of cut command is to drag and drop cells to move the contents. Select the range A3:C4, and place the mouse pointer at any edge of selected area. A four-headed arrow will appear, then press and hold the mouse and drag your desired place and release the mouse, the selected content will move. Here is the picture below.

cut1

The picture below shows that the content of A3 to C4 have been moved into A6 to C7.

cut1

Delete cell content:

Select the cell with content which you want to delete.

delete-select

Press the Delete or Backspace key on the keyboard. The cell’s contents will be deleted.

delete-select1

Edit cell content

The content of a cell can be modified by the various way. You can do it by double clicking the cell where the content located, or select the cell and click on formula bar and edit the content or select the cell and press the F2 function key from the keyboard to edit the content of the cell.

delete-part-data

Previous: Backstage View — Excel 2013
Next:
Cell References in Excel

Lesson 7: Cell Basics

/en/excel2013/saving-and-sharing-workbooks/content/

Introduction

Whenever you work with Excel, you’ll enter information—or content—into cells. Cells are the basic building blocks of a worksheet. You’ll need to learn the basics of cells and cell content to calculate, analyze, and organize data in Excel.

Optional: Download our practice workbook.

Understanding cells

Every worksheet is made up of thousands of rectangles, which are called cells. A cell is the intersection of a row and a column. Columns are identified by letters (A, B, C), while rows are identified by numbers (1, 2, 3).

Screenshot of Excel 2013A cell

Each cell has its own name—or cell address—based on its column and row. In this example, the selected cell intersects column C and row 5, so the cell address is C5. The cell address will also appear in the Name box. Note that a cell’s column and row headings are highlighted when the cell is selected.

Screenshot of Excel 2013Cell C5

You can also select multiple cells at the same time. A group of cells is known as a cell range. Rather than a single cell address, you will refer to a cell range using the cell addresses of the first and last cells in the cell range, separated by a colon. For example, a cell range that included cells A1, A2, A3, A4, and A5 would be written as A1:A5.

In the images below, two different cell ranges are selected:

  • Cell range A1:A8

    Screenshot of Excel 2013Cell range A1:A8

  • Cell range A1:B8

    Screenshot of Excel 2013Cell range A1:B8

If the columns in your spreadsheet are labeled with numbers instead of letters, you’ll need to change the default reference style for Excel. Review our Extra on What are Reference Styles? to learn how.

To select a cell:

To input or edit cell content, you’ll first need to select the cell.

  1. Click a cell to select it.
  2. A border cell border will appear around the selected cell, and the column heading and row heading will be highlighted. The cell will remain selected until you click another cell in the worksheet.

    Screenshot of Excel 2013Selecting a single cell

You can also select cells using the arrow keys on your keyboard.

To select a cell range:

Sometimes you may want to select a larger group of cells, or a cell range.

  1. Click, hold, and drag the mouse until all of the adjoining cells you want to select are highlighted.
  2. Release the mouse to select the desired cell range. The cells will remain selected until you click another cell in the worksheet.

    Screenshot of Excel 2013Selecting a cell range

Cell content

Any information you enter into a spreadsheet will be stored in a cell. Each cell can contain different types of content, including text, formatting, formulas, and functions.

  • Text
    Cells can contain text, such as letters, numbers, and dates.

    Screenshot of Excel 2013Cell text

  • Formatting attributes
    Cells can contain formatting attributes that change the way letters, numbers, and dates are displayed. For example, percentages can appear as 0.15 or 15%. You can even change a cell’s background color.

    Screenshot of Excel 2013Cell formatting

  • Formulas and functions
    Cells can contain formulas and functions that calculate cell values. In our example, SUM(B2:B8) adds the value of each cell in cell range B2:B8 and displays the total in cell B9.

    Screenshot of Excel 2013Cell formulas

To insert content:

  1. Click a cell to select it.

    Screenshot of Excel 2013Selecting cell A1

  2. Type content into the selected cell, then press Enter on your keyboard. The content will appear in the cell and the formula bar. You can also input and edit cell content in the formula bar.

    Screenshot of Excel 2013Inserting cell content

To delete cell content:

  1. Select the cell with content you want to delete.

    Screenshot of Excel 2013Selecting a cell

  2. Press the Delete or Backspace key on your keyboard. The cell’s contents will be deleted.

    Screenshot of Excel 2013Deleting cell content

You can use the Delete key on your keyboard to delete content from multiple cells at once. The Backspace key will only delete one cell at a time.

To delete cells:

There is an important difference between deleting the content of a cell and deleting the cell itself. If you delete the entire cell, the cells below it will shift up and replace the deleted cells.

  1. Select the cell(s) you want to delete.

    Screenshot of Excel 2013Selecting a cell to delete

  2. Select the Delete command from the Home tab on the Ribbon.

    Screenshot of Excel 2013Clicking the Delete command

  3. The cells below will shift up.

    Screenshot of Excel 2013Cells shifted to replace the deleted cell

To copy and paste cell content:

Excel allows you to copy content that is already entered into your spreadsheet and paste that content to other cells, which can save you time and effort.

  1. Select the cell(s) you want to copy.

    Screenshot of Excel 2013Selecting a cell to copy

  2. Click the Copy command on the Home tab, or press Ctrl+C on your keyboard.

    Screenshot of Excel 2013Clicking the Copy command

  3. Select the cell(s) where you want to paste the content. The copied cells will now have a dashed box around them.

    Screenshot of Excel 2013Pasting cells

  4. Click the Paste command on the Home tab, or press Ctrl+V on your keyboard.

    Screenshot of Excel 2013Clicking the Paste command

  5. The content will be pasted into the selected cells.

    Screenshot of Excel 2013The pasted cell content

To cut and paste cell content:

Unlike copying and pasting, which duplicates cell content, cutting allows you to move content between cells.

  1. Select the cell(s) you want to cut.

    Screenshot of Excel 2013Selecting a cell range to cut

  2. Click the Cut command on the Home tab, or press Ctrl+X on your keyboard.

    Screenshot of Excel 2013Clicking the Cut command

  3. Select the cells where you want to paste the content. The cut cells will now have a dashed box around them.

    Screenshot of Excel 2013Pasting cells

  4. Click the Paste command on the Home tab, or press Ctrl+V on your keyboard.

    Screenshot of Excel 2013Clicking the Paste command

  5. The cut content will be removed from the original cells and pasted into the selected cells.

    Screenshot of Excel 2013The cut and pasted cells

To access more paste options:

You can also access additional paste options, which are especially convenient when working with cells that contain formulas or formatting.

  • To access more paste options, click the drop-down arrow on the Paste command.

Screenshot of Excel 2013Additional Paste options

Rather than choose commands from the Ribbon, you can access commands quickly by right-clicking. Simply select the cell(s) you want to format, then right-click the mouse. A drop-down menu will appear, where you’ll find several commands that are also located on the Ribbon.

Screenshot of Excel 2013Right-clicking to access formatting options

To drag and drop cells:

Rather than cutting, copying, and pasting, you can drag and drop cells to move their contents.

  1. Select the cell(s) you want to move.
  2. Hover the mouse over the border of the selected cell(s) until the cursor changes from a white cross Cursor to a black cross with four arrowsCursor.

    Screenshot of Excel 2013Hovering over the cell border

  3. Click, hold, and drag the cells to the desired location.

    Screenshot of Excel 2013Dragging the selected cells

  4. Release the mouse, and the cells will be dropped in the selected location.

    Screenshot of Excel 2013The dropped cells

To use the fill handle:

There may be times when you need to copy the content of one cell to several other cells in your worksheet. You could copy and paste the content into each cell, but this method would be time consuming. Instead, you can use the fill handle to quickly copy and paste content to adjacent cells in the same row or column.

  1. Select the cell(s) containing the content you want to use. The fill handle will appear as a small square in the bottom-right corner of the selected cell(s).

    Screenshot of Excel 2013Locating the fill handle

  2. Click, hold, and drag the fill handle until all of the cells you want to fill are selected.

    Screenshot of Excel 2013Dragging the fill handle

  3. Release the mouse to fill the selected cells.

    Screenshot of Excel 2013The filled cells

To continue a series with the fill handle:

The fill handle can also be used to continue a series. Whenever the content of a row or column follows a sequential order, like numbers (1, 2, 3) or days (Monday, Tuesday, Wednesday), the fill handle can guess what should come next in the series. In many cases, you may need to select multiple cells before using the fill handle to help Excel determine the series order. In our example below, the fill handle is used to extend a series of dates in a column.

Screenshot of Excel 2013Using the fill handle to extend a series

ExcelThe extended series

You can also double-click the fill handle instead of clicking and dragging. This can be useful with larger spreadsheets, where clicking and dragging may be awkward.

Watch the video below to see an example of double-clicking the fill handle.

To use Flash Fill:

A new feature in Excel 2013, Flash Fill can enter data automatically into your worksheet, saving you time and effort. Just like the fill handle, Flash Fill can guess what type of information you’re entering into your worksheet. In the example below, we’ll use Flash Fill to create a list of first names using a list of existing email addresses.

  1. Enter the desired information into your worksheet. A Flash Fill preview will appear below the selected cell whenever Flash Fill is available.

    Screenshot of Excel 2013Previewing Flash Fill data

  2. Press Enter. The Flash Fill data will be added to the worksheet.

    Screenshot of Excel 2013The entered Flash Fill data

To modify or undo Flash Fill, click the Flash Fill button next to recently added Flash Fill data.

Screenshot of Excel 2013Clicking the Flash Fill button

Find and Replace

When working with a lot of data in Excel, it can be difficult and time consuming to locate specific information. You can easily search your workbook using the Find feature, which also allows you to modify content using the Replace feature.

To find content:

In our example, we’ll use the Find command to locate a specific name in a long list of employees.

  1. From the Home tab, click the Find and Select command, then select Find… from the drop-down menu.

    Screenshot of Excel 2013Clicking the Find command

  2. The Find and Replace dialog box will appear. Enter the content you want to find. In our example, we’ll type the employee’s name.
  3. Click Find Next. If the content is found, the cell containing that content will be selected.

    Screenshot of Excel 2013Clicking Find Next

  4. Click Find Next to find further instances or Find All to see every instance of the search term.

    Screenshot of Excel 2013Clicking Find All

  5. When you are finished, click Close to exit the Find and Replace dialog box.

    Screenshot of Excel 2013Closing the Find and Replace dialog box

You can also access the Find command by pressing Ctrl+F on your keyboard.

Click Options to see advanced search criteria in the Find and Replace dialog box.

Screenshot of Excel 2013Clicking Options

To replace cell content:

At times, you may discover that you’ve repeatedly made a mistake throughout your workbook (such as misspelling someone’s name), or that you need to exchange a particular word or phrase for another. You can use Excel’s Find and Replace feature to make quick revisions. In our example, we’ll use Find and Replace to correct a list of email addresses.

  1. From the Home tab, click the Find and Select command, then select Replace… from the drop-down menu.

    Screenshot of Excel 2013Clicking the Replace command

  2. The Find and Replace dialog box will appear. Type the text you want to find in the Find what: field.
  3. Type the text you want to replace it with in the Replace with: field, then click Find Next.

    Screenshot of Excel 2013Clicking Find Next

  4. If the content is found, the cell containing that content will be selected.
  5. Review the text to make sure you want to replace it.
  6. If you want to replace it, select one of the replace options:
    • Replace will replace individual instances.
    • Replace All will replace every instance of the text throughout the workbook. In our example, we’ll choose this option to save time.

    Screenshot of Excel 2013Replacing the highlighted text

  7. A dialog box will appear, confirming the number of replacements made. Click OK to continue.

    Screenshot of Excel 2013Clicking OK

  8. The selected cell content will be replaced.

    Screenshot of Excel 2013The replaced content

  9. When you are finished, click Close to exit the Find and Replace dialog box.

    Screenshot of Excel 2013Closing the Find and Replace dialog box

Challenge!

  1. Open an existing Excel 2013 workbook. If you want, you can use our practice workbook.
  2. Select cell D3. Notice how the cell address appears in the Name box and its content appears in both the cell and the Formula bar.
  3. Select a cell, and try inserting text and numbers.
  4. Delete a cell, and note how the cells below shift up to fill in its place.
  5. Cut cells and paste them into a different location. If you are using the example, cut cells D4:D6 and paste them to E4:E6.
  6. Try dragging and dropping some cells to other parts of the worksheet.
  7. Use the fill handle to fill in data to adjoining cells both vertically and horizontally. If you are using the example, use the fill handle to continue the series of dates across row 3.
  8. Use the Find feature to locate content in your workbook. If you are using the example, type the name Lewis into the Find what: field.

/en/excel2013/modifying-columns-rows-and-cells/content/

A cell is an essential part of MS-Excel. It is an object of Excel worksheets. Whenever you open Excel, the Excel worksheet contains cells to store the information in them. You enter content and your data into these cells. Cells are the building blocks of the Excel worksheet. So, you should know every single point about it.

What is a cell in Excel

In the Excel worksheet, a cell is a rectangular-shaped box. It is a small unit of the Excel spreadsheet. There are around 17 billion cells in an Excel worksheet, which are united together in horizontal and vertical lines.

An Excel worksheet contains cells in rows and columns. Rows are labeled as numbers and columns as alphabets. It means the rows are identified by numbers and columns by alphabets.

What is a cell in Excel

Which data can enter into cell

Excel consists of a group of cells in a worksheet. You can enter data in any of these cells. Excel allows the user to enter any type of data in Excel cells, such as numeric, text, date, and time data. Whatever you enter in a cell, it appears inside the cell and as well as in the formula bar.

What is a cell in Excel

Double-tap on any of a cell to make it editable and write the data in it. In Excel, you can enter any type of data in Excel cells, such as number, string, text, date, time, etc. In addition, the users can also perform operations on it.

How to identify cell number?

In Excel, you can easily identify the cell number you are currently in. You can either find the cell number inside the Name box or also from row and column headers.

The highlighted row and column in the header is the cell number when a cell is selected. See the screenshot below:

What is a cell in Excel

Else see the cell number inside the Name box of the currently selected cell and get the cell number, e.g., D15.

Enter data into the cell

To enter the data/information into a cell, double-tap on any cell to make it editable and write the data in it. Let’s understand with an example.

Delete cell data

Select the cell along with data inside it and either press Backspace or Delete button to delete the content of the cell. It will delete one letter at a time means 1 tap backspace/delete will delete only one letter of that cell.

You can also delete cell data in one go. For this, select the cell data and then either press the Backspace or Delete button. The selected cell content will be deleted.

You can also use this Delete button to delete the content of multiple cells. For this, you have to select cells with data whose data you want to delete and press the Delete key on your keyboard. The data of the selected cells will be deleted.

Delete cell

There is a huge difference between deleting the cell data or deleting a cell itself. So, don’t be confused between them. To delete the cells, you have to perform a bit different steps, as we are discussing below:

Step 1: Select one or more cells, which you want to delete. E.g., A3, A4, and B3, B4.

What is a cell in Excel

Step 2: Right-click any of the selected cells and click on the Delete command present inside the list.

What is a cell in Excel

Step 3: Mark the relevant radio button and click on the OK button. We have chosen to Shift cells up option to shift the remaining cells data of the selected column to the upper row.

What is a cell in Excel

Step 4: The selected cells will be deleted and the remaining cells will shift up at the place of deleted cells.

What is a cell in Excel

Cell range

Cell range is one, which has a starting and ending point. When the multiple cells are selected in a sequence, it is called as cell range. Cell range shows from start cell to end cell. Selected cells must be in sequence without any gap in selection.

For example,

Cell range A1:A8

Cell A1 to A8 is selected in this range. It means that total 8 cells are selected.

Cell range A1:B8

Cell A1 to A8 and B1 to B8 are selected in this cell range. It means that total 16 cells are selected.

How to select multiple cells

Sometimes, there is a need to select a large range of cell data in an Excel sheet. You can easily select a larger group of cells or a cell range in two ways. Either with mouse or shift and arrow key.

1. Continues selection

Firstly, we will show you a contiguous selection of multiple cells using both methods.

  • Select cells with mouse

Click on a cell, hold the mouse left key and drag until you got select all needed cells.

  • Select cells with Shift and arrow key

There is one more way selecting multiple cells at one time. You can use the Shift key with arrow keys (choose direction) to select multiple cells.

Firstly, click on one cell in the Excel worksheet. Keep pressing the shift key and use the required arrow key with it according to selection to select the multiple cells.

2. Scattered selection

Excel also allows to select multiple cells from different rows and columns without following any contiguous selection range process as above. We can do it only using the Ctrl key.

  • Select scattered cells with the CTRL key

Excel provides a way to select two or more cells of different rows and different columns. You can use the CTRL key to hold the selection and then choose the cells to select.

Remember that only those cells will be selected which has some data. Blank cells cannot be selected even using the Ctrl key.

Cut, copy, and paste the cells data

Cut, copy, and paste are the most used operations of every tool. Excel allows its users to copy or cut the content from one place and paste it to another cell in Excel.

Excel also provides shortcut commands for these operations. CTRL + C for copy, CTRL + P for paste the copied content, and CTRL + X for cut is used in Excel. These shortcut keys are the same for almost every tool.

Copy and paste the cell data

Step 1: Select the cell whose data you want to copy and press the CTRL+C command to copy the data.

What is a cell in Excel

Step 2: Now, go to that where you want to paste the copied data and press the CTRL+P shortcut command to place the data there.

What is a cell in Excel

Step 3: Your data has been copied from one cell and pasted to another one.

Cut and paste the cell data

Step 1: Select the cell whose data you want to cut and press the CTRL+X command.

What is a cell in Excel

Step 2: Now, go to the cell where you want to paste the cut data and press the CTRL+P shortcut command to place the data there.

Step 3: Your data has been placed from one cell and pasted to another one.

What is a cell in Excel

How to increase the size of cell

In Excel, you can increase the size of cells in following ways:

  1. Increase the height of the row from row header
  2. Increase the width of the column from column header
  3. Merge the two or more cells to enhance the cell size
  4. Increase the font size to make the cell bigger

You can use any of these methods accordingly as needed.


Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel for iPad Excel for iPhone Excel for Android tablets Excel 2010 Excel 2007 Excel for Mac 2011 Excel for Android phones Excel Starter 2010 More…Less

The CELL function returns information about the formatting, location, or contents of a cell. For example, if you want to verify that a cell contains a numeric value instead of text before you perform a calculation on it, you can use the following formula:

=IF(CELL(«type»,A1)=»v»,A1*2,0)

This formula calculates A1*2 only if cell A1 contains a numeric value, and returns 0 if A1 contains text or is blank.

Note: Formulas that use CELL have language-specific argument values and will return errors if calculated using a different language version of Excel. For example, if you create a formula containing CELL while using the Czech version of Excel, that formula will return an error if the workbook is opened using the French version.  If it is important for others to open your workbook using different language versions of Excel, consider either using alternative functions or allowing others to save local copies in which they revise the CELL arguments to match their language.

Syntax

CELL(info_type, [reference])

The CELL function syntax has the following arguments:

Argument

Description

info_type   

Required

A text value that specifies what type of cell information you want to return. The following list shows the possible values of the Info_type argument and the corresponding results.

reference    

Optional

The cell that you want information about.

If omitted, the information specified in the info_type argument is returned for cell selected at the time of calculation. If the reference argument is a range of cells, the CELL function returns the information for active cell in the selected range.

Important: Although technically reference is optional, including it in your formula is encouraged, unless you understand the effect its absence has on your formula result and want that effect in place. Omitting the reference argument does not reliably produce information about a specific cell, for the following reasons:

  • In automatic calculation mode, when a cell is modified by a user the calculation may be triggered before or after the selection has progressed, depending on the platform you’re using for Excel.  For example, Excel for Windows currently triggers calculation before selection changes, but Excel for the web triggers it afterward.

  • When Co-Authoring with another user who makes an edit, this function will report your active cell rather than the editor’s.

  • Any recalculation, for instance pressing F9, will cause the function to return a new result even though no cell edit has occurred.

info_type values

The following list describes the text values that can be used for the info_type argument. These values must be entered in the CELL function with quotes (» «).

info_type

Returns

«address»

Reference of the first cell in reference, as text. 

«col»

Column number of the cell in reference.

«color»

The value 1 if the cell is formatted in color for negative values; otherwise returns 0 (zero).

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«contents»

Value of the upper-left cell in reference; not a formula.

«filename»

Filename (including full path) of the file that contains reference, as text. Returns empty text («») if the worksheet that contains reference has not yet been saved.

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«format»

Text value corresponding to the number format of the cell. The text values for the various formats are shown in the following table. Returns «-» at the end of the text value if the cell is formatted in color for negative values. Returns «()» at the end of the text value if the cell is formatted with parentheses for positive or all values.

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«parentheses»

The value 1 if the cell is formatted with parentheses for positive or all values; otherwise returns 0.

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«prefix»

Text value corresponding to the «label prefix» of the cell. Returns single quotation mark (‘) if the cell contains left-aligned text, double quotation mark («) if the cell contains right-aligned text, caret (^) if the cell contains centered text, backslash () if the cell contains fill-aligned text, and empty text («») if the cell contains anything else.

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«protect»

The value 0 if the cell is not locked; otherwise returns 1 if the cell is locked.

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

«row»

Row number of the cell in reference.

«type»

Text value corresponding to the type of data in the cell. Returns «b» for blank if the cell is empty, «l» for label if the cell contains a text constant, and «v» for value if the cell contains anything else.

«width»

Returns an array with 2 items.

The 1st item in the array is the column width of the cell, rounded off to an integer. Each unit of column width is equal to the width of one character in the default font size.

The 2nd item in the array is a Boolean value, the value is TRUE if the column width is the default or FALSE if the width has been explicitly set by the user. 

Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

CELL format codes

The following list describes the text values that the CELL function returns when the Info_type argument is «format» and the reference argument is a cell that is formatted with a built-in number format.

If the Excel format is

The CELL function returns

General

«G»

0

«F0»

#,##0

«,0»

0.00

«F2»

#,##0.00

«,2»

$#,##0_);($#,##0)

«C0»

$#,##0_);[Red]($#,##0)

«C0-«

$#,##0.00_);($#,##0.00)

«C2»

$#,##0.00_);[Red]($#,##0.00)

«C2-«

0%

«P0»

0.00%

«P2»

0.00E+00

«S2»

# ?/? or # ??/??

«G»

m/d/yy or m/d/yy h:mm or mm/dd/yy

«D4»

d-mmm-yy or dd-mmm-yy

«D1»

d-mmm or dd-mmm

«D2»

mmm-yy

«D3»

mm/dd

«D5»

h:mm AM/PM

«D7»

h:mm:ss AM/PM

«D6»

h:mm

«D9»

h:mm:ss

«D8»

Note: If the info_type argument in the CELL function is «format» and you later apply a different format to the referenced cell, you must recalculate the worksheet (press F9) to update the results of the CELL function.

Examples

CELL function examples

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

See Also

Change the format of a cell

Create or change a cell reference

ADDRESS function

Add, change, find or clear conditional formatting in a cell

Need more help?

На чтение 18 мин. Просмотров 75.2k.

VBA Range

сэр Артур Конан Дойл

Это большая ошибка — теоретизировать, прежде чем кто-то получит данные

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

Рассматриваемые темы включают свойство смещения, чтение
значений между ячейками, чтение значений в массивы и форматирование ячеек.

Содержание

  1. Краткое руководство по диапазонам и клеткам
  2. Введение
  3. Важное замечание
  4. Свойство Range
  5. Свойство Cells рабочего листа
  6. Использование Cells и Range вместе
  7. Свойство Offset диапазона
  8. Использование диапазона CurrentRegion
  9. Использование Rows и Columns в качестве Ranges
  10. Использование Range вместо Worksheet
  11. Чтение значений из одной ячейки в другую
  12. Использование метода Range.Resize
  13. Чтение Value в переменные
  14. Как копировать и вставлять ячейки
  15. Чтение диапазона ячеек в массив
  16. Пройти через все клетки в диапазоне
  17. Форматирование ячеек
  18. Основные моменты

Краткое руководство по диапазонам и клеткам

Функция Принимает Возвращает Пример Вид
Range адреса
ячеек
диапазон
ячеек
.Range(«A1:A4») $A$1:$A$4
Cells строка,
столбец
одна
ячейка
.Cells(1,5) $E$1
Offset строка,
столбец
диапазон .Range(«A1:A2»)
.Offset(1,2)
$C$2:$C$3
Rows строка (-и) одна или
несколько
строк
.Rows(4)
.Rows(«2:4»)
$4:$4
$2:$4
Columns столбец
(-цы)
один или
несколько
столбцов
.Columns(4)
.Columns(«B:D»)
$D:$D
$B:$D

Введение

Это третья статья, посвященная трем основным элементам VBA. Этими тремя элементами являются Workbooks, Worksheets и Ranges/Cells. Cells, безусловно, самая важная часть Excel. Почти все, что вы делаете в Excel, начинается и заканчивается ячейками.

Вы делаете три основных вещи с помощью ячеек:

  1. Читаете из ячейки.
  2. Пишите в ячейку.
  3. Изменяете формат ячейки.

В Excel есть несколько методов для доступа к ячейкам, таких как Range, Cells и Offset. Можно запутаться, так как эти функции делают похожие операции.

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

Давайте начнем с самого простого метода доступа к ячейкам — с помощью свойства Range рабочего листа.

Важное замечание

Я недавно обновил эту статью, сейчас использую Value2.

Вам может быть интересно, в чем разница между Value, Value2 и значением по умолчанию:

' Value2
Range("A1").Value2 = 56

' Value
Range("A1").Value = 56

' По умолчанию используется значение
Range("A1") = 56

Использование Value может усечь число, если ячейка отформатирована, как валюта. Если вы не используете какое-либо свойство, по умолчанию используется Value.

Лучше использовать Value2, поскольку он всегда будет возвращать фактическое значение ячейки.

Свойство Range

Рабочий лист имеет свойство Range, которое можно использовать для доступа к ячейкам в VBA. Свойство Range принимает тот же аргумент, что и большинство функций Excel Worksheet, например: «А1», «А3: С6» и т.д.

В следующем примере показано, как поместить значение в ячейку с помощью свойства Range.

Sub ZapisVYacheiku()

    ' Запишите число в ячейку A1 на листе 1 этой книги
    ThisWorkbook.Worksheets("Лист1").Range("A1").Value2 = 67

    ' Напишите текст в ячейку A2 на листе 1 этой рабочей книги
    ThisWorkbook.Worksheets("Лист1").Range("A2").Value2 = "Иван Петров"

    ' Запишите дату в ячейку A3 на листе 1 этой книги
    ThisWorkbook.Worksheets("Лист1").Range("A3").Value2 = #11/21/2019#

End Sub

Как видно из кода, Range является членом Worksheets, которая, в свою очередь, является членом Workbook. Иерархия такая же, как и в Excel, поэтому должно быть легко понять. Чтобы сделать что-то с Range, вы должны сначала указать рабочую книгу и рабочий лист, которому она принадлежит.

В оставшейся части этой статьи я буду использовать кодовое имя для ссылки на лист.

code name worksheet

Следующий код показывает приведенный выше пример с использованием кодового имени рабочего листа, т.е. Лист1 вместо ThisWorkbook.Worksheets («Лист1»).

Sub IspKodImya ()

    ' Запишите число в ячейку A1 на листе 1 этой книги    
     Sheet1.Range("A1").Value2 = 67

    ' Напишите текст в ячейку A2 на листе 1 этой рабочей книги
    Sheet1.Range("A2").Value2 = "Иван Петров"

    ' Запишите дату в ячейку A3 на листе 1 этой книги
    Sheet1.Range("A3").Value2 = #11/21/2019#

End Sub

Вы также можете писать в несколько ячеек, используя свойство
Range

Sub ZapisNeskol()

    ' Запишите число в диапазон ячеек
    Sheet1.Range("A1:A10").Value2 = 67

    ' Написать текст в несколько диапазонов ячеек
    Sheet1.Range("B2:B5,B7:B9").Value2 = "Иван Петров"

End Sub

Свойство Cells рабочего листа

У Объекта листа есть другое свойство, называемое Cells, которое очень похоже на Range . Есть два отличия:

  1. Cells возвращают диапазон только одной ячейки.
  2. Cells принимает строку и столбец в качестве аргументов.

В приведенном ниже примере показано, как записывать значения
в ячейки, используя свойства Range и Cells.

Sub IspCells()

    ' Написать в А1
    Sheet1.Range("A1").Value2 = 10
    Sheet1.Cells(1, 1).Value2  = 10

    ' Написать в А10
    Sheet1.Range("A10").Value2 = 10
    Sheet1.Cells(10, 1).Value2  = 10

    ' Написать в E1
    Sheet1.Range("E1").Value2 = 10
    Sheet1.Cells(1, 5).Value2  = 10

End Sub

Вам должно быть интересно, когда использовать Cells, а когда Range. Использование Range полезно для доступа к одним и тем же ячейкам при каждом запуске макроса.

Например, если вы использовали макрос для вычисления суммы и
каждый раз записывали ее в ячейку A10, тогда Range подойдет для этой задачи.

Использование свойства Cells полезно, если вы обращаетесь к
ячейке по номеру, который может отличаться. Проще объяснить это на примере.

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

Sub ZapisVPervuyuPustuyuYacheiku()

    Dim UserCol As Integer
    
    ' Получить номер столбца от пользователя
    UserCol = Application.InputBox("Пожалуйста, введите номер столбца...", Type:=1)
    
    ' Написать текст в выбранный пользователем столбец
    Sheet1.Cells(1, UserCol).Value2 = "Иван Петров"

End Sub

В приведенном выше примере мы используем номер для столбца,
а не букву.

Чтобы использовать Range здесь, потребуется преобразовать эти значения в ссылку на
буквенно-цифровую ячейку, например, «С1». Использование свойства Cells позволяет нам
предоставить строку и номер столбца для доступа к ячейке.

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

Использование Cells и Range вместе

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

Sub IspCellsSRange()

    With Sheet1
        ' Запишите 5 в диапазон A1: A10, используя свойство Cells
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5

        ' Диапазон B1: Z1 будет выделен жирным шрифтом
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True

    End With

End Sub

Как видите, вы предоставляете начальную и конечную ячейку
диапазона. Иногда бывает сложно увидеть, с каким диапазоном вы имеете дело,
когда значением являются все числа. Range имеет свойство Address, которое
отображает буквенно-цифровую ячейку для любого диапазона. Это может
пригодиться, когда вы впервые отлаживаете или пишете код.

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

Sub PokazatAdresDiapazona()

    ' Примечание. Использование подчеркивания позволяет разделить строки кода.
    With Sheet1

        ' Запишите 5 в диапазон A1: A10, используя свойство Cells
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
        Debug.Print "Первый адрес: " _
            + .Range(.Cells(1, 1), .Cells(10, 1)).Address

        ' Диапазон B1: Z1 будет выделен жирным шрифтом
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
        Debug.Print "Второй адрес : " _
            + .Range(.Cells(1, 2), .Cells(1, 26)).Address

    End With

End Sub

В примере я использовал Debug.Print для печати в Immediate Window. Для просмотра этого окна выберите «View» -> «в Immediate Window» (Ctrl +  G).

ImmediateWindow

ImmediateSampeText

Свойство Offset диапазона

У диапазона есть свойство, которое называется Offset. Термин «Offset» относится к отсчету от исходной позиции. Он часто используется в определенных областях программирования. С помощью свойства «Offset» вы можете получить диапазон ячеек того же размера и на определенном расстоянии от текущего диапазона. Это полезно, потому что иногда вы можете выбрать диапазон на основе определенного условия. Например, на скриншоте ниже есть столбец для каждого дня недели. Учитывая номер дня (т.е. понедельник = 1, вторник = 2 и т.д.). Нам нужно записать значение в правильный столбец.

VBA Offset

Сначала мы попытаемся сделать это без использования Offset.

' Это Sub тесты с разными значениями
Sub TestSelect()

    ' Понедельник
    SetValueSelect 1, 111.21
    ' Среда
    SetValueSelect 3, 456.99
    ' Пятница
    SetValueSelect 5, 432.25
    ' Воскресение
    SetValueSelect 7, 710.17

End Sub

' Записывает значение в столбец на основе дня
Public Sub SetValueSelect(lDay As Long, lValue As Currency)

    Select Case lDay
        Case 1: Sheet1.Range("H3").Value2 = lValue
        Case 2: Sheet1.Range("I3").Value2 = lValue
        Case 3: Sheet1.Range("J3").Value2 = lValue
        Case 4: Sheet1.Range("K3").Value2 = lValue
        Case 5: Sheet1.Range("L3").Value2 = lValue
        Case 6: Sheet1.Range("M3").Value2 = lValue
        Case 7: Sheet1.Range("N3").Value2 = lValue
    End Select

End Sub

Как видно из примера, нам нужно добавить строку для каждого возможного варианта. Это не идеальная ситуация. Использование свойства Offset обеспечивает более чистое решение.

' Это Sub тесты с разными значениями
Sub TestOffset()

    DayOffSet 1, 111.01
    DayOffSet 3, 456.99
    DayOffSet 5, 432.25
    DayOffSet 7, 710.17

End Sub

Public Sub DayOffSet(lDay As Long, lValue As Currency)

    ' Мы используем значение дня с Offset, чтобы указать правильный столбец
    Sheet1.Range("G3").Offset(, lDay).Value2 = lValue

End Sub

Как видите, это решение намного лучше. Если количество дней увеличилось, нам больше не нужно добавлять код. Чтобы Offset был полезен, должна быть какая-то связь между позициями ячеек. Если столбцы Day в приведенном выше примере были случайными, мы не могли бы использовать Offset. Мы должны были бы использовать первое решение.

Следует иметь в виду, что Offset сохраняет размер диапазона. Итак .Range («A1:A3»).Offset (1,1) возвращает диапазон B2:B4. Ниже приведены еще несколько примеров использования Offset.

Sub IspOffset()

    ' Запись в В2 - без Offset
    Sheet1.Range("B2").Offset().Value2 = "Ячейка B2"

    ' Написать в C2 - 1 столбец справа
    Sheet1.Range("B2").Offset(, 1).Value2 = "Ячейка C2"

    ' Написать в B3 - 1 строка вниз
    Sheet1.Range("B2").Offset(1).Value2 = "Ячейка B3"

    ' Запись в C3 - 1 столбец справа и 1 строка вниз
    Sheet1.Range("B2").Offset(1, 1).Value2 = "Ячейка C3"

    ' Написать в A1 - 1 столбец слева и 1 строка вверх
    Sheet1.Range("B2").Offset(-1, -1).Value2 = "Ячейка A1"

    ' Запись в диапазон E3: G13 - 1 столбец справа и 1 строка вниз
    Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Ячейки E3:G13"

End Sub

Использование диапазона CurrentRegion

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

VBA CurrentRegion

Строка или столбец пустых ячеек означает конец CurrentRegion.

Вы можете вручную проверить
CurrentRegion в Excel, выбрав диапазон и нажав Ctrl + Shift + *.

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

Например:

Range («B3»). CurrentRegion вернет диапазон B3:D14

Range («D14»). CurrentRegion вернет диапазон B3:D14

Range («C8:C9»). CurrentRegion вернет диапазон B3:D14 и так далее

Как пользоваться

Мы получаем CurrentRegion следующим образом

' CurrentRegion вернет B3:D14 из приведенного выше примера
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

Только чтение строк данных

Прочитать диапазон из второй строки, т.е. пропустить строку заголовка.

' CurrentRegion вернет B3:D14 из приведенного выше примера
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Начало в строке 2 - строка после заголовка
Dim i As Long
For i = 2 To rg.Rows.Count
    ' текущая строка, столбец 1 диапазона
    Debug.Print rg.Cells(i, 1).Value2
Next i

Удалить заголовок

Удалить строку заголовка (т.е. первую строку) из диапазона. Например, если диапазон — A1:D4, это возвратит A2:D4

' CurrentRegion вернет B3:D14 из приведенного выше примера
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Удалить заголовок
Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)

' Начните со строки 1, так как нет строки заголовка
Dim i As Long
For i = 1 To rg.Rows.Count
    ' текущая строка, столбец 1 диапазона
    Debug.Print rg.Cells(i, 1).Value2
Next i

Использование Rows и Columns в качестве Ranges

Если вы хотите что-то сделать со всей строкой или столбцом,
вы можете использовать свойство «Rows и
Columns
» на рабочем листе. Они оба принимают один параметр — номер строки
или столбца, к которому вы хотите получить доступ.

Sub IspRowIColumns()

    ' Установите размер шрифта столбца B на 9
    Sheet1.Columns(2).Font.Size = 9

    ' Установите ширину столбцов от D до F
    Sheet1.Columns("D:F").ColumnWidth = 4

    ' Установите размер шрифта строки 5 до 18
    Sheet1.Rows(5).Font.Size = 18

End Sub

Использование Range вместо Worksheet

Вы также можете использовать Cella, Rows и Columns, как часть Range, а не как часть Worksheet. У вас может быть особая необходимость в этом, но в противном случае я бы избегал практики. Это делает код более сложным. Простой код — твой друг. Это уменьшает вероятность ошибок.

Код ниже выделит второй столбец диапазона полужирным. Поскольку диапазон имеет только две строки, весь столбец считается B1:B2

Sub IspColumnsVRange()

    ' Это выделит B1 и B2 жирным шрифтом.
    Sheet1.Range("A1:C2").Columns(2).Font.Bold = True

End Sub

Чтение значений из одной ячейки в другую

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

В следующем примере показано, как это сделать:

Sub ChitatZnacheniya()

    ' Поместите значение из B1 в A1
    Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2

    ' Поместите значение из B3 в лист2 в ячейку A1
    Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2

    ' Поместите значение от B1 в ячейки A1 до A5
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2

    ' Вам необходимо использовать свойство «Value», чтобы прочитать несколько ячеек
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2

End Sub

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

Sub KopirovatZnacheniya()

    ' Сохранить диапазон копирования в переменной
    Dim rgCopy As Range
    Set rgCopy = Sheet1.Range("B1:B5")

    ' Используйте это для копирования из более чем одной ячейки
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5")

    ' Вы можете вставить в несколько мест назначения
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")

End Sub

Функция Copy копирует все, включая формат ячеек. Это тот же результат, что и ручное копирование и вставка выделения. Подробнее об этом вы можете узнать в разделе «Копирование и вставка ячеек»

Использование метода Range.Resize

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

Использование функции Resize позволяет изменить размер
диапазона до заданного количества строк и столбцов.

Например:

Sub ResizePrimeri()
 
    ' Печатает А1
    Debug.Print Sheet1.Range("A1").Address

    ' Печатает A1:A2
    Debug.Print Sheet1.Range("A1").Resize(2, 1).Address

    ' Печатает A1:A5
    Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
    
    ' Печатает A1:D1
    Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
    
    ' Печатает A1:C3
    Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
    
End Sub

Когда мы хотим изменить наш целевой диапазон, мы можем
просто использовать исходный размер диапазона.

Другими словами, мы используем количество строк и столбцов
исходного диапазона в качестве параметров для изменения размера:

Sub Resize()

    Dim rgSrc As Range, rgDest As Range
    
    ' Получить все данные в текущей области
    Set rgSrc = Sheet1.Range("A1").CurrentRegion

      ' Получить диапазон назначения
    Set rgDest = Sheet2.Range("A1")
    Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
    
    rgDest.Value2 = rgSrc.Value2

End Sub

Мы можем сделать изменение размера в одну строку, если нужно:

Sub Resize2()

    Dim rgSrc As Range
    
    ' Получить все данные в ткущей области
    Set rgSrc = Sheet1.Range("A1").CurrentRegion
    
    With rgSrc
        Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count) = .Value2
    End With
    
End Sub

Чтение Value в переменные

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

Sub IspVar()

    ' Создайте
    Dim val As Integer

    ' Читать число из ячейки
    val = Sheet1.Range("A1").Value2

    ' Добавить 1 к значению
    val = val + 1

    ' Запишите новое значение в ячейку
    Sheet1.Range("A2").Value2 = val

End Sub

Для чтения текста в переменную вы используете переменную
типа String.

Sub IspVarText()

    ' Объявите переменную типа string
    Dim sText As String

    ' Считать значение из ячейки
    sText = Sheet1.Range("A1").Value2

    ' Записать значение в ячейку
    Sheet1.Range("A2").Value2 = sText

End Sub

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

Sub VarNeskol()

    ' Считать значение из ячейки
    Sheet1.Range("A1:B10").Value2 = 66

End Sub

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

Как копировать и вставлять ячейки

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

Вы можете просто скопировать ряд ячеек, как здесь:

Range("A1:B4").Copy Destination:=Range("C5")

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

Работает так:

Range("A1:B4").Copy
Range("F3").PasteSpecial Paste:=xlPasteValues
Range("F3").PasteSpecial Paste:=xlPasteFormats
Range("F3").PasteSpecial Paste:=xlPasteFormulas

В следующей таблице приведен полный список всех типов вставок.

Виды вставок
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats

Чтение диапазона ячеек в массив

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

Range("A3:Z3").Value2 = Range("A1:Z1").Value2

Значение диапазона в этом примере считается вариантом массива. Это означает, что вы можете легко читать из диапазона ячеек в массив. Вы также можете писать из массива в диапазон ячеек. Если вы не знакомы с массивами, вы можете проверить их в этой статье.

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

Sub ChitatMassiv()

    ' Создать динамический массив
    Dim StudentMarks() As Variant

    ' Считать 26 значений в массив из первой строки
    StudentMarks = Range("A1:Z1").Value2

    ' Сделайте что-нибудь с массивом здесь

    ' Запишите 26 значений в третью строку
    Range("A3:Z3").Value2 = StudentMarks

End Sub

Имейте в виду, что массив, созданный для чтения, является
двумерным массивом. Это связано с тем, что электронная таблица хранит значения
в двух измерениях, то есть в строках и столбцах.

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

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

Вы можете сделать это, используя цикл For Each, показанный в следующем коде.

Sub PeremeschatsyaPoYacheikam()

    ' Пройдите через каждую ячейку в диапазоне
    Dim rg As Range
    For Each rg In Sheet1.Range("A1:A10,A20")
        ' Распечатать адрес ячеек, которые являются отрицательными
        If rg.Value < 0 Then
            Debug.Print rg.Address + " Отрицательно."
        End If
    Next

End Sub

Вы также можете проходить последовательные ячейки, используя
свойство Cells и стандартный цикл For.

Стандартный цикл более гибок в отношении используемого вами
порядка, но он медленнее, чем цикл For Each.

Sub PerehodPoYacheikam()
 
    ' Пройдите клетки от А1 до А10
    Dim i As Long
    For i = 1 To 10
        ' Распечатать адрес ячеек, которые являются отрицательными
        If Range("A" & i).Value < 0 Then
            Debug.Print Range("A" & i).Address + " Отрицательно."
        End If
    Next
 
    ' Пройдите в обратном порядке, то есть от A10 до A1
    For i = 10 To 1 Step -1
        ' Распечатать адрес ячеек, которые являются отрицательными
        If Range("A" & i) < 0 Then
            Debug.Print Range("A" & i).Address + " Отрицательно."
        End If
    Next
 
End Sub

Форматирование ячеек

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

Sub FormatirovanieYacheek()

    With Sheet1

        ' Форматировать шрифт
        .Range("A1").Font.Bold = True
        .Range("A1").Font.Underline = True
        .Range("A1").Font.Color = rgbNavy

        ' Установите числовой формат до 2 десятичных знаков
        .Range("B2").NumberFormat = "0.00"
        ' Установите числовой формат даты
        .Range("C2").NumberFormat = "dd/mm/yyyy"
        ' Установите формат чисел на общий
        .Range("C3").NumberFormat = "Общий"
        ' Установить числовой формат текста
        .Range("C4").NumberFormat = "Текст"

        ' Установите цвет заливки ячейки
        .Range("B3").Interior.Color = rgbSandyBrown

        ' Форматировать границы
        .Range("B4").Borders.LineStyle = xlDash
        .Range("B4").Borders.Color = rgbBlueViolet

    End With

End Sub

Основные моменты

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

  1. Range возвращает диапазон ячеек
  2. Cells возвращают только одну клетку
  3. Вы можете читать из одной ячейки в другую
  4. Вы можете читать из диапазона ячеек в другой диапазон ячеек.
  5. Вы можете читать значения из ячеек в переменные и наоборот.
  6. Вы можете читать значения из диапазонов в массивы и наоборот
  7. Вы можете использовать цикл For Each или For, чтобы проходить через каждую ячейку в диапазоне.
  8. Свойства Rows и Columns позволяют вам получить доступ к диапазону ячеек этих типов

Понравилась статья? Поделить с друзьями:
  • What is a cell for excel
  • What is a cell address in ms excel
  • What is a contraction word in a sentence
  • What is a context free word
  • What is a content word example