Привязка excel с vba

Раннее и позднее связывание переменных с экземплярами внешних и внутренних объектов в VBA Excel. Преимущества ранней привязки объектов. Примеры кода.

Связывание – это процесс назначения внутреннего или внешнего объекта переменной.

Внутренними называются объекты, которые принадлежат объектной модели Excel (Range, Sheet, Workbook, Chart). Внешние объекты не принадлежат объектной модели Excel. А также новый экземпляр Excel.Application является внешним объектом по отношению к тому экземпляру приложения Excel, из которого он создается.

Раннее связывание

Раннее связывание – это объявление переменной с определенным типом объекта или присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта.

Определение типа объекта при ранней привязке выполняется еще до запуска приложения.

Объявление переменной определенного типа

Объявление переменной с определенным типом объекта:

‘Внутренние объекты

Dim myRange As Range

Dim mySheet As Sheets

Dim myWorkbook As Workbook

‘Внешние объекты

Dim myDictionary As Dictionary

Dim myExcel As Excel.Application

Dim myWord As Word.Application

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

‘Внутренние объекты

Set myRange = Range(«A1:D10»)

Set mySheet = Sheets(1)

Set myWorkbook = Workbooks.Open(«C:Книга1.xlsm»)

‘Внешние объекты

Set myDictionary = New Dictionary

Set myExcel = New Excel.Application

Set myWord = New Word.Application

Присвоение переменной объекта при объявлении

Присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта:

Dim myDictionary As New Dictionary

Dim myExcel As New Excel.Application

Dim myWord As New Word.Application

Ссылка на библиотеку внешнего объекта

Чтобы использовать раннее связывание для внешнего объекта, необходимо подключить в редакторе VBA Excel ссылку на библиотеку этого объекта, если она еще не подключена. Подключается ссылка на библиотеку в окне «References VBAproject», перейти в которое можно через главное меню редактора: Tools–>References…

Ссылка на библиотеку Microsoft Scripting Runtime, которая необходима для ранней привязки объекта Dictionary:

Ссылка на библиотеку Microsoft Word Object Library, которая необходима для ранней привязки объекта Word.Application:

После выбора библиотеки следует нажать кнопку «OK».

Преимущества ранней привязки

Главное преимущество раннего связывания заключается в возможности использовать при написании кода VBA Excel лист выбора и вставки свойств-методов привязанных объектов (Auto List Members). Лист подсказок отображается автоматически или вызывается сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».

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

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

Скопируйте процедуру Primer1 с ранней привязкой объекта Sheet в любой программный модуль:

Sub Primer1()

Dim mySheet As Sheet

mySheet

End Sub

Поставьте точку после mySheet в 3 строке и вы увидите лист выбора и вставки свойств-методов:

Если вдруг лист подсказок не отобразился автоматически, его можно вызвать сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».

Теперь скопируйте процедуру Primer2 с поздней привязкой объекта Sheet в любой программный модуль:

Sub Primer2()

Dim mySheet As Object

Set mySheet = Sheets(1)

mySheet

End Sub

Поставьте точку после mySheet в 4 строке – лист подсказок не отобразится:

Сочетания клавиш «Ctrl+Пробел» и «Ctrl+J» тоже не помогут. В данном случае тип объекта, присвоенного переменной, определяется только в процессе выполнения программы.

Позднее связывание

Позднее связывание – это присвоение переменной, объявленной как Object, экземпляра внутреннего объекта с помощью ключевого слова Set или экземпляра внешнего объекта с помощью ключевого слова Set и функции GetObject или CreateObject.

Тип объекта при поздней привязке определяется только в процессе выполнения программы.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

‘Внутренние объекты

‘Диапазон ячеек

Dim myRange As Object

Set myRange = Range(«A1:D10»)

‘Рабочий лист

Dim mySheet As Object

Set mySheet = Sheets(1)

‘Рабочая книга Excel

Dim myWorkbook As Object

Set myWorkbook = Workbooks.Open(«C:Книга1.xlsm»)

‘Внешние объекты

‘Словарь

Dim myDictionary As Object

Set myDictionary = CreateObject(«Scripting.Dictionary»)

‘Приложение Excel

Dim myExcel As Object

Set myExcel = CreateObject(«Excel.Application»)

‘Приложение Word

Dim myWord As Object

Set myWord = CreateObject(«Word.Application»)

Функция CreateObject используется для создания нового экземпляра объекта, а функция GetObject – для получения сохраненного объекта.

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

 

Здравствуйте.
Помогите с макросом, который запускает форму.

Есть простой макрос, запускающий форму.
Но форма все время открывается, в каком-то одном месте.

Как изменить макрос, чтобы форма открывалась, не где-нибудь а в районе ячейки, адрес которой указан в F3 ?
То есть форма откроется так, что ее верхний левый угол — будет совпадать с левым верхнем углом ячейки, чей адрес указан в F3 (это ячейка J7)

Прикрепленные файлы

  • книга.xlsb (18.18 КБ)

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

 

БМВ

Модератор

Сообщений: 21385
Регистрация: 28.12.2016

Excel 2013, 2016

#2

09.05.2019 14:14:17

Цитата
Красноглазый Пиркаф написал:
а в районе ячейки

а точнее?
Ох не совсем простое это занятие, нужно учитывать и положене окна и видимую область и масштаб
В закромах валялось, но не помню уже, работало ли :-) ActiveCell — это относительно какой ячейки позиционируем форму.

Код
'With Application
'    Me.Top = (((.Height - .UsableHeight) + (.ActiveCell.Top - .ActiveWindow.VisibleRange.Top) + .ActiveCell.Height - 2) * .ActiveWindow.Zoom / 100) + .ActiveWindow.Top + .Top
'    Me.Left = (((.Width - .UsableWidth) + (.ActiveCell.Left - .ActiveWindow.VisibleRange.Left) + .ActiveCell.MergeArea.Width + 17) * .ActiveWindow.Zoom / 100) + .ActiveWindow.Left + .Left
'End With

По вопросам из тем форума, личку не читаю.

 

Красноглазый Пиркаф

Пользователь

Сообщений: 110
Регистрация: 09.05.2019

#3

09.05.2019 14:19:38

БМВ, почему-то данная система не работает. Выдает ошибку:

Цитата
«Compile error: Invalid use of Me keyword»

А сам макрос выглядит так:

Код
Sub Form_Show11()
    UserForm1.Show
