Excel vba диапазон весь столбец

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

Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

Примеры диапазонов:

  • Одна ячейка – Range("A1").
  • Девять ячеек – Range("A1:С3").
  • Весь рабочий лист в Excel 2016 – Range("1:1048576").

Для справки: выражение Range("1:1048576") описывает диапазон с 1 по 1048576 строку, где число 1048576 – это номер последней строки на рабочем листе Excel 2016.

В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

Примеры обращения к одной ячейке:

  • Cells(1000), где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
  • Cells(50, 20), где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
  • Range("A1:C3").Cells(6), где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

Для справки: порядковый номер ячейки в диапазоне считается построчно слева направо с перемещением к следующей строке сверху вниз.

Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

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

Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range("A1:C3").Cells(6).

Свойства ячейки (объекта Range)

Свойство Описание
Address Возвращает адрес ячейки (диапазона).
Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range("A1:A20").
EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range("A2:H2").
Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
Name Возвращает или задает имя ячейки (диапазона).
NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range("A1").NumberFormat = "@". Общий формат: Range("A1").NumberFormat = "General".
Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.

Простые примеры для начинающих

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

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

Sub Primer1()

MsgBox «Зальем ячейку A1 зеленым цветом и запишем в ячейку B1 текст: «Ячейка A1 зеленая!»»

Range(«A1»).Interior.Color = vbGreen

Range(«B1»).Value = «Ячейка A1 зеленая!»

MsgBox «Сделаем высоту строки, в которой находится ячейка A2, в 2 раза больше высоты ячейки A1, « _

& «а в ячейку B1 вставим текст: «Наша строка стала в 2 раза выше первой строки!»»

Range(«A2»).RowHeight = Range(«A1»).RowHeight * 2

Range(«B2»).Value = «Наша строка стала в 2 раза выше первой строки!»

MsgBox «Запишем в ячейку A3 высоту 2 строки, а в ячейку B3 вставим текст: «Такова высота второй строки!»»

Range(«A3»).Value = Range(«A2»).RowHeight

Range(«B3»).Value = «Такова высота второй строки!»

MsgBox «Применим к столбцу, в котором содержится ячейка B1, метод AutoFit для автоподбора ширины»

Range(«B1»).EntireColumn.AutoFit

MsgBox «Выделим текст в ячейке B2 красным цветом и выровним его по центру (по вертикали)»

Range(«B2»).Font.Color = vbRed

Range(«B2»).VerticalAlignment = xlCenter

MsgBox «Добавим к ячейкам диапазона A1:B3 границы»

Range(«A1:B3»).Borders.LineStyle = True

MsgBox «Сделаем границы ячеек в диапазоне A1:B3 двойными»

Range(«A1:B3»).Borders.LineStyle = xlDouble

MsgBox «Очистим ячейки диапазона A1:B3 от заливки, выравнивания, границ и содержимого»

Range(«A1:B3»).Clear

MsgBox «Присвоим высоте второй строки высоту первой, а ширине второго столбца — ширину первого»

Range(«A2»).RowHeight = Range(«A1»).RowHeight

Range(«B1»).ColumnWidth = Range(«A1»).ColumnWidth

MsgBox «Демонстрация форматирования ячеек закончена!»

End Sub

Вычисления в ячейках (свойство Value)

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

Обратите внимание, что разделителем дробной части у чисел в VBA Excel является точка, а не запятая.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Sub Primer2()

MsgBox «Запишем в ячейку A1 число 25.3, а в ячейку B1 — число 34.42»

Range(«A1»).Value = 25.3

Range(«B1»).Value = 34.42

MsgBox «Запишем в ячейку C1 произведение чисел, содержащихся в ячейках A1 и B1»

Range(«C1»).Value = Range(«A1»).Value * Range(«B1»).Value

MsgBox «Запишем в ячейку D1 формулу, которая перемножает числа в ячейках A1 и B1»

Range(«D1»).Value = «=A1*B1»

MsgBox «Заменим содержимое ячеек A1 и B1 на числа 6.258 и 54.1, а также активируем ячейку D1»

Range(«A1»).Value = 6.258

Range(«B1»).Value = 54.1

Range(«D1»).Activate

MsgBox «Мы видим, что в ячейке D1 произведение изменилось, а в строке состояния отображается формула; « _

& «следующим шагом очищаем задействованные ячейки»

Range(«A1:D1»).Clear

MsgBox «Демонстрация вычислений в ячейках завершена!»

End Sub

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

Различие свойств Text, Value и Value2

Построение с помощью кода VBA Excel таблицы с результатами сравнения того, как свойства Text, Value и Value2 возвращают число, дату и текст.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

Sub Primer3()

‘Присваиваем ячейкам всей таблицы общий формат на тот

‘случай, если формат отдельных ячеек ранее менялся

Range(«A1:E4»).NumberFormat = «General»

‘добавляем сетку (границы ячеек)

Range(«A1:E4»).Borders.LineStyle = True

‘Создаем строку заголовков

Range(«A1») = «Значение»

Range(«B1») = «Код формата» ‘формат соседней ячейки в столбце A

