Using cells in excel

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 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?

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.

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

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 позволяют вам получить доступ к диапазону ячеек этих типов

Lesson 5: Cell Basics

/en/excel/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.

Watch the video below to learn more about the basics of working with cells.

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. In other words, it’s where a row and column meet.

Columns are identified by letters (A, B, C), while rows are identified by numbers (1, 2, 3). Each cell has its own name—or cell address—based on its column and row. In the example below, the selected cell intersects column C and row 5, so the cell address is C5.

cell C5

Note that the cell address also appears in the Name box in the top-left corner, and that a cell’s column and row headings are highlighted when the cell is selected.

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. Take a look at the different cell ranges below:

  • Cell range A1:A8

    cell range A1:A8

  • Cell range A1:F1

    cell range A1:F1

  • Cell range A1:F8

    cell range A1:F8

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. In our example, we’ll select cell D9.
  2. A 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.

    selecting cell D9

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 and drag the mouse until all of the adjoining cells you want to select are highlighted. In our example, we’ll select the cell range B5:C18.
  2. Release the mouse to select the desired cell range. The cells will remain selected until you click another cell in the worksheet.

    selecting cell range B5:C18

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.

    content entered into cells

  • 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 text or background color.

    the same cell content with different 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 the cell range B2:B8 and displays the total in cell B9.

    a cell containing a formula

To insert content:

  1. Click a cell to select it. In our example, we’ll select cell F9.

    selecting cell F9

  2. Type something 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.

    typing in a cell

To delete (or clear) cell content:

  1. Select the cell(s) with content you want to delete. In our example, we’ll select the cell range A10:H10.

    selecting cells A10:H10

  2. Select the Clear command on the Home tab, then click Clear Contents.

    selecting the Clear Contents command

  3. The cell contents will be deleted.

    the cleared cell range

You can also use the Delete key on your keyboard to delete content from multiple cells at once. The Backspace key will only delete content from 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 to fill in the gaps and replace the deleted cells.

  1. Select the cell(s) you want to delete. In our example, we’ll select A10:H10.

    selecting cell range A10:H10

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

    clicking the Delete command on the Home tab

  3. The cells below will shift up and fill in the gaps.

    the shifted cells after deleting

To copy and paste cell content:

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

  1. Select the cell(s) you want to copy. In our example, we’ll select F9.

    selecting cell F9

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

    clicking the Copy command on the Home tab

  3. Select the cell(s) where you want to paste the content. In our example, we’ll select F12:F17. The copied cell(s) will have a dashed box around them.

    selecting a destination for the copied cell(s)

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

    selecting the Paste command

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

    the pasted content

To access additional paste options:

You can also access additional paste options, which are especially convenient when working with cells that contain formulas or formatting. Just click the drop-down arrow on the Paste command to see these options.

clicking the Paste command drop-down menu

Instead of choosing 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.

right-clicking to access cut, copy, and paste options

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. In our example, we’ll select G5:G6.
  2. Right-click the mouse and select the Cut command. You can also use the command on the Home tab, or press Ctrl+X on your keyboard.

    selecting the Cut command from the right-click menu

  3. Select the cells where you want to paste the content. In our example, we’ll select F10:F11. The cut cells will now have a dashed box around them.
  4. Right-click the mouse and select the Paste command. You can also use the command on the Home tab, or press Ctrl+V on your keyboard.

    pasting the cut cells

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

    the pasted cells

To drag and drop cells:

Instead of cutting, copying, and pasting, you can drag and drop cells to move their contents.

  1. Select the cell(s) you want to move. In our example, we’ll select H4:H12.
  2. Hover the mouse over the border of the selected cell(s) until the mouse changes to a pointer with four arrows.

    hovering over the border of a selected cell range

  3. Click and drag the cells to the desired location. In our example, we’ll move them to G4:G12.

    dragging the cells to a new location

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

    the dropped cells in their new location

To use the fill handle:

If you’re copying cell content to adjacent cells in the same row or column, the fill handle is a good alternative to the copy and paste commands.

  1. Select the cell(s) containing the content you want to use, then hover the mouse over the lower-right corner of the cell so the fill handle appears.

    the fill handle

  2. Click and drag the fill handle until all of the cells you want to fill are selected. In our example, we’ll select G13:G17.

    dragging the fill handle down

  3. Release the mouse to fill the selected cells.

    the 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 most cases, you will need to select multiple cells before using the fill handle to help Excel determine the series order. Let’s take a look at an example:

  1. Select the cell range that contains the series you want to continue. In our example, we’ll select E4:G4.
  2. Click and drag the fill handle to continue the series.

    continuing a series with the fill handle

  3. Release the mouse. If Excel understood the series, it will be continued in the selected cells. In our example, Excel added Part 4, Part 5, and Part 6 to H4:J4.

    the finished 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.

Challenge!

  1. Open our practice workbook.
  2. Select cell D6 and type hlee.
  3. Clear the contents in row 14.
  4. Delete column G.
  5. Using either cut and paste or drag and drop, move the contents of row 18 to row 14.
  6. Use the fill handle to put an X in cells F9:F17.
  7. When you’re finished, your workbook should look like this:

    Cell Basics Challenge

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