With Application
    Me.Top = (((.Height - .UsableHeight) + (.ActiveCell.Top - .ActiveWindow.VisibleRange.Top) + .ActiveCell.Height - 2) * .ActiveWindow.Zoom / 100) + .ActiveWindow.Top + .Top
    Me.Left = (((.Width - .UsableWidth) + (.ActiveCell.Left - .ActiveWindow.VisibleRange.Left) + .ActiveCell.MergeArea.Width + 17) * .ActiveWindow.Zoom / 100) + .ActiveWindow.Left + .Left
End With
End Sub

Как вы считаете, чем может быть вызвана эта ошибка ?

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

 

БМВ

Модератор

Сообщений: 21385
Регистрация: 28.12.2016

Excel 2013, 2016

Естесвенно, это надо  в Private Sub UserForm_Activate()

По вопросам из тем форума, личку не читаю.

 

БМВ, ясно, исправил.
Но все равно что-то не то.

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

Прикрепленные файлы

  • книга.xlsb (20.01 КБ)

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

 

БМВ

Модератор

Сообщений: 21385
Регистрация: 28.12.2016

Excel 2013, 2016

ну при масштабе 100 все ок, но не при других :-(

По вопросам из тем форума, личку не читаю.

 

БМВ, так у меня 100% масштаб и стоит.

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

 

sokol92

Пользователь

Сообщений: 4446
Регистрация: 10.09.2017

Добрый день, с праздником!

У Владимира (

ZVI

) есть известное

решение

.

 

Красноглазый Пиркаф

Пользователь

Сообщений: 110
Регистрация: 09.05.2019

#9

09.05.2019 17:24:30

sokol92,  вас тоже поздравляю с праздником.

Открываю файл, на который вы ссылаетесь — но макрос в нем, к сожалению — не работает.
Выдает ошибку:

Цитата
Could not load an object because it is not available on this machine

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

 

Ivan.kh

Пользователь

Сообщений: 2024
Регистрация: 04.03.2013

.

Прикрепленные файлы

  • ZVI.xlsm (24.45 КБ)

Изменено: Ivan.kh09.05.2019 18:33:52

 

Красноглазый Пиркаф

Пользователь

Сообщений: 110
Регистрация: 09.05.2019

#11

09.05.2019 18:40:10

Ivan.kh, не работает.
При двойном щелчке на ячейке — выдает ошибку:

Цитата
Run-time error 429: ActiveX component cant create object.

И еще выдает ошибку:

Цитата
Compile error: Type mismatch

Изменено: Красноглазый Пиркаф09.05.2019 18:44:21

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

 

Ivan.kh

Пользователь

Сообщений: 2024
Регистрация: 04.03.2013

на 2-х разных компьютерах проверил. все работает …

 

Ivan.kh, проверил этот файл еще раз.

Он работает только на Excel2008 а на Excel2013 — уже не работает.
(Выдает ошибку и подсвечивает в коде — слово «FindWindow»

Как изменить этот макрос, чтобы он и на excel2013 — тоже стал работать ?

Прикрепленные файлы

  • ZVI.xlsm (24.49 КБ)

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

 

БМВ

Модератор

Сообщений: 21385
Регистрация: 28.12.2016

Excel 2013, 2016

#14

09.05.2019 19:41:14

Цитата
Красноглазый Пиркаф написал:
на Excel2008

точно не сработает :-)

По вопросам из тем форума, личку не читаю.

 

БМВ, я говорю — что запустил этот макрос на эксель2008 — и там он работал.
И вопрос в том — что изменить в макросе, чтобы он заработал и на экселе2013.

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

 

sokol92

Пользователь

Сообщений: 4446
Регистрация: 10.09.2017

Попробуйте такую редакцию (#If Win64->VBA7, тип hwnd->Variant).

Прикрепленные файлы

  • ZVI.xlsm (31.67 КБ)

 

БМВ

Модератор

Сообщений: 21385
Регистрация: 28.12.2016

Excel 2013, 2016

#17

09.05.2019 20:14:48

Цитата
Красноглазый Пиркаф написал:
эксель2008

Excel 2007, 2010, Server 2008? Excel 2008 for MAC — знаю , Excel 2008  под Win — не знаю.

По вопросам из тем форума, личку не читаю.

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#18

09.05.2019 20:15:57

Цитата
Красноглазый Пиркаф написал:
Он работает только на Excel2008 а на Excel2013 — уже не работает.

ЭЭЭЭ… Вы, как-бы, ничего не путаете? Ибо данный код предназначен для нормального Excel, к коим относится 2013, ибо использует API Windows, но никак не 2008, предназначенный для огрызка, которому сии нюансы неведомы.

Изменено: RAN09.05.2019 20:16:59

 

Ivan.kh

Пользователь

Сообщений: 2024
Регистрация: 04.03.2013

Красноглазый Пиркаф, Для Excel на Mac есть отдельная ветка на форуме…

 

sokol92, спасибо.
Теперь все намного лучше и макрос работает в Excel2013.

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

Прикрепленные файлы

  • ZVI_2.xlsm (27.33 КБ)

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

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

#21

09.05.2019 21:35:26

Код
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
  If Not Intersect(Target, Range("J7")) Is Nothing Then
    With Target(1)
      If .HasFormula Then Exit Sub
      If IsDate(.Value) Or IsEmpty(.Value) Then
        UserForm1.Show vbModeless
        Cancel = True
      End If
    End With
  End If
End Sub 

Красноглазый Пиркаф,  а Вы УМЫШЛЕННО для всей книги делаете?

 

Красноглазый Пиркаф

Пользователь

Сообщений: 110
Регистрация: 09.05.2019

#22

09.05.2019 21:48:14

Юрий М, добавил этот код.
А как этот код к кнопке подключить ?

Я вот так записал, но выдает ошибку :

Код
Sub Макрос1()
  If Not Intersect(Target, Range("J7")) Is Nothing Then
    With Target(1)
      If .HasFormula Then Exit Sub
      If IsDate(.Value) Or IsEmpty(.Value) Then
        UserForm1.Show vbModeless
        Cancel = True
      End If
    End With
  End If
End Sub

Я имел ввиду — не двойной щелчок по ячейке J7, а запуск с кнопки.

Прикрепленные файлы

  • ZVI_3.xlsm (29.73 КБ)

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

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#23

09.05.2019 21:52:49

Убираем событие, указываем ячейку.

Код
Sub Macro1()
    With Range("J7")
      If .HasFormula Then Exit Sub
      If IsDate(.Value) Or IsEmpty(.Value) Then UserForm1.Show vbModeless
    End With
End Sub
 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

В Вашем примере событийный макрос, который сработает на двойной клик в любом листе. А Ваш вариант в #22 не сработает — нет Target в данном случае ))
Точно нужно на кнопку? И требуется уточнение — нажатие на кнопку должно отобразить форму, только если активна ячейка J7?

 

vikttur, ясно.
Теперь форма открывается, но не там где нужно.

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

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

#26

09.05.2019 22:10:02

Код
Sub Macro1()
  If ActiveCell.Address = "$J$7" Then
    With ActiveCell
      If .HasFormula Then Exit Sub
      If IsDate(.Value) Or IsEmpty(.Value) Then
        UserForm1.Show vbModeless
      End If
    End With
  End If
End Sub
 

Красноглазый Пиркаф

Пользователь

Сообщений: 110
Регистрация: 09.05.2019

#27

09.05.2019 22:11:40

Цитата
Юрий М написал:
В Вашем примере событийный макрос

Я знаю. Но это не мой пример, мне его дали.
Поэтому я и спрашиваю как его на кнопку навесить.

Цитата
Юрий М написал:
Точно нужно на кнопку? И требуется уточнение — нажатие на кнопку должно отобразить форму, только если активна ячейка J7?

Да — точно нужно на кнопку.
Нажатие на кнопку — должно отобразить форму у ячейки J7, вне зависимости от того — какая ячейка активна.

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

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

#28

09.05.2019 22:14:40

Цитата
Красноглазый Пиркаф написал:
вне зависимости от того — какая ячейка активна.

А сразу (СРАЗУ!) нельзя было об этом сказать?

 

Юрий М, так вроде бы я в первом сообщении сразу и написал свой вопрос.

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

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

#30

09.05.2019 22:21:07

Найдите в коде фрагмент и исправьте так:

Код
    ' Определить колонку и столбец ячейки под курсором мышки
'    With .RangeFromPoint(Pt.x, Pt.y).MergeArea.Cells
'      a = .Address
      a = "$J$7"
'    End With

27 / 2 / 0

Регистрация: 20.02.2013

Сообщений: 126

1

06.03.2013, 14:37. Показов 6596. Ответов 4


Студворк — интернет-сервис помощи студентам

Можно ли средствами VBA привязать переменную к ячейке, как это можно из самого Excel:

d_a1$ = .Range(«A48») — здесь идёт конкретная привязка, а если ячейку сдвинуть, то будет ошибка. Как связать?



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

06.03.2013, 14:45

2

Visual Basic
1
Set MyCell = .Range("A48")

Переменная будет содержать ссылку на объект-ячейку. Если ячейка сдвинется (поменяет адрес) в результате удаления/добавления ячеек, «привязка» останется.



0



trvi

27 / 2 / 0

Регистрация: 20.02.2013

Сообщений: 126

06.03.2013, 16:53

 [ТС]

3

Сделал:

Visual Basic
1
2
3
4
5
Sub fffff()
Dim mycell As Range
    Set mycell = Worksheets("Лист1").Range("X3")
    MsgBox mycell
End Sub

в ячейке x3 значение 45
после перемещения ячейки со значением 45, макрос уже не видит значение



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

06.03.2013, 17:16

4

Код модуля

Visual Basic
1
2
3
4
5
6
7
8
9
Dim mycell As Range 'переменная модуля
 
Sub Установить_привязку()
    Set mycell = Worksheets("Лист1").Range("X3")
End Sub
 
Sub Вывести_значение()
    MsgBox mycell
End Sub



1



27 / 2 / 0

Регистрация: 20.02.2013

Сообщений: 126

06.03.2013, 17:21

 [ТС]

5

Работает… А в коде значение ячейки .Range(«X3») осталось, хотя ячейку перенес на другой адрес.
Это стабильное решение или после закрытия и открытия придётся сначала запускать «Установить привязку»?



0



Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert

You can refer to or access a worksheet range using properties and methods of the Range object. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. One of the most important aspects in vba coding is referencing and using Ranges within a Worksheet. This section (divided into 2 parts) covers various properties and methods for referencing, accessing & using ranges, divided under the following chapters.

Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address;

Activate & Select Cells; the ActiveCell & Selection;

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method;

Excel VBA Refer to Ranges — Union & Intersect; Resize; Areas, CurrentRegion, UsedRange & End Properties; SpecialCells Method:

Ranges — Union & Intersect;

Resize a Range;

Referencing — Contiguous Block(s) of Cells, Range of Contiguous Data, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region, Last Used Row or Column;


Related Links:

Working with Objects in Excel VBA

Excel VBA Application Object, the Default Object in Excel

Excel VBA Workbook Object, working with Workbooks in Excel

Microsoft Excel VBA — Worksheets

Excel VBA Custom Classes and Objects


——————————————————————————————-

Contents:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

Activate & Select Cells; the ActiveCell & Selection

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

——————————————————————————————-

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. A Range object is always with reference to a specific worksheet, and Excel currently does not support Range objects spread over multiple worksheets.

Range object refers to a single cell:

Dim rng As Range
Set rng = Range(«A1»)

Range object refers to a block of contiguous cells:

Dim rng As Range
Set rng = Range(«A1:C3»)

Range object refers to a row:

Dim rng As Range
Set rng = Rows(1)

Range object refers to multiple columns:

Dim rng As Range
Set rng = Columns(«A:C»)

Range object refers to 2 or more blocks of contiguous cells — using the ‘Union method’ & ‘Selection’ (these have been explained in detail later in this section).

Union method:

Dim rng1 As Range, rng2 As Range, rngUnion As Range
‘set a contiguous block of cells as the first range:
Set rng1 = Range(«A1:B2»)
‘set another contiguous block of cells as the second range:
Set rng2 = Range(«D3:E4»)
‘assign a variable (range object) to represent the union of the 2 ranges, using the Union method:
Set rngUnion = Union(rng1, rng2)
‘set interior color for the range which is the union of 2 range objects:
rngUnion.Interior.Color = vbYellow

Selection property:

‘select 2 contiguous block of cells, using the Select method:
Range(«A1:B2,D3:E4»).Select
‘perform action (set interior color of cells to yellow) on the Selection, which is a Range object:
Selection.Interior.Color = vbYellow

Range property of the Worksheet object ie. Worksheet.Range Property. Syntax: WorksheetObject.Range(Cell1, Cell2). You have an option to use only the Cell1 argument and in this case it will have to be a A1-style reference to a range which can include a range operator (colon) or the union operator (comma), or the reference to a range can be a defined name. Examples of using this type of reference are Worksheets(«Sheet1»).Range(«A1») which refers to cell A1; or Worksheets(«Sheet1»).Range(«A1:B3») which refers to the cells A1, A2, A3, B1, B2 & B3. When both the Cell1 & Cell2 arguments are used (cell1 and cell2 are Range objects), these refer to the cells at the top-left corner and the lower-right corner of the range (ie. the start and end cells of the range), and these arguments can be a single cell, an entire row or column or a single named cell. An example of using this type of reference is Worksheets(«Sheet1»).Range(Cells(1, 1), Cells(3, 2)) which refers to the cells A1, A2, A3, B1, B2 & B3. Omitting the object qualifier will default to the active sheet viz. using the code Range(«A1») will return cell A1 of the active sheet, and will be the same as using Application.Range(«A1») or ActiveSheet.Range(«A1»).

Range property of the Range object: Use the Range.Range property [Syntax: RangeObject.Range(Cell1,Cell2)] for relative referencing ie. to access a range relative to a range object. For example, Worksheets(«Sheet1»).Range(«C5:E8»).Range(«A1») will refer to Range(«C5») and Worksheets(«Sheet1»).Range(«C5:E8»).Range(«B2») will refer to Range(«D6»).

Shortcut Range Reference: As compared to using the Range property, you can also use a shorter code to refer to a range by using square brackets to enclose an A1-style reference or a name. While using square brackets, you do not type the Range word or wrap the range in quotation marks to make it a string. Using square brackets is similar to applying the Evaluate method of the Application object. The Range property or the Evaluate method use a string argument which enables you to manipulate the string with vba code, whereas using the square brackets will be inflexible in this respect. Examples: using [A1].Value = 5 is equivalent to using Range(«A1»).Value = 5; using [A1:A3,B2:B4,C3:D5].Interior.Color = vbRed is equivalent to Range(«A1:A3,B2:B4,C3:D5»).Interior.Color = vbRed; and with named ranges, [Score].Interior.Color = vbBlue is equivalent to Range(«Score»).Interior.Color = vbBlue. Using square brackets only enables reference to fixed ranges which is a significant shortcoming. Using the Range property enables you to manipulate the string argument with vba code so that you can use variables to refer to a dynamic range, as illustrated below:

Sub DynamicRangeVariable()
‘using a variable to refer a dynamic range.

Dim i As Integer

‘enters the text «Hello» in each cell from B1 to B5:
For i = 1 To 5
Range(«B» & i) = «Hello»
Next

End Sub

The Cells Property returns a Range object referring to all cells in a worksheet or a range, as it can be used with respect to an Application object, a Worksheet object or a Range object. Application.Cells Property refers to all cells in the active worksheet. You can use the code Application.Cells or omit the object qualifier (this property is a member of ‘globals’) and use the code Cells to refer to all cells of the active worksheet. The Worksheet.Cells Property (Syntax: WorksheetObject.Cells) refers to all cells of a specified worksheet. Use the code Worksheets(«Sheet1»).Cells to refer to all cells of worksheet named «Sheet1». Use the Range.Cells Property ro refer to cells in a specified range — (Syntax: RangeObject.Cells). This property can be used as Range(«A1:B5»).Cells, however using the word cells in this case is immaterial because with or without this word the code will refer to the range A1:B5. To refer to a specific cell, use the Item property of the Range object (as explained in detail below) by specifying the relative row and column positions after the Cells keyword, viz. Worksheets(«Sheet1»).Cells.Item(2, 3) refers to range C2 and Worksheets(«Sheet1»).Range(«C2»).Cells(2, 3) will refer to range E3. Because the Item property is the Range object’s default property you can omit the Item word word and use the code Worksheets(«Sheet1»).Cells(2, 3) which also refers to range C2. You may find it preferable in some cases to use Worksheets(«Sheet1»).Cells(2, 3) over Worksheets(«Sheet1»).Range(«C2») because variables for the row and column can easily be used therein.

Item property of the Range object: Use the Range.Item Property to return a range as offset to the specified range. Syntax: RangeObject.Item(RowIndex, ColumnIndex). The Item word can be omitted because Item is the Range object’s default property. It is necessary to specify the RowIndex argument while ColumnIndex is optional. RowIndex is the index number of the cell, starting with 1 and increasing from left to right and then down. Worksheets(«Sheet1»).Cells.Item(1) or Worksheets(«Sheet1»).Cells(1) refers to range A1 (the top-left cell in the worksheet), Worksheets(«Sheet1»).Cells(2) refers to range B1 (cell next to the right of the top-left cell). While using a single-parameter reference of the Item property (ie. RowIndex), if index exceeds the number of columns in the specified range, the reference will wrap to successive rows within the range columns. Omitting the object qualifier will default to active sheet. Cells(16385) refers to range A2 of the active sheet in Excel 2007 which has 16384 columns, and Cells(16386) refers to range B2, and so on. Also note that RowIndex and ColumnIndex are offsets and relative to the specified Range (ie. relative to the top-left corner of the specified range). Both Range(«B3»).Item(1) and Range(«B3:D6»).Item(1) refer to range B3. The following refer to range D4, the sixth cell in the range: Range(«B3:D6»).Item(6) or Range(«B3:D6»).Cells(6) or Range(«B3:D6»)(6). ColumnIndex refers to the column number of the cell, can be a number starting with 1 or can be a string starting with the letter «A». Worksheets(«Sheet1»).Cells(2, 3) and Worksheets(«Sheet1»).Cells(2, «C») both refer to range C2 wherein the RowIndex is 2 and ColumnIndex is 3 (column C). Range(«C2»).Cells(2, 3) refers to range E3 in the active sheet, and Range(«C2»).Cells(4, 5) refers to range G5 in the active sheet. Using Range(«C2»).Item(2, 3) and Range(«C2»).Item(4, 5) has the same effect and will refer to range E3 & range G5 respectively. Using Range(«C2:D3»).Cells(2, 3) and Range(«C2:D3»).Cells(4, 5) will also refer to range E3 & range G5 respectively. Omitting the Item or Cells word — Range(«C2:D3»)(2, 3) and Range(«C2:D3»)(4, 5) also refers to range E3 & range G5 respectively. It is apparant here that you can refer to and return cells outside the original specified range, using the Item property.

Columns property of the Worksheet object: Use the Worksheet.Columns Property (Syntax: WorksheetObject.Columns) to refer to all columns in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Columns will return all columns of the worksheet; Worksheets(«Sheet1»).Columns(1) returns the first column (column A) in the worksheet; Worksheets(«Sheet1»).Columns(«A») returns the first column (column A); Worksheets(«Sheet1»).Columns(«A:C») returns the columns A, B & C; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Columns(1) will return the first column of the active sheet, and will be the same as using Application.Columns(1).

Columns property of the Range object: Use the Range.Columns Property (Syntax: RangeObject.Columns) to refer to columns in a specified range. Example1: color cells from all columns of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns.Interior.Color = vbYellow. Example2: color cells from first column of the range only ie. B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the columns from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first column of the first area only ie. cells B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Columns(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to column A of the ActiveSheet: Columns(1).Interior.Color = vbRed.

Use the Worksheet.Rows Property (Syntax: WorksheetObject.Rows) to refer to all rows in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Rows will return all rows of the worksheet; Worksheets(«Sheet1»).Rows(1) returns the first row (row one) in the worksheet; Worksheets(«Sheet1»).Rows(3) returns the third row (row three) in the worksheet; Worksheets(«Sheet1»).Rows(«1:3») returns the first 3 rows; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Rows(1) will return the first row of the active sheet, and will be the same as using Application.Rows(1).

Use the Range.Rows Property (Syntax: RangeObject.Rows) to refer to rows in a specified range. Example1: color cells from all rows of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Rows.Interior.Color = vbYellow. Example2: color cells from first row of the range only ie. B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4»).Rows(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the rows from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first row of the first area only ie. cells B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Rows(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to row one of the ActiveSheet: Rows(1).Interior.Color = vbRed.

To refer to a range as offset from a specified range, use the Range.Offset Property. Syntax: RangeObject.Offset(RowOffset, ColumnOffset). Both arguments are optional to specify. The RowOffset argument specifies the number of rows by which the specified range is offset — negative values indicating upward offset and positive values indicating downward offset, with default value being 0. The ColumnOffset argument specifies the number of columns by which the specified range is offset — negative values indicating left offset and positive values indicating right offset, with default value being 0. Examples: Range(«C5»).Offset(1, 2) offsets 1 row & 2 columns and refers to Range E6, Range(«C5:D7»).Offset(1, -2) offsets 1 row downward & 2 columns to the left and refers to Range (A6:B8).

Accessing a worksheet range, with vba code:-

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1» (omitting to mention a property with the Range object will assume the Value property, as shown below):

Worksheets(«Sheet1»).Range(«A1»).Value = 10

Worksheets(«Sheet1»).Range(«A1») = 10

Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:

ActiveSheet.Cells(2, 3).Value = 10

Referencing a range of cells:

Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:

ActiveSheet.Range(«A1:B3»).Value = 10

ActiveSheet.Range(«A1», «B3»).Value = 10

ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10

Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1,B3»).Value = 10

Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:

ActiveWorkbook.Worksheets(«Sheet3»).

Range(«B2:D3,H7»).Interior.Color = vbRed

Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:

Range(«Score»).Value = 10

ActiveSheet.Range(«Score»).Value = 10

Select all the cells of the active worksheet:

ActiveSheet.Cells.Select

Cells.Select

Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:

ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»

ActiveSheet.Cells.Font.Size = 11

Cells.Font.Size = 11

Referencing Row(s) or Column(s):

Select all the Rows of active worksheet:

ActiveSheet.Rows.Select

Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Rows(2).Value = 10

Select all the Columns of the active worksheet:

ActiveSheet.Columns.Select

Columns.Select

Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:

ActiveSheet.Columns(3).Value = 10

Columns(«C»).Value = 10

Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Columns(«A:C»).Value = 10

Relative Referencing:

Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«A1») = 10

Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«B2») = 10

Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:

Range(«C5»).Offset(1, 2) = 10

Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:

Range(«C5:E8»).Offset(2, 3) = 10

Example 1 — Using Range, Cells, Columns & Rows property — refer Image 1:

Sub CellsColumnsRowsProperty()
‘using Range, Cells, Columns & Rows property — refer Image 1:

Dim ws As Worksheet
Dim rng As Range
Dim r As Integer, c As Integer, n As Integer, i As Integer, j As Integer

‘set worksheet:
Set ws = Worksheets(«Sheet1»)
‘activate worksheet:
ws.activate

‘enter numbers starting from 1 in each row, for a 5 row & 5 column range (A1:E5):

For r = 1 To 5

n = 1

For c = 1 To 5

Cells(r, c).Value = n

n = n + 1

Next c

Next r

‘set range to A1:E5, wherein the numbers have been entered as above:
Set rng = Range(Cells(1, 1), Cells(5, 5))

‘set background color of each even number column to yellow and of each odd number column to green:

For i = 1 To 5

If i Mod 2 = 0 Then

rng.Columns(i).Interior.Color = vbYellow
Else

rng.Columns(i).Interior.Color = vbGreen

End If

Next i

‘set font color to red and set font to bold for of even number rows:

For j = 1 To 5

If j Mod 2 = 0 Then

rng.Rows(j).Font.Bold = True

rng.Rows(j).Font.Color = vbRed

End If

Next j

‘set font for all cells of the range to italics:
rng.Cells.Font.Italic = True

End Sub

To return the number of the first row in a range, use the Range.Row Property. If the specified range contains multiple areas, this property will return the number of the first row in the first area (Areas property has been explained in detail later in this section). Syntax: RangeObject.Row. To return the number of the first column in a range, use the Range.Column Property. If the specified range contains multiple areas, this property will return the number of the first column in the first area. Syntax: RangeObject.Column.

Examples:

Get the number of the first row in the specified range — returns 4:

MsgBox ActiveSheet.Range(«B4»).Row

MsgBox Worksheets(«Sheet1»).Range(«B4:D7»).Row

Get the number of the first column in the specified range — returns 2:

MsgBox ActiveSheet.Range(«B4:D7»).Column

Get the number of the last row in the specified range — returns 7:

Explanation: Range(«B4:D7»).Rows.Count returns 4 (the number of rows in the range). Range(«B4:D7»).Rows(Range(«B4:D7»).Rows.Count) or Range(«B4:D7»).Rows(4), returns the last row in the specified range.

MsgBox Range(«B4:D7»).Rows(Range(«B4:D7»).

Rows.Count).Row

Example 2: Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Sub RowColumnProperty()
‘Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Dim rng As Range, cell As Range
Dim i As Integer

Set rng = Worksheets(«Sheet1»).Range(«B4:D7»)

‘enter its row number & column number within each cell in the specified range:

For Each cell In rng

cell.Value = cell.Row & «,» & cell.Column

Next

‘set background color of each alternate row of the specified range:

For i = 1 To rng.Rows.count

If i Mod 2 = 1 Then

rng.Rows(i).Interior.Color = vbGreen

Else

rng.Rows(i).Interior.Color = vbYellow

End If

Next

End Sub

Also refer to Example 23, of using the End & Row properties to determine the last used row or column with data.

You can get a Range reference in vba language by using the Range.Address Property, which returns the address of a Range as a string value. This property is read-only.

Examples of using the Address Property:

Returns $B$2:

MsgBox Range(«B2»).Address

Returns $B$2,$C$3:

MsgBox Range(«B2,C3»).Address

Returns $A$1:$B$2,$C$3,$D$4:

Dim strRng As String
Range(«A1:B2,C3,D4»).Select
strRng = Selection.Address
MsgBox strRng

Returns $B2:

MsgBox Range(«B2»).Address(RowAbsolute:=False)

Returns B$2:

MsgBox Range(«B2»).Address(ColumnAbsolute:=False)

Returns R2C2:

MsgBox Range(«B2»).Address(ReferenceStyle:=xlR1C1)

Includes the worksheet (active sheet — «Sheet1») & workbook («Book1.xlsm») name, and returns [Book1.xlsm]Sheet1!$B$2:

MsgBox Range(«B2»).Address(External:=True)

Returns R[1]C[-1] — Range(«B2») is 1 row and -1 columns relative to Range(«C1»):

MsgBox Range(«B2»).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Returns RC[-2] — Range(«A1») is 0 row and -2 columns relative to Range(«C1»):

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Activate & Select Cells; the ActiveCell & Selection

The Select method (of the Range object) is used to select a cell or a range of cells in a worksheet — Syntax: RangeObject.Select. Ensure that the worksheet wherein the Select method is applied to select cells, is the active sheet. The ActiveCell Property (of the Application object) returns a single active cell (Range object) in the active worksheet. Remember that the ActiveCell property will not work if the active sheet is not a worksheet. When a cell(s) is selected in the active window, the Selection property (of the Application object) returns a Range object representing all cells which are currently selected in the active worksheet. A Selection may consist of a single cell or a range of multiple cells, but there will only be one active cell within it, which is returned by using the ActiveCell property. When only a single cell is selected, the ActiveCell property returns this cell. On selecting multiple cells using the Select method, the first referenced cell becomes the active cell, and thereafter you can change the active cell using the Activate method. Both the ActiveCell Property & the Selection property are read-only, and not specifying the Application object qualifier viz. Application.ActiveCell or ActiveCell, Application.Selection or Selection, will have the same effect. To activate a single cell within the current selection, use the Activate Method (of the Range object) — Syntax: RangeObject.Activate, and this activated cell is returned by using the ActiveCell property.

We have discussed above that a Selection may consist of a single cell or a range of multiple cells, whereas there can be only one active cell within the Selection. When you activate a cell outside the current selection, the activated cell becomes the only selected cell. You can also use the Activate method to specify a range of multiple cells, but in effect only a single cell will be activated, and this activated cell will be the top-left corner cell of the range specified in the method. If this top-left cell lies within the selection, the current selection will not change, but if this top-left cell lies outside the selection, then the specified range in the Activate method becomes the new selection.

See below codes which illustrate the concepts of ActiveCell and Selection.

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C1:F5»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«F5:C1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C5:F1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Activate a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8:
Range(«C8»).Activate
MsgBox ActiveCell.Address

Activate a cell outside the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now A2:
Range(«A2»).Activate
MsgBox ActiveCell.Address

Select a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now C8:
Range(«C8»).Select
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is within the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8 — refer Image 3b:
Range(«C8:G12»).Activate
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is outside the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection range changes to range B1:F8, and the active cell is now B1 — refer Image 3c:
Range(«B1:F8»).Activate
MsgBox ActiveCell.Address

Using the Application.Selection Property returns the selected object wherein the selection determines the returned object type. Where the selection is a range of cells, this property returns a Range object, and this Selection — which is a Range object — can comprise of a single cell, or multiple cells or multiple non-contiguous ranges. And as mentioned above, the Select method (of the Range object) is used to select a cell or a range of cells in a worksheet. Therefore, after selecting a range, you can perform actions on the selection of cells by using the Selection object. See below illustration. 

Sub SelectionObject()

‘select cells in the active sheet using the Range.Select method:

Range(«A1:B3,D6»).Select

‘perform action (set interior color of cells to red) on the Selection, which is a Range object:

Selection.Interior.Color = vbRed

End Sub

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

Use the Range.EntireRow Property to return an entire row or rows within which the specific range is contained. Using this property returns a Range object referring to the entire row(s). Syntax: RangeObject.EntireRow. Use the Range.EntireColumn Property to return an entire column or columns within which the specific range is contained. Using this property returns a Range object referring to the entire column(s). Syntax: RangeObject.EntireColumn.

Examples of using the EntireRow & EntireColumn Properties

Selects row no. 2:

Range(«A2»).EntireRow.Select

Selects row nos. 2, 3 & 4:

Range(«A2:C4»).EntireRow.Select

Enters value 3 in range A3 ie. in the first cell of row no. 3:

Cells(3, 4).EntireRow.Cells(1, 1).Value = 3

Selects column A:

Range(«A2»).EntireColumn.Select

Selects columns A to C:

Range(«A2:C4»).EntireColumn.Select

Enters value 4 in range D1 ie. in the first cell of column no. 4:

Cells(3, 4).EntireColumn.Cells(1, 1).Value = 4

Use the Range.Insert Method to insert a cell or a range of cells in a worksheet. Syntax: RangeObject.Insert(Shift, CopyOrigin). Both arguments are optional to specify. When you insert cell(s) the other cells are shifted to make way, and you can set a value for the Shift argument to determine the direction in which the other cells are shifted — specifying xlShiftDown (value -4121) will shift the cells down, and xlShiftToRight (value -4161) shifts the cells to the right. Omitting this argument will decide the shift direction based on the shape of the range. Specifying xlFormatFromLeftOrAbove (value 0) for the CopyOrigin argument will copy the format for inserted cell(s) from the above cells or cells to the left, and specifying xlFormatFromRightOrBelow (value 1) will copy format from the below cells or cells to the right.

Illustrating Range.Insert Method — for start data refer Image 4a:

Shifts cells down and copies formatting of inserted cell from above cell — refer image 4b:

Range(«B2»).Insert

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4c:

Range(«B2:C4»).Insert

Shifts cells down and copies formatting of inserted cells from above cells — refer image 4d:

Range(«B2:D3»).Insert

Shifts cells down and copies formatting of inserted cells from below cells — refer image 4e:

Range(«B2:D3»).Insert CopyOrigin:=xlFormatFromRightOrBelow

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4f:

Range(«B2:D3»).Insert shift:=xlShiftToRight

Shifts cells to the right and copies formatting of inserted cells from cells to the right — refer image 4g:

Range(«B2:D3»).Insert shift:=xlShiftToRight, CopyOrigin:=xlFormatFromRightOrBelow

Inserts 2 rows — row no 2 & 3 — and copies formatting of inserted rows from above cells — refer image 4h:

Range(«B2:D3»).EntireRow.Insert

Below are some illustrations of inserting entire row(s) or column(s) dynamically in a worksheet.

Example 3: Insert row or column — specify the row / column to insert.

Sub InsertRowColumn()
‘Insert row or column — specify the row / column to insert:

Dim ws As Worksheet
Set ws = Worksheets(«Sheet1»)

‘NOTE: each of the below codes need to be run individually.

‘specify the exact row number to insert — insert a row as row no 12:
ws.Rows(12).Insert

‘specify the range below which to insert a row — insert a row below range C3 ie. as row no 4.
ws.Range(«C3»).EntireRow.Offset(1, 0).Insert

‘specify the exact column number to insert — insert a column as column no 4:
ws.Columns(4).Insert

‘specify the range to the right of which to insert a column — insert a column to the right of range C3 ie. as column no 4.

ws.Range(«C3»).EntireColumn.Offset(0, 1).Insert

End Sub

Example 4: Insert row(s) after a specified value is found.

Sub InsertRow1()
‘insert row(s) after a specified value is found:

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim lFindRow As Long

Set ws = Worksheets(«Sheet1»)

‘find a value after which to insert a row:
Set rngSearch = ws.Range(«A1:E100»)
‘begin search AFTER the last cell in search range (this will start serach from the first cell in search range):
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

‘exit procedure if value not found:

If Not rngFind Is Nothing Then

lFindRow = rngFind.Row

MsgBox lFindRow

Else

MsgBox «Value not found!»

Exit Sub

End If

‘NOTE: each of the below codes need to be run individually.

‘if value found is in row no 12, one row will be inserted below as row no 13:
ws.Cells(lFindRow + 1, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow + 3, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow, 1).Offset(3).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted above (as row nos 12, 13 & 14) and the value found row 12 will be pushed down to row 15:
ws.Cells(lFindRow, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(Cells(lFindRow, 1), Cells(lFindRow + 2, 1)).EntireRow.Insert
‘alternate:
ws.Rows(lFindRow & «:» & lFindRow + 2).EntireRow.Insert Shift:=xlDown

‘if value found is in row no 12, 3 rows will be inserted below (as row nos 13, 14 & 15) and the value found row 12 will remain at the same position:
ws.Cells(lFindRow + 1, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(ws.Cells(lFindRow + 1, 1), ws.Cells(lFindRow + 3, 1)).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted after row no 13 (as row nos 14, 15 & 16) and existing rows 12 & 13 will remain at the same position:

ws.Cells(lFindRow + 2, 1).EntireRow.Resize(3).Insert

End Sub

Example 5: Insert a row, n rows above the last used row.

Sub InsertRow2()
‘insert a row, n rows above the last used row

Dim ws As Worksheet
Dim lRowsC As Long

Set ws = Worksheets(«Sheet1»)

‘determine the last used row in a column (column A):
lRowsC = ws.Cells(Rows.count, «A»).End(xlUp).Row
MsgBox lRowsC

‘set n to the no of rows above the last used row:
n = 5

‘check if there are enough rows before the last used row, else you will get an error:

If lRowsC >= n Then

‘insert a row, n rows above the last used row — if last used row is no 5 before insertion, then insert as row no 1 and the last used row will become no 6 (similarly, if last used row is 27, then insert as row no 23) :

ws.Rows(lRowsC).Offset(-n + 1, 0).EntireRow.Insert

Else

MsgBox «Not enough rows before the last used row!»

End If

End Sub

Example 6: Insert a row each time the searched value is found in a range.

For live code of this example, click to download excel file.

Sub InsertRow3()
‘search value in a range and insert a row each time the value is found.
‘you can set the search range with the variable rngSearch in below code — the code will look within this range to find the value below which row is to be inserted.

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim strAddress As String

Set ws = Worksheets(«Sheet1»)

‘set search range:
Set rngSearch = ws.Range(«A1:K100»)
MsgBox «Searching for ‘ExcelVBA’ within range: » & rngSearch.Address
‘begin search AFTER the last cell in search range
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)

‘find value in specified range, starting search AFTER the last cell in search range:
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

If rngFind Is Nothing Then

MsgBox «Value not found!»

Exit Sub

Else

‘save cell address of first value found:

strAddress = rngFind.Address

Do

‘find next occurrence of value:

Set rngFind = rngSearch.FindNext(After:=rngFind)

‘insert row below when value is found (if value is found twice in a row, then 2 rows will be inserted):

rngFind.Offset(1).EntireRow.Insert

‘loop till reaching the first value found range:

Loop While rngFind.Address <> strAddress

End If

End Sub

Example 7: Insert rows (user-defined number) within consecutive values found in a column — refer Images 5a & 5b.

For live code of this example, click to download excel file.

Sub InsertRow4()
‘insert rows (user-defined number) wherever 2 consecutive values are found in a column.
‘set column number in which 2 consecutive values are checked to insert rows, using the variable lCellColumn in below code.
‘set row number from where to start searching consecutive values, using the variable lCellRow in below code.
‘refer Image 5a which shows raw data, and Image 5b after this procedure is executed — a single row (lRowsInsert value entered as 1 in input box) is inserted where consecutive values appear in column 1:

Dim ws As Worksheet
Dim lLastUsedRow As Long, lRowsInsert As Long, lCellRow As Long, lCellColumn As Long
Dim rng As Range

Set ws = Worksheets(«Sheet1»)
ws.Activate

‘set column number in which 2 consecutive values are checked to insert rows:
lCellColumn = 1
‘set row number from where to start searching consecutive values:
lCellRow = 1

‘determine the last used row in the column (column no. lCellColumn):
lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘enter number of rows to insert between 2 consecutive values:
lRowsInsert = InputBox(«Enter number of rows to insert»)

If lRowsInsert < 1 Then

MsgBox «Error — please enter a value equal to or greater than 1»

Exit Sub

End If

MsgBox «This code will insert » & lRowsInsert & » rows, wherever consecutive values are found in column number » & lCellColumn & «, starting search from row number » & lCellRow

‘loop till the row number equals the last used row (ie. loop right till the end value in the column):

Do While lCellRow < lLastUsedRow

Set rng = Cells(lCellRow, lCellColumn)

‘in case of 2 consecutive values:

If rng <> «» And rng.Offset(1, 0) <> «» Then

‘enter the user-defined number of rows:

Range(rng.Offset(1, 0), rng.Offset(lRowsInsert, 0)).EntireRow.Insert

lCellRow = lCellRow + lRowsInsert + 1

‘determine the last used row — it is dynamic and changes on insertion of rows:

lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘alternate method to determine the last used row, when number of rows inserted is fixed — this is faster than using End(xlUp):

‘lLastUsedRow = lLastUsedRow + lRowsInsert + 1

‘MsgBox lLastUsedRow

Else

lCellRow = lCellRow + 1

End If

Loop

End Sub

«Привязать» форму к ячейке

Модератор:Naeel Maqsudov

sergvk

Сообщения:128
Зарегистрирован:21 июн 2005, 14:33
Откуда:Крым, Феодосия
Контактная информация:

Мне необходимо открывать форму и при открытии задать ее положение в окне Excel, причем так, что бы форма была «привязана» (например к ячейке «А1») :lol: Возможно ли это сделать?

Avsha

Сообщения:664
Зарегистрирован:08 сен 2005, 13:47
Откуда:KZ

12 апр 2006, 02:10

что бы форма была «привязана» (например к ячейке «А1»)

Что-то это мне напоминает контекстное меню, может добавить в него свои пункты.
Или нужна обязательно форма?

sergvk

Сообщения:128
Зарегистрирован:21 июн 2005, 14:33
Откуда:Крым, Феодосия
Контактная информация:

14 апр 2006, 17:25

Что-то это мне напоминает контекстное меню, может добавить в него свои пункты.
Или нужна обязательно форма?

.. не совсем — :( ( Мне надо открыть форму при активации листа в районе, например, Range(«A1:C4»)
Дело в том, что мне надо спрашивать пользователя часто, но не хочется делать это через постоянное открывание формы.
В зависимости от действий пользователя, соответственно будет изменяться содержимое элементов на форме.
В общем то форма будет открыта всегда и надо, что бы она распологалась всегда в одном месте по отношению к листу — :) )))