Range(«C1») = «Свойство Text»

Range(«D1») = «Свойство Value»

Range(«E1») = «Свойство Value2»

‘Назначаем строке заголовков жирный шрифт

Range(«A1:E1»).Font.Bold = True

‘Задаем форматы ячейкам A2, A3 и A4

‘Ячейка A2 — числовой формат с разделителем триад и двумя знаками после запятой

‘Ячейка A3 — формат даты «ДД.ММ.ГГГГ»

‘Ячейка A4 — текстовый формат

Range(«A2»).NumberFormat = «# ##0.00»

Range(«A3»).NumberFormat = «dd.mm.yyyy»

Range(«A4»).NumberFormat = «@»

‘Заполняем ячейки A2, A3 и A4 значениями

Range(«A2») = 2362.4568

Range(«A3») = CDate(«01.01.2021»)

‘Функция CDate преобразует текстовый аргумент в формат даты

Range(«A4») = «Озеро Байкал»

‘Заполняем ячейки B2, B3 и B4 кодами форматов соседних ячеек в столбце A

Range(«B2») = Range(«A2»).NumberFormat

Range(«B3») = Range(«A3»).NumberFormat

Range(«B4») = Range(«A4»).NumberFormat

‘Присваиваем ячейкам C2-C4 значения свойств Text ячеек A2-A4

Range(«C2») = Range(«A2»).Text

Range(«C3») = Range(«A3»).Text

Range(«C4») = Range(«A4»).Text

‘Присваиваем ячейкам D2-D4 значения свойств Value ячеек A2-A4

Range(«D2») = Range(«A2»).Value

Range(«D3») = Range(«A3»).Value

Range(«D4») = Range(«A4»).Value

‘Присваиваем ячейкам E2-E4 значения свойств Value2 ячеек A2-A4

Range(«E2») = Range(«A2»).Value2

Range(«E3») = Range(«A3»).Value2

Range(«E4») = Range(«A4»).Value2

‘Применяем к таблице автоподбор ширины столбцов

Range(«A1:E4»).EntireColumn.AutoFit

End Sub

Результат работы кода:

Сравнение свойств ячейки Text, Value и Value2

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


Хитрости »

27 Июль 2013              306896 просмотров


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

Range("A1").Value = "Привет"

Тоже самое можно сделать сразу для нескольких ячеек:

Range("A1:C10").Value = "Привет"

Если необходимо обратиться к именованному диапазону:

Range("Диапазон1").Select

Диапазон1 — это имя диапазона/ячейки, к которому надо обратиться в коде. Указывается в кавычках, как и адреса ячеек.
Но в VBA есть и альтернативный метод записи значений в ячейке — через объект Cells:

Cells(1, 1).Value = "Привет"

Синтаксис объекта Range:
Range(Cell1, Cell2)

  • Cell1 — первая ячейка диапазона. Может быть ссылкой на ячейку или диапазон ячеек, текстовым представлением адреса или имени диапазона/ячейки. Допускается указание несвязанных диапазонов(A1,B10), пересечений(A1 B10).
  • Cell2 — последняя ячейка диапазона. Необязательна к указанию. Допускается указание ссылки на ячейку, столбец или строку.

Синтаксис объекта Cells:
Cells(Rowindex, Columnindex)

  • Rowindex — номер строки
  • Columnindex — номер столбца

Исходя из этого несложно предположить, что к диапазону можно обратиться, используя Cells и Range:

'выделяем диапазон "A1:B10" на активном листе
Range(Cells(1,1), Cells(10,2)).Select

и для чего? Ведь можно гораздо короче:

Иногда обращение посредством Cells куда удобнее. Например для цикла по столбцам(да еще и с шагом 3) совершенно неудобно было бы использовать буквенное обозначение столбцов.
Объект Cells так же можно использовать для указания ячеек внутри непосредственно указанного диапазона. Например, Вам необходимо выделить ячейку в 3 строке и 2 столбце диапазона «D5:F56». Можно пройтись по листу и посмотреть, отсчитать нужное количество строк и столбцов и понять, что это будет «E7». А можно сделать проще:

Range("D5:F56").Cells(3, 2).Select

Согласитесь, это гораздо удобнее, чем отсчитывать каждый раз. Особенно, если придется оперировать смещением не на 2-3 ячейки, а на 20 и более. Конечно, можно было бы применить Offset. Но данное свойство именно смещает диапазон на указанное количество строк и столбцов и придется уменьшать на 1 смещение каждого параметра для получения нужной ячейки. Да и смещает на указанное количество строк и столбцов весь диапазон, а не одну ячейку. Это, конечно, тоже не проблема — можно вдобавок к этому использовать метод Resize — но запись получится несколько длиннее и менее наглядной:

Range("D5:F56").Offset(2, 1).Resize(1, 1).Select

И неплохо бы теперь понять, как значение диапазона присвоить переменной. Для начала переменная должна быть объявлена с типом Range. А т.к. Range относится к глобальному типу Object, то присвоение значения такой переменной должно быть обязательно с применением оператора Set:

Dim rR as Range
Set rR = Range("D5")