Very often, when working in Excel, you need to use data about addressing cells in a spreadsheet. For this was provided the function CELL. Consider its use on specific examples.



Function CELL value and properties in Excel

It should be noted that Excel uses several functions for addressing cells:

  • — ROW;
  • — COLUMN and others.

CELL function return information about the formatting, address, or contents of a cell. The function can return detailed information about the cell format, thereby eliminating the need to use VBA in some cases. The function is especially useful if you need to display the full path of the file in the cells.

How does the CELL function in Excel work?

Function in its work uses the syntax that consists of two arguments:

Function CELL.

=CELL(info_type,[reference])

  1. Info_type is a text value that specifies the type of cell information that is required. When you enter a function manually, a drop-down list is displayed where all possible values of the “information type” argument are shown:
  2. info_type.

  3. [Reference] is an optional argument. The cell for which you want to receive information. If this argument is omitted, the information specified in the information_type argument is returned for the last cell changed. If the link argument points to a range of cells, function returns information only for the upper-left value of the range.



Examples of using the CELL function in Excel

Example 1. Given the table of accounting work of employees of the organization of the form:

Example 1.

It is necessary with the help of the CELL function to calculate in which row and column the salary is in the amount of 235,000 dollars.

To do this, we introduce the following formula:

calculate in which row and column.

here:

  • — «row» and «column» — output parameter;
  • — C8 — address data with a salary.

As a result of the calculations, we obtain: row №8 and column № 3 (C).

How to know width of an Excel spreadsheet?

Example 2. It is necessary to calculate the width of the table in characters. Immediately it should be noted that in Excel, by default, the width of columns and cells is measured in the number of characters that they fit in their value are available for display in a cell without a line break.

Note. The height of lines and cells in Excel is by default measured in units of the basic font — in (pt) points. The larger the font, the higher the line for full display of characters in height.

Let’s enter into C14 the formula for calculating the sum of the width of each column of the table:

Example 2.

here:

  • — «width» is a function parameter;
  • — A1 — the width of a specific column.

How to get the value of the first value in the range

Example 3. In the condition of example 1, you need to display the contents of only the first (upper left) value from the range A5:C8.

We introduce the formula for calculating:

first value in range.

Download examples CELL function in Excel

Description of the formula is similar to the previous two examples.

totn Excel


In Microsoft Excel, a cell is a rectangular box that occurs at the intersection of a vertical column and a horizontal row in a worksheet. Vertical columns are numbered with alphabetic values such as A, B, C. Horizontal rows are numbered with numeric values such as 1, 2, 3.

Microsoft Excel

Each cell has its own set of coordinates or position in the worksheet such as A1, A2, or M16. In the example above, we are positioned on cell A1 which is the intersection of column A and row 1.

A cell can only store 1 piece of data at a time. You can store data in a cell such as a formula, text value, numeric value, or date value.

There are many things that you can do with cells in Excel such as changing the font format, number format, background, alignment, and conditional formatting. Here is a list of topics that explain how to use cells in Excel.

Font Format

  • Change the font in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Change the font color in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Change the font size in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Draw a line through a value in a cell (strikethrough) in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Create a subscript value in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Create a superscript value in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Use the Format Painter Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Number Format

  • Format display of text in a cell (ie: numbers, dates, etc) in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Fill/Background Format

  • Change the background color of a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Alignment Format

  • Align text to the top of the cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Center text across multiple cells in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Wrap text in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Merge cells in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Wrap text in merged cells in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Rotate text in a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Stop «wrap text» when pasting in Excel 2013 | 2011 | 2010 | 2007 | 2003

Border/Line Format

  • Draw a border around a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Protection

  • Protect a cell in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Hide formulas from appearing in the edit bar in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Conditional Formatting

  • Change the font color based on the value in the cell in Excel 2011 | 2010 | 2007 | 2003
  • Automatically alternate row colors (one shaded, one white) in Excel 2010 | 2007 | 2003
  • Automatically alternate row colors (two shaded, two white) in Excel 2010 | 2007 | 2003
  • Automatically alternate row colors (three shaded, three white) in Excel 2010 | 2007 | 2003
  • Automatically highlight highest and lowest values in a range of cells in Excel 2011 | 2010 | 2007 | 2003
  • Automatically highlight expired dates and dates that are 30 days from expiration in Excel 2010 | 2007 | 2003
  • Highlight 1st, 2nd, 3rd highest scores in Excel 2003
  • Change the font color in one cell based on the value in another cell in Excel 2003

Data Validation

  • Set up a cell to allow a maximum number of characters in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Set up a cell to allow a specific number of characters in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003
  • Set up a cell to allow positive numbers in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

Comments

  • Display comment indicator in Excel 2016 | 2013 | 2011 | 2010 | 2007 | 2003

AutoCorrect

  • Turn off AutoCorrect in Excel 2010 | 2007 | 2003

Miscellaneous

  • Copy and paste only nonblank cells (condensing paste range) in Excel 2013 | 2011 | 2010 | 2007 | 2003

Понравилась статья? Поделить с друзьями:
  • Using but as the first word in a sentence
  • Using bullets in word
  • Using brackets in excel
  • Using because as the first word in a sentence
  • Using arrays in vba excel