Аватара пользователя

Ser Artur

Сообщения:82
Зарегистрирован:24 май 2005, 16:32

15 апр 2006, 19:09

Prosti vot tak

Код: Выделить всё

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address = "$A$1" Then
UserForm1.Show
End If
End Sub

Ser Artur

Sokl

Сообщения:449
Зарегистрирован:12 сен 2005, 08:52
Откуда:ОМ

17 апр 2006, 13:53

Ну, ничего себе! «Привязал» форму к ячейке!
:shock:
Кстати, у меня не получилось вывести форму по координатам X и Y ячейки… Челендж блин!

Аватара пользователя

Naeel Maqsudov

Сообщения:2551
Зарегистрирован:20 фев 2004, 19:17
Откуда:Moscow, Russia
Контактная информация:

18 апр 2006, 00:42

Не удивительно!
У UserForm при StartupPosition=0 координаты Left и Top показывают положение формы на экране (т.е. 0:0 — это верхний левый угол экрана и ось Y направлена ВНИЗ). Они естественно в пикселах.

Left и Top ячеек дают координаты:
1) внутри рабочей области документа (т.е. 0:0 это верхний левый угол A1) Т.е. эти кординаты могут оказаться далеко за экраном
2) не в пикселах, а в пунктах (как шрифт)