если оператор Set не применять, то в лучшем случае получите ошибку, а в худшем(он возможен, если переменной rR не назначать тип) переменной будет назначено значение Null или значение ячейки по умолчанию. Почему это хуже? Потому что в таком случае код продолжит выполняться, но логика кода будет неверной, т.к. эта самая переменная будет содержать значение неверного типа и применение её в коде в дальнейшем все равно приведет к ошибке. Только ошибку эту отловить будет уже сложнее.
Использовать же такую переменную в дальнейшем можно так же, как и прямое обращение к диапазону:

Вроде бы на этом можно было завершить, но…Это как раз только начало. То, что я написал выше знает практически каждый, кто пишет в VBA. Основной же целью этой статьи было пояснить некоторые нюансы обращения к диапазонам. Итак, поехали.

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

'так выглядит запись слова Test в ячейку А1
Range("A1").Select
Selection.Value = "Test"

Но как правило выделение — действие лишнее. Можно записать значение и без него:

'запишем слово Test в ячейку A1 на активном листе
Range("A1").Value = "Test"

Теперь чуть подробнее разберем, как обратиться к диапазону не выделяя его и при этом сделать все правильно. Диапазон и ячейка — это объекты листа. У каждого объекта есть родитель — грубо говоря это другой объект, который является управляющим для дочернего объекта. Для ячейки родительский объект — Лист, для Листа — Книга, для Книги — Приложение Excel. Если смотреть на иерархию зависимости объектов, то от старшего к младшему получится так:
Applicaton => Workbooks => Sheets => Range
По умолчанию для всех диапазонов и ячеек родительским объектом является текущий(активный) лист. Т.е. если для диапазона(ячейки) не указать явно лист, к которому он относится, в качестве родительского листа для него будет использован текущий — ActiveSheet:

'запишем слово Test в ячейку A1 на активном листе
Range("A1").Value = "Test"

Т.е. если в данный момент активен Лист1 — то слово Test будет записано в ячейку А1 Лист1. Если активен Лист3 — в А1 Лист3. Иначе говоря такая запись равносильна записи:

ActiveSheet.Range("A1").Value = "Test"

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

'активируем Лист2
Worksheets("Лист2").Select
'записываем слово Test в ячейку A1
Range("A1").Value = "Test"

Чтобы не активируя другой лист записать в него данные, необходимо явно указать принадлежность объекта Range именно этому листу:

'запишем слово Test в ячейку A1 на Лист2 независимо от того, какой лист активен
Worksheets("Лист2").Range("A1").Value = "Test"

Таким же образом происходит считывание данных с ячеек — если не указывать лист, данные ячеек которого необходимо считать — считаны будут данные с ячейки активного листа. Чтобы считать данные с Лист2 независимо от того, какой лист активен применяется такой код:

'считываем значение ячейки A1 с Лист2 независимо от того, какой лист активен
MsgBox Worksheets("Лист2").Range("A1").Value

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

'запишем слово Test в ячейку A1 на Лист2 книги Книга2.xlsx независимо от того, какая книга и какой лист активен
Workbooks("Книга2.xlsx").Worksheets("Лист2").Range("A1").Value = "Test"
'считываем значение ячейки A1 с Лист2 книги Книга3.xlsx независимо от того, какой лист активен
MsgBox Workbooks("Книга3.xlsx").Worksheets("Лист2").Range("A1").Value

Важный момент: лучше всегда указать имя книги вместе с расширением(.xlsx, xlsm, .xls и т.д.). Если в настройках ОС Windows(Панель управленияПараметры папок -вкладка ВидСкрывать расширения для зарегистрированных типов файлов) указано скрывать расширения — то указывать расширение не обязательно — Workbooks(«Книга2»). Но и ошибки не будет, если его указать. Однако, если пункт «Скрывать расширения для зарегистрированных типов файлов» отключен, то указание Workbooks(«Книга2») обязательно приведет к ошибке.


Очень часто ошибки обращения к ячейкам листов и книг делают начинающие, особенно в циклах по листам. Вот пример неправильного цикла:

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

MsgBox будет выдавать правильные значения, но сами имена листов будут записываться не на каждый лист, а последовательно в ячейку активного листа. Поэтому на активном листе в ячейке А1 будет имя последнего листа.
А вот так выглядит правильный цикл:
Вариант 1 — активация листа(медленный)

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    wsSh.Activate 'активируем каждый лист
    Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

Вариант 2 — без активации листа(быстрый и более правильный)

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    wsSh.Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox wsSh.Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

Важно: если код записан в модуле листа(правая кнопка мыши на листе-Исходный текст) и для объекта Range или Cells родитель явно не указан(т.е. нет имени листа и книги) — тогда в качестве родителя будет использован именно тот лист, в котором записан код, независимо от того какой лист активный. Иными словами — если в модуле листа записать обращение вроде Range(«A1»).Value = «привет», то слово привет всегда будет записывать в ячейку A1 именно того листа, в котором записан сам код. Это следует учитывать, когда располагаете свои коды внутри модулей листов.

В конструкциях типа Range(Cells(,),Cells(,)) Range является контейнером, в котором указываются ссылки на объекты, из которых и будет создана ссылка на непосредственно конечный объект.
Предположим, что активен «Лист1», а код запущен с листа «Итог».
Если запись будет вида

Sheets("Итог").Range(Cells(1, 1), Cells(10, 1))

это вызовет ошибку «Run-time error ‘1004’: Application-defined or object-defined error». А ошибка появляется потому, что контейнер и объекты внутри него не могут располагаться на разных листах, равно как и:

Sheets("Итог").Range(Cells(1, 1), Sheets("Итог").Cells(10, 1))
'запись ниже так же неверна
Range(Cells(1, 1), Sheets("Итог").Cells(10, 1))

т.к. ссылки на объекты внутри контейнера относятся к разным листам. Cells(1, 1) — к активному листу, а Sheets(«Итог»).Cells(10, 1) — к листу Итог.
А вот такие записи будут правильными:

Sheets("Итог").Range(Sheets("Итог").Cells(1, 1), Sheets("Итог").Cells(10, 1))
Range(Sheets("Итог").Cells(1, 1), Sheets("Итог").Cells(10, 1))

Вторая запись не содержит ссылки на родителя для Range, но ошибки это в большинстве случаев не вызовет — т.к. если для контейнера ссылка не указана, а для двух объектов внутри контейнера родитель один — он будет применен и для самого контейнера. Однако лучше делать как в первой строке — т.е. с обязательным указанием родителя для контейнера и для его составляющих. Т.к. при определенных обстоятельствах(например, если в момент обращения к диапазону активной является книга, открытая в режиме защищенного просмотра) обращение к Range без родителя может вызывать ошибку выполнения.
Если запись будет вида Range(«A1″,»A10»), то указывать ссылку на родителя внутри Range не обязательно — достаточно будет указать эту ссылку перед самим Range — Sheets(«Итог»).Range(«A1″,»A10»), т.к. текстовое представление адреса внутри Range не является объектом(у которого может быть какой-то родительский объект), что обязывает создать ссылку именно на родителя контейнера.

Разберем пример, приближенный к жизненной ситуации. Необходимо на лист Итог занести формулу вычитания, начиная с ячейки А2 и до последней заполненной. На момент записи активен Лист1. Очень часто начинающие записывают так:

Sheets("Итог").Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row) _
                                        .FormulaR1C1 = "=RC2-RC11"