Sokl

Сообщения:449
Зарегистрирован:12 сен 2005, 08:52
Откуда:ОМ

18 апр 2006, 11:50

Дык это я понял ишо тогда, когда пытался «вычислить» координаты ячейки относительно экрана… безуспешно…
(пункты перевести в пикселы теоретически можно
.PointsToScreenPixelsY
только вот практически невозможно — возвращает «0» всегда???)

Аватара пользователя

Naeel Maqsudov

Сообщения:2551
Зарегистрирован:20 фев 2004, 19:17
Откуда:Moscow, Russia
Контактная информация:

18 апр 2006, 22:32

У меня нормальные значения возвращает, но от этого не легче

Код: Выделить всё

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Application.Caption = _
  Target.Application.ActiveWindow.PointsToScreenPixelsY(Target.Top) & "-" & _
  Target.Application.ActiveWindow.PointsToScreenPixelsX(Target.Left)
End Sub

Аватара пользователя

Naeel Maqsudov

Сообщения:2551
Зарегистрирован:20 фев 2004, 19:17
Откуда:Moscow, Russia
Контактная информация:

18 апр 2006, 23:28

Эврика!!!
Вот привязка к координатам ячейки, где было кликнуто правой кнопкой.

Код: Выделить всё

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
  Cancel = True
  Dim b As CommandBar
  dx = 0: dy = 0
  For Each b In Application.CommandBars
    If b.Visible Then
      Select Case b.Position
       Case msoBarLeft: dx = dx + b.Width
       Case msoBarMenuBar, msoBarTop: dy = dy + b.Height
      End Select
    End If
  Next
  With Target.Application.ActiveWindow
    UserForm1.Left = (Target.Left - .VisibleRange.Left) * .Zoom / 100 + .Application.Left + dx
    UserForm1.Top = (Target.Top - .VisibleRange.Top) * .Zoom / 100 + .Application.Top + dy
    UserForm1.Show
  End With
End Sub

Тут сначала вычисляется размер области, занимаемой тулбарами (DX,DY)
Ну а дальше дело техники:
1) минус .VisibleRange.TopLeft — убирает то что получилось в результате прокрутки листа
2) * .Zoom / 100 — учитывает масштаб листа (как оказалось это тоже надо учитывать)
3) и прибавить сдвиг самого окна, а затем размеры тулбаров

Надо конечно еще чуть-чуть добавить, так как от края окна до тулбаров есть еще толщина границы окна, но ее точное значение надо доставать функциями WinAPI (GetSystemMetrics, или что-то в этом роде, но это уже мелочи — можно пренебречь)

Понравилась статья? Поделить с друзьями:
  • Привязать содержании к страницам в word
  • Привязанные таблицы в excel
  • Привет excel мои первые
  • Привести телефоны к одному виду excel
  • Привести к строке excel