Запись смешанная — и текстовое представление адреса ячейки(«A2:A») и ссылка на объект Cells. В данном случае явную ошибку код не вызовет, но и работать будет не всегда так, как хотелось бы. А это самое плохое, что может случиться при разработке.
Sheets(«Итог»).Range(«A2:A» — создается ссылка на столбец "A" листа Итог. Но далее идет вычисление последней строки первого столбца. И вот как раз это вычисление происходит на основе объекта Cells, который не содержит в себе ссылки на родительский объект. А значит он будет вычислять последнюю строку исключительно для текущего листа(если код записан в стандартном модуле, а не модуле листа) — т.е. для Лист1. Правильно было бы записать так:

Sheets("Итог").Range("A2:A" & Sheets("Итог").Cells(Rows.Count, 1).End(xlUp).Row) _
                                                      .FormulaR1C1 = "=RC2-RC11"

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

lLastRow = Workbooks("Книга3.xls").Sheets("Лист1").Cells(Rows.Count, 1).End(xlUp).Row

с виду все нормально, но есть нюанс. Rows.Count по умолчанию будет относится к активной книге, если записано в стандартном модуле. Приведенный выше код должен работать с книгой формата 97-2003 и вычислить последнюю заполненную ячейку на листе1. В книгах формата Excel 97-2003(.xls) всего 65536 строк. Если в момент выполнения приведенной строки активна книга формата 2007 и выше(форматы .xlsx, .xlsm, .xlsb и пр) — то Rows.Count вернет 1048576, т.к. именно такое количество строк в листах книг версий Excel, начиная с 2007. И т.к. в книге, в которой мы пытаемся вычислить последнюю строку всего 65536 строк — получим ошибку 1004, т.к. не может быть номера строки 1048576 на листе с количеством строк 65536. Поэтому имеет смысл указывать явно откуда считывать Rows.Count:

lLastRow = Workbooks("Книга3.xls").Sheets("Лист1").Cells(Workbooks("Книга3.xls").Sheets("Лист1").Rows.Count, 1).End(xlUp).Row

или применить конструкцию With

With Workbooks("Книга3.xls").Sheets("Лист1")
    lLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

Также не мешало бы упомянуть возможность выделения несмежного диапазона(часто его называют «рваным»). Это диапазон, который обычно привыкли выделять на листе при помощи зажатой клавиши Ctrl. Что это дает? Это дает возможность выделить одновременно ячейки A1 и B10 и записать значения только в них. Для этого есть несколько способов. Самый очевидный и описанный в справке — метод Union:

Union(Range("A1"), Range("B10")).Value = "Привет"

Однако существует и другой метод:

Range("A1,B10").Value = "Привет"

В чем отличие(я бы даже сказал преимущество) Union: можно применять в цикле по условию. Например, выделить в диапазоне A1:F50 только те ячейки, значение которых больше 10 и меньше 20:

Sub SelOne()
    Dim rCell As Range, rSel As Range
    For Each rCell In Range("A1:F50")
        If rCell.Value > 10 And rCell.Value < 20 Then
            If rSel Is Nothing Then
                Set rSel = rCell
            Else
                Set rSel = Union(rSel, rCell)
            End If
        End If
    Next rCell
    If Not rSel Is Nothing Then rSel.Select
End Sub

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

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

Также см.:
Как определить последнюю ячейку на листе через VBA?
Как определить первую заполненную ячейку на листе?
Как из Excel обратиться к другому приложению


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика


Download Article


Download Article

This wikiHow teaches you how to start using Visual Basic procedures to select data in Microsoft Excel. As long as you’re familiar with basic VB scripting and using more advanced features of Excel, you’ll find the selection process pretty straight-forward.

  1. 1

    Select one cell on the current worksheet. Let’s say you want to select cell E6 with Visual Basic. You can do this with either of the following options:[1]

    ActiveSheet.Cells(6, 5).Select
    

    ActiveSheet.Range("E6").Select
    
  2. 2

    Select one cell on a different worksheet in the same workbook. Let’s say our example cell, E6, is on a sheet called Sheet2. You can use either of the following options to select it:

    Application.Goto ActiveWorkbook.Sheets("Sheet2").Cells(6, 5)
    
    Application.Goto (ActiveWorkbook.Sheets("Sheet2").Range("E6"))
    

    Advertisement

  3. 3

    Select one cell on a worksheet in a different workbook. Let’s say you want to select a cell from Sheet1 in a workbook called BOOK2.XLS. Either of these two options should do the trick:

    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Cells(2,1)
    
    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("A2")
    
  4. 4

    Select a cell relative to another cell. You can use VB to select a cell based on its location relative to the active (or a different) cell. Just be sure the cell exists to avoid errors. Here’s how to use :

    • Select the cell three rows below and four columns to the left of the active cell:

      ActiveCell.Offset(3, -4).Select
      
    • Select the cell five rows below and four columns to the right of cell C7:

      ActiveSheet.Cells(7, 3).Offset(5, 4).Select
      
  5. Advertisement

  1. 1

    Select a range of cells on the active worksheet. If you wanted to select cells C1:D6 on the current sheet, you can enter any of the following three examples:

    ActiveSheet.Range(Cells(1, 3), Cells(6, 4)).Select
    
    ActiveSheet.Range("C1:D6").Select
    
    ActiveSheet.Range("C1", "D6").Select
    
  2. 2

    Select a range from another worksheet in the same workbook. You could use either of these examples to select cells C3:E11 on a sheet called Sheet3:

    Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("C3:E11")
    
    Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("C3", "E11")
    
  3. 3

    Select a range of cells from a worksheet in a different workbook. Both of these examples would select cells E12:F12 on Sheet1 of a workbook called BOOK2.XLS:

    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("E12:F12")
    
    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("E12", "F12")
    
  4. 4

    Select a named range. If you’ve assigned a name to a range of cells, you’d use the same syntax as steps 4-6, but you’d replace the range address (e.g., «E12», «F12») with the range’s name (e.g., «Sales»). Here are some examples:

    • On the active sheet:

      ActiveSheet.Range("Sales").Select
      
    • Different sheet of same workbook:

      Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("Sales")
      
    • Different workbook:

      Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("Sales")
      
  5. 5

    Select a range relative to a named range. The syntax varies depending on the named range’s location and whether you want to adjust the size of the new range.

    • If the range you want to select is the same size as one called Test5 but is shifted four rows down and three columns to the right, you’d use:
      ActiveSheet.Range("Test5").Offset(4, 3).Select
      
    • If the range is on Sheet3 of the same workbook, activate that worksheet first, and then select the range like this:
      Sheets("Sheet3").Activate ActiveSheet.Range("Test").Offset(4, 3).Select
      
  6. 6

    Select a range and resize the selection. You can increase the size of a selected range if you need to. If you wanted to select a range called Database’ and then increase its size by 5 rows, you’d use this syntax:

    Range("Database").Select Selection.Resize(Selection.Rows.Count + 5, _Selection.Columns.Count).Select
    
  7. 7

    Select the union of two named ranges. If you have two overlapping named ranges, you can use VB to select the cells in that overlapping area (called the «union»). The limitation is that you can only do this on the active sheet. Let’s say you want to select the union of a range called Great and one called Terrible:

    • Application.Union(Range("Great"), Range("Terrible")).Select
      
    • If you want to select the intersection of two named ranges instead of the overlapping area, just replace Application.Union with Application.Intersect.
  8. Advertisement

  1. 1

    Use this example data for the examples in this method. This chart full of example data, courtesy of Microsoft, will help you visualize how the examples behave:[2]

    A1: Name B1: Sales C1: Quantity
    A2: a B2: $10 C2: 5
    A3: b B3: C3: 10
    A4: c B4: $10 C4: 5
    A5: B5: C5:
    A6: Total B6: $20 C6: 20
  2. 2

    Select the last cell at the bottom of a contiguous column. The following example will select cell A4:

    ActiveSheet.Range("A1").End(xlDown).Select
    
  3. 3

    Select the first blank cell below a column of contiguous cells. The following example will select A5 based on the chart above:

    ActiveSheet.Range("A1").End(xlDown).Offset(1,0).Select
    
  4. 4

    Select a range of continuous cells in a column. Both of the following examples will select the range A1:A4:

    ActiveSheet.Range("A1", ActiveSheet.Range("a1").End(xlDown)).Select
    
    ActiveSheet.Range("A1:" & ActiveSheet.Range("A1"). End(xlDown).Address).Select
    
  5. 5

    Select a whole range of non-contiguous cells in a column. Using the data table at the top of this method, both of the following examples will select A1:A6:

    ActiveSheet.Range("A1",ActiveSheet.Range("A65536").End(xlUp)).Select
    
    ActiveSheet.Range("A1",ActiveSheet.Range("A65536").End(xlUp)).Select
    
  6. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

  • The «ActiveSheet» and «ActiveWorkbook» properties can usually be omitted if the active sheet and/or workbook(s) are implied.

Thanks for submitting a tip for review!

Advertisement

About This Article

Article SummaryX

1. Use ActiveSheet.Range(«E6»).Select to select E6 on the active sheet.
2. Use Application.Goto (ActiveWorkbook.Sheets(«Sheet2»).Range(«E6»)) to select E6 on Sheet2.
3. Add Workbooks(«BOOK2.XLS») to the last step to specify that the sheet is in BOOK2.XLS.

Did this summary help you?

Thanks to all authors for creating a page that has been read 167,714 times.

Is this article up to date?

“It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle

This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.

A Quick Guide to Ranges and Cells

Function Takes Returns Example Gives

Range

cell address multiple cells .Range(«A1:A4») $A$1:$A$4
Cells row, column one cell .Cells(1,5) $E$1
Offset row, column multiple cells Range(«A1:A2»)
.Offset(1,2)
$C$2:$C$3
Rows row(s) one or more rows .Rows(4)
.Rows(«2:4»)
$4:$4
$2:$4
Columns column(s) one or more columns .Columns(4)
.Columns(«B:D»)
$D:$D
$B:$D

Download the Code

 

The Webinar

If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.

(Note: Website members have access to the full webinar archive.)

vba ranges video

Introduction

This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.

 
Generally speaking, you do three main things with Cells

  1. Read from a cell.
  2. Write to a cell.
  3. Change the format of a cell.

 
Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion

In this post I will tackle each one, explain why you need it and when you should use it.

 
Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.

Important Notes

I have recently updated this article so that is uses Value2.

You may be wondering what is the difference between Value, Value2 and the default:

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

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

' Default uses value
Range("A1") = 56

 
Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.

It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)

The Range Property

The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.

The following example shows you how to place a value in a cell using the Range property.

' https://excelmacromastery.com/
Public Sub WriteToCell()

    ' Write number to cell A1 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67

    ' Write text to cell A2 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith"

    ' Write date to cell A3 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017#

End Sub

 
As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.

For the rest of this post I will use the code name to reference the worksheet.

code name worksheet

 
 
The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).

' https://excelmacromastery.com/
Public Sub UsingCodeName()

    ' Write number to cell A1 in sheet1 of this workbook
    Sheet1.Range("A1").Value2 = 67

    ' Write text to cell A2 in sheet1 of this workbook
    Sheet1.Range("A2").Value2 = "John Smith"

    ' Write date to cell A3 in sheet1 of this workbook
    Sheet1.Range("A3").Value2 = #11/21/2017#

End Sub

You can also write to multiple cells using the Range property

' https://excelmacromastery.com/
Public Sub WriteToMulti()

    ' Write number to a range of cells
    Sheet1.Range("A1:A10").Value2 = 67

    ' Write text to multiple ranges of cells
    Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith"

End Sub

 
You can download working examples of all the code from this post from the top of this article.
 

The Cells Property of the Worksheet

The worksheet object has another property called Cells which is very similar to range. There are two differences

  1. Cells returns a range of one cell only.
  2. Cells takes row and column as arguments.

 
The example below shows you how to write values to cells using both the Range and Cells property

' https://excelmacromastery.com/
Public Sub UsingCells()

    ' Write to A1
    Sheet1.Range("A1").Value2 = 10
    Sheet1.Cells(1, 1).Value2  = 10

    ' Write to A10
    Sheet1.Range("A10").Value2 = 10
    Sheet1.Cells(10, 1).Value2  = 10

    ' Write to E1
    Sheet1.Range("E1").Value2 = 10
    Sheet1.Cells(1, 5).Value2  = 10

End Sub

 
You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.

For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.

Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.

 
In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.

' https://excelmacromastery.com/
Public Sub WriteToColumn()

    Dim UserCol As Integer
    
    ' Get the column number from the user
    UserCol = Application.InputBox(" Please enter the column...", Type:=1)
    
    ' Write text to user selected column
    Sheet1.Cells(1, UserCol).Value2 = "John Smith"

End Sub

 
In the above example, we are using a number for the column rather than a letter.

To use Range here would require us to convert these values to the letter/number  cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.

Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.

Using Cells and Range together

As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows

' https://excelmacromastery.com/
Public Sub UsingCellsWithRange()

    With Sheet1
        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5

        ' Format Range B1:Z1 to be bold
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True

    End With

End Sub

 
As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.

 
In the following example we print out the address of the ranges we are using:

' https://excelmacromastery.com/
Public Sub ShowRangeAddress()

    ' Note: Using underscore allows you to split up lines of code
    With Sheet1

        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
        Debug.Print "First address is : " _
            + .Range(.Cells(1, 1), .Cells(10, 1)).Address

        ' Format Range B1:Z1 to be bold
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
        Debug.Print "Second address is : " _
            + .Range(.Cells(1, 2), .Cells(1, 26)).Address

    End With

End Sub

 
In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)

 
ImmediateWindow

 
ImmediateSampeText

 
You can download all the code for this post from the top of this article.
 

The Offset Property of Range

Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.

 
VBA Offset

 
We will first attempt to do this without using Offset.

' https://excelmacromastery.com/
' This sub tests with different values
Public Sub TestSelect()

    ' Monday
    SetValueSelect 1, 111.21
    ' Wednesday
    SetValueSelect 3, 456.99
    ' Friday
    SetValueSelect 5, 432.25
    ' Sunday
    SetValueSelect 7, 710.17

End Sub

' Writes the value to a column based on the day
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

 
As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution

' https://excelmacromastery.com/
' This sub tests with different values
Public 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)

    ' We use the day value with offset specify the correct column
    Sheet1.Range("G3").Offset(, lDay).Value2 = lValue

End Sub

 
As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.

 
One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset

' https://excelmacromastery.com/
Public Sub UsingOffset()

    ' Write to B2 - no offset
    Sheet1.Range("B2").Offset().Value2 = "Cell B2"

    ' Write to C2 - 1 column to the right
    Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2"

    ' Write to B3 - 1 row down
    Sheet1.Range("B2").Offset(1).Value2 = "Cell B3"

    ' Write to C3 - 1 column right and 1 row down
    Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3"

    ' Write to A1 - 1 column left and 1 row up
    Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1"

    ' Write to range E3:G13 - 1 column right and 1 row down
    Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13"

End Sub

Using the Range CurrentRegion

CurrentRegion returns a range of all the adjacent cells to the given range.

In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.

VBA CurrentRegion

A row or column of blank cells signifies the end of a current region.

You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.

If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.

For example
Range(“B3”).CurrentRegion will return the range B3:D14
Range(“D14”).CurrentRegion will return the range B3:D14
Range(“C8:C9”).CurrentRegion will return the range B3:D14
and so on

How to Use

We get the CurrentRegion as follows

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

Read Data Rows Only

Read through the range from the second row i.e.skipping the header row

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Start at row 2 - row after header
Dim i As Long
For i = 2 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i

Remove Header

Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Remove Header
Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)

' Start at row 1 as no header row
Dim i As Long
For i = 1 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i

 

Using Rows and Columns as Ranges

If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access

' https://excelmacromastery.com/
Public Sub UseRowAndColumns()

    ' Set the font size of column B to 9
    Sheet1.Columns(2).Font.Size = 9

    ' Set the width of columns D to F
    Sheet1.Columns("D:F").ColumnWidth = 4

    ' Set the font size of row 5 to 18
    Sheet1.Rows(5).Font.Size = 18

End Sub

Using Range in place of Worksheet

You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.

 
The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2

' https://excelmacromastery.com/
Public Sub UseColumnsInRange()

    ' This will set B1 and B2 to be bold
    Sheet1.Range("A1:C2").Columns(2).Font.Bold = True

End Sub

 
You can download all the code for this post from the top of this article.
 

Reading Values from one Cell to another

In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.

 
The following example shows you how to do this:

' https://excelmacromastery.com/
Public Sub ReadValues()

    ' Place value from B1 in A1
    Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2

    ' Place value from B3 in sheet2 to cell A1
    Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2

    ' Place value from B1 in cells A1 to A5
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2

    ' You need to use the "Value" property to read multiple cells
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2

End Sub

 
As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter

' https://excelmacromastery.com/
Public Sub CopyValues()

    ' Store the copy range in a variable
    Dim rgCopy As Range
    Set rgCopy = Sheet1.Range("B1:B5")

    ' Use this to copy from more than one cell
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5")

    ' You can paste to multiple destinations
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")

End Sub

 
The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.

Using the Range.Resize Method

When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.

Using the Resize function allows us to resize a range to a given number of rows and columns.

For example:
 

' https://excelmacromastery.com/
Sub ResizeExamples()
 
    ' Prints A1
    Debug.Print Sheet1.Range("A1").Address

    ' Prints A1:A2
    Debug.Print Sheet1.Range("A1").Resize(2, 1).Address

    ' Prints A1:A5
    Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
    
    ' Prints A1:D1
    Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
    
    ' Prints A1:C3
    Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
    
End Sub

 
When we want to resize our destination range we can simply use the source range size.

In other words, we use the row and column count of the source range as the parameters for resizing:

' https://excelmacromastery.com/
Sub Resize()

    Dim rgSrc As Range, rgDest As Range
    
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion

      ' Get the range destination
    Set rgDest = Sheet2.Range("A1")
    Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
    
    rgDest.Value2 = rgSrc.Value2

End Sub

 
We can do the resize in one line if we prefer:

' https://excelmacromastery.com/
Sub ResizeOneLine()

    Dim rgSrc As Range
    
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion
    
    With rgSrc
        Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
    End With
    
End Sub

Reading Values to variables

We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.

' https://excelmacromastery.com/
Public Sub UseVariables()

    ' Create
    Dim number As Long

    ' Read number from cell
    number = Sheet1.Range("A1").Value2

    ' Add 1 to value
    number = number + 1

    ' Write new value to cell
    Sheet1.Range("A2").Value2 = number

End Sub

 
To read text to a variable you use a variable of type String:

' https://excelmacromastery.com/
Public Sub UseVariableText()

    ' Declare a variable of type string
    Dim text As String

    ' Read value from cell
    text = Sheet1.Range("A1").Value2

    ' Write value to cell
    Sheet1.Range("A2").Value2 = text

End Sub

 
You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.

' https://excelmacromastery.com/
Public Sub VarToMulti()

    ' Read value from cell
    Sheet1.Range("A1:B10").Value2 = 66

End Sub

 
You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.

How to Copy and Paste Cells

If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.

Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
I have written a complete guide to copying data in Excel VBA here.

 
You can simply copy a range of cells like this:

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

 
Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.

 
It works like this

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

 
The following table shows a full list of all the paste types

Paste Type
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats

Reading a Range of Cells to an Array

You can also copy values by assigning the value of one range to another.

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

 
The value of  range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.  

 
The following code shows an example of using an array with a range:

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Create dynamic array
    Dim StudentMarks() As Variant

    ' Read 26 values into array from the first row
    StudentMarks = Range("A1:Z1").Value2

    ' Do something with array here

    ' Write the 26 values to the third row
    Range("A3:Z3").Value2 = StudentMarks

End Sub

 
Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns

Going through all the cells in a Range

Sometimes you may want to go through each cell one at a time to check value.

 
You can do this using a For Each loop shown in the following code

' https://excelmacromastery.com/
Public Sub TraversingCells()

    ' Go through each cells in the range
    Dim rg As Range
    For Each rg In Sheet1.Range("A1:A10,A20")
        ' Print address of cells that are negative
        If rg.Value < 0 Then
            Debug.Print rg.Address + " is negative."
        End If
    Next

End Sub

 
You can also go through consecutive Cells using the Cells property and a standard For loop.

 
The standard loop is more flexible about the order you use but it is slower than a For Each loop.

' https://excelmacromastery.com/
Public Sub TraverseCells()
 
    ' Go through cells from A1 to A10
    Dim i As Long
    For i = 1 To 10
        ' Print address of cells that are negative
        If Range("A" & i).Value < 0 Then
            Debug.Print Range("A" & i).Address + " is negative."
        End If
    Next
 
    ' Go through cells in reverse i.e. from A10 to A1
    For i = 10 To 1 Step -1
        ' Print address of cells that are negative
        If Range("A" & i) < 0 Then
            Debug.Print Range("A" & i).Address + " is negative."
        End If
    Next
 
End Sub

Formatting Cells

Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells

' https://excelmacromastery.com/
Public Sub FormattingCells()

    With Sheet1

        ' Format the font
        .Range("A1").Font.Bold = True
        .Range("A1").Font.Underline = True
        .Range("A1").Font.Color = rgbNavy

        ' Set the number format to 2 decimal places
        .Range("B2").NumberFormat = "0.00"
        ' Set the number format to a date
        .Range("C2").NumberFormat = "dd/mm/yyyy"
        ' Set the number format to general
        .Range("C3").NumberFormat = "General"
        ' Set the number format to text
        .Range("C4").NumberFormat = "Text"

        ' Set the fill color of the cell
        .Range("B3").Interior.Color = rgbSandyBrown

        ' Format the borders
        .Range("B4").Borders.LineStyle = xlDash
        .Range("B4").Borders.Color = rgbBlueViolet

    End With

End Sub

Main Points

The following is a summary of the main points

  1. Range returns a range of cells
  2. Cells returns one cells only
  3. You can read from one cell to another
  4. You can read from a range of cells to another range of cells.
  5. You can read values from cells to variables and vice versa.
  6. You can read values from ranges to arrays and vice versa
  7. You can use a For Each or For loop to run through every cell in a range.
  8. The properties Rows and Columns allow you to access a range of cells of these types

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Понравилась статья? Поделить с друзьями:
  • Excel vba диапазон весь лист
  • Excel vba диалоговое окно да нет
  • Excel vba диалог открытия файла
  • Excel vba диалог ввода
  • Excel vba день месяц год