Named ranges excel что это

Содержание

  • Манипуляции с именованными областями
    • Создание именованного диапазона
    • Операции с именованными диапазонами
    • Управление именованными диапазонами
  • Вопросы и ответы

Именованный диапазон в Microsoft Excel

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

Манипуляции с именованными областями

Именованный диапазон — это область ячеек, которой пользователем присвоено определенное название. При этом данное наименование расценивается Excel, как адрес указанной области. Оно может использоваться в составе формул и аргументов функций, а также в специализированных инструментах Excel, например, «Проверка вводимых значений».

Существуют обязательные требования к наименованию группы ячеек:

  • В нём не должно быть пробелов;
  • Оно обязательно должно начинаться с буквы;
  • Его длина не должна быть больше 255 символов;
  • Оно не должно быть представлено координатами вида A1 или R1C1;
  • В книге не должно быть одинаковых имен.

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

Имя диапазона строке имен в Microsoft Excel

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

Имя диапазону не присвоено в Microsoft Excel

Создание именованного диапазона

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

  1. Самый быстрый и простой вариант присвоения названия массиву – это записать его в поле имен после выделения соответствующей области. Итак, выделяем массив и вводим в поле то название, которое считаем нужным. Желательно, чтобы оно легко запоминалось и отвечало содержимому ячеек. И, безусловно, необходимо, чтобы оно отвечало обязательным требованиям, которые были изложены выше.
  2. Присвоение имени диапазону через поле имен в Microsoft Excel

  3. Для того, чтобы программа внесла данное название в собственный реестр и запомнила его, жмем по клавише Enter. Название будет присвоено выделенной области ячеек.

Наименование диапазону через поле имен присвоено в Microsoft Excel

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

  1. Выделяем массив, над которым требуется выполнить операцию. Клацаем по выделению правой кнопкой мыши. В открывшемся списке останавливаем выбор на варианте «Присвоить имя…».
  2. Переход к присвоению имени диапазону ячеек через контекстное меню в Microsoft Excel

  3. Открывается окошко создания названия. В область «Имя» следует вбить наименование в соответствии с озвученными выше условиями. В области «Диапазон» отображается адрес выделенного массива. Если вы провели выделение верно, то вносить изменения в эту область не нужно. Жмем по кнопке «OK».
  4. Окно создания имени в Microsoft Excel

  5. Как можно видеть в поле имён, название области присвоено успешно.

Наименование диапазону через контекстное меню присвоено в Microsoft Excel

Lumpics.ru

Ещё один вариант выполнения указанной задачи предусматривает использование инструментов на ленте.

  1. Выделяем область ячеек, которую требуется преобразовать в именованную. Передвигаемся во вкладку «Формулы». В группе «Определенные имена» производим клик по значку «Присвоить имя».
  2. Переход к присвоению имени диапазону через кнопку на ленте в Microsoft Excel

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

Окно создания имени в программе Microsoft Excel

Последний вариант присвоения названия области ячеек, который мы рассмотрим, это использование Диспетчера имен.

  1. Выделяем массив. На вкладке «Формулы», клацаем по крупному значку «Диспетчер имен», расположенному всё в той же группе «Определенные имена». Или же можно вместо этого применить нажатие сочетания клавиш Ctrl+F3.
  2. Переход в Диспетчер имен в Microsoft Excel

  3. Активируется окно Диспетчера имён. В нем следует нажать на кнопку «Создать…» в верхнем левом углу.
  4. Переход к созданию имени в Диспетчере имён в Microsoft Excel

  5. Затем запускается уже знакомое окошко создания файлов, где нужно провести те манипуляции, о которых шёл разговор выше. То имя, которое будет присвоено массиву, отобразится в Диспетчере. Его можно будет закрыть, нажав на стандартную кнопку закрытия в правом верхнем углу.

Закрытие окна Диспетчера имён в Microsoft Excel

Урок: Как присвоить название ячейке в Экселе

Операции с именованными диапазонами

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

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

  1. Прежде всего, на листе со списком присваиваем диапазону наименование любым из тех способов, о которых шла речь выше. В итоге, при выделении перечня в поле имён у нас должно отображаться наименование данного массива. Пусть это будет наименование «Модели».
  2. Наименование диапазону моделей присвоено в Microsoft Excel

  3. После этого перемещаемся на лист, где находится таблица, в которой нам предстоит создать выпадающий список. Выделяем область в таблице, в которую планируем внедрить выпадающий список. Перемещаемся во вкладку «Данные» и щелкаем по кнопке «Проверка данных» в блоке инструментов «Работа с данными» на ленте.
  4. Переход в окно проверки данных в Microsoft Excel

  5. В запустившемся окне проверки данных переходим во вкладку «Параметры». В поле «Тип данных» выбираем значение «Список». В поле «Источник» в обычном случае нужно либо вручную вписать все элементы будущего выпадающего списка, либо дать ссылку на их перечень, если он расположен в документе. Это не очень удобно, особенно, если перечень располагается на другом листе. Но в нашем случае все намного проще, так как мы соответствующему массиву присвоили наименование. Поэтому просто ставим знак «равно» и записываем это название в поле. Получается следующее выражение:

    =Модели

    Жмем по «OK».

  6. Окно проверки вводимых значений в Microsoft Excel

  7. Теперь при наведении курсора на любую ячейку диапазона, к которой мы применили проверку данных, справа от неё появляется треугольник. При нажатии на этот треугольник открывается список вводимых данных, который подтягивается из перечня на другом листе.
  8. Выпадающий список в Microsoft Excel

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

Значение из выпадающего списка выбрано в Microsoft Excel

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

Итак, мы имеем таблицу, в которой помесячно расписана выручка пяти филиалов предприятия. Нам нужно узнать общую выручку по Филиалу 1, Филиалу 3 и Филиалу 5 за весь период, указанный в таблице.

Таблица выручки по филиалам предприятия в Microsoft Excel

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

  3. Таким же образом, выделяя соответствующие области, даем названия строкам и других филиалов: «Филиал_2», «Филиал_3», «Филиал_4», «Филиал_5».
  4. Имя всем диапазонам таблицы пррисвоено в Microsoft Excel

  5. Выделяем элемент листа, в который будет выводиться итог суммирования. Клацаем по иконке «Вставить функцию».
  6. Переход в Мастер функций в Microsoft Excel

  7. Инициируется запуск Мастера функций. Производим перемещение в блок «Математические». Останавливаем выбор из перечня доступных операторов на наименовании «СУММ».
  8. Переход в окно аргументов функции СУММ в Microsoft Excel

  9. Происходит активация окошка аргументов оператора СУММ. Данная функция, входящая в группу математических операторов, специально предназначена для суммирования числовых значений. Синтаксис представлен следующей формулой:

    =СУММ(число1;число2;…)

    Как нетрудно понять, оператор суммирует все аргументы группы «Число». В виде аргументов могут применяться, как непосредственно сами числовые значения, так и ссылки на ячейки или диапазоны, где они расположены. В случае применения массивов в качестве аргументов используется сумма значений, которая содержится в их элементах, подсчитанная в фоновом режиме. Можно сказать, что мы «перескакиваем», через действие. Именно для решения нашей задачи и будет использоваться суммирование диапазонов.

    Всего оператор СУММ может насчитывать от одного до 255 аргументов. Но в нашем случае понадобится всего три аргумента, так как мы будет производить сложение трёх диапазонов: «Филиал_1», «Филиал_3» и «Филиал_5».

    Итак, устанавливаем курсор в поле «Число1». Так как мы дали названия диапазонам, которые требуется сложить, то не нужно ни вписывать координаты в поле, ни выделять соответствующие области на листе. Достаточно просто указать название массива, который подлежит сложению: «Филиал_1». В поля «Число2» и «Число3» соответственно вносим запись «Филиал_3» и «Филиал_5». После того, как вышеуказанные манипуляции были сделаны, клацаем по «OK».

  10. Окно аргументов функции СУММ в Microsoft Excel

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

Результат вычисления функции СУММ в Microsoft Excel

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

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

Урок: Как посчитать сумму в Майкрософт Эксель

Управление именованными диапазонами

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

  1. Чтобы перейти в Диспетчер, перемещаемся во вкладку «Формулы». Там следует кликнуть по иконке, которая так и называется «Диспетчер имен». Указанная иконка располагается в группе «Определенные имена».
  2. Переход в Диспетчер имен в программе Microsoft Excel

  3. После перехода в Диспетчер для того, чтобы произвести необходимую манипуляцию с диапазоном, требуется найти его название в списке. Если перечень элементов не очень обширный, то сделать это довольно просто. Но если в текущей книге располагается несколько десятков именованных массивов или больше, то для облегчения задачи есть смысл воспользоваться фильтром. Клацаем по кнопке «Фильтр», размещенной в правом верхнем углу окна. Фильтрацию можно выполнять по следующим направлениям, выбрав соответствующий пункт открывшегося меню:
    • Имена на листе;
    • в книге;
    • с ошибками;
    • без ошибок;
    • Определенные имена;
    • Имена таблиц.

    Для того, чтобы вернутся к полному перечню наименований, достаточно выбрать вариант «Очистить фильтр».

  4. Фильтрация в Диспетчере имён в Microsoft Excel

  5. Для изменения границ, названия или других свойств именованного диапазона следует выделить нужный элемент в Диспетчере и нажать на кнопку «Изменить…».
  6. Переход к изменению именованного диапазона через Диспетчер имен в Microsoft Excel

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

    В поле «Имя» можно сменить наименование области. В поле «Примечание» можно добавить или отредактировать существующее примечание. В поле «Диапазон» можно поменять адрес именованного массива. Существует возможность сделать, как применив ручное введение требуемых координат, так и установив курсор в поле и выделив соответствующий массив ячеек на листе. Его адрес тут же отобразится в поле. Единственное поле, значения в котором невозможно отредактировать – «Область».

    После того, как редактирование данных окончено, жмем на кнопку «OK».

Окно изменения имени именнованного диапазона в Microsoft Excel

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

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

  1. Чтобы провести процедуру удаления, выделяем нужный элемент из перечня и жмем на кнопку «Удалить».
  2. Удаление именованного диапазона через Диспетчер имен в Microsoft Excel

  3. После этого запускается диалоговое окно, которое просит подтвердить свою решимость удалить выбранный элемент. Это сделано во избежание того, чтобы пользователь по ошибке не выполнил данную процедуру. Итак, если вы уверены в необходимости удаления, то требуется щелкнуть по кнопке «OK» в окошке подтверждения. В обратном случае жмите по кнопке «Отмена».
  4. Подтверждение удаления имени в Microsoft Excel

  5. Как видим, выбранный элемент был удален из перечня Диспетчера. Это означает, что массив, к которому он был прикреплен, утратил наименование. Теперь он будет идентифицироваться только по координатам. После того, как все манипуляции в Диспетчере завершены, клацаем по кнопке «Закрыть», чтобы завершить работу в окне.

Закрытие окна Диспетчера имен в Microsoft Excel

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


November 15, 2015/



Chris Newman

Blog Post Banner (hdr).png

What Is A Named Range?

Creating a named range allows you to refer to a cell or group of cells with a custom name instead of the usual column/row reference. The HUGE benefit to using Named Ranges is it adds the ability to describe the data inside your cells. Let’s look at a quick example:

Can you tell if shipping costs are charged with the product price?

  1. = (B7 + B5 * C4) * (1 + A3)

  2. =(ShippingCharge + ProductPrice * Quantity) * (1 + TaxRate)

Hopefully, you can clearly see option number TWO gives you immediate insight to whether the cost of the products includes shipping costs. This allows the user to easily understand how the formula is calculating without having to waste time searching through cells to figure out what is what.

How Do I Use Named Ranges?

As a financial analyst, I play around with a bunch of rates. Examples could be anything from a tax rate to an estimated inflation rate. I use named ranges to organize my variables that either are changed infrequently (ie Month or Year) or something that will be static for a good amount of time (ie inflation rate). Here are a list of common names I use on a regular basis:

  • ReportDate

  • Year

  • Month

  • FcstID

  • TaxRate

  • RawData

Creating Unique Names On The Fly

It is super easy to create a Named Range. All you have to do is highlight the cell(s) you want to reference and give it a name in the Name Box. You name cannot have any spaces in it, so if you need to separate words you can either capitalize the beginning of each new word or use an underscore (_). Make sure you hit the ENTER key after you have finished typing the name to confirm the creation of the Named Range.

As a side note, any Named Range created with the Name Box has a Workbook scope. This means the named range can be accessed by any worksheet in your Excel file.

Name Box.png

Creating Names With The «Name Manager»

If you want to customize your named ranges even more, you can open up the Name Manager (Formulas tab > Defined Names group > Name Manager button) to edit and create new named ranges.

I won’t go into great detail in this article, but know that with the Name Manager you can

  1. Change the name of an existing Named Range

  2. Change the reference formula

  3. Specify the scope (what worksheets the name can be accessed from)

On To The VBA

Now that you have had a brief overview on Named Ranges, lets dig into some VBA macros you can use to help automate the use of Named Ranges.

Add A Named Range

The below VBA code shows ways you can create various types of named ranges.

Sub NameRange_Add()
‘PURPOSE: Various ways to create a Named Range
‘SOURCE: www.TheSpreadsheetGuru.com

Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String

‘Single Cell Reference (Workbook Scope)
  RangeName = «Price»
  CellName = «D7»

    Set cell = Worksheets(«Sheet1»).Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell

‘Single Cell Reference (Worksheet Scope)
  RangeName = «Year»
  CellName = «A2»

    Set cell = Worksheets(«Sheet1»).Range(CellName)
  Worksheets(«Sheet1»).Names.Add Name:=RangeName, RefersTo:=cell

‘Range of Cells Reference (Workbook Scope)
  RangeName = «myData»
  CellName = «F9:J18»

    Set cell = Worksheets(«Sheet1»).Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell

‘Secret Named Range (doesn’t show up in Name Manager)
  RangeName = «Username»
  CellName = «L45»

    Set cell = Worksheets(«Sheet1»).Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell, Visible:=False

End Sub

Loop Through Named Ranges

This VBA macro code shows how you can cycle through the named ranges within your spreadsheet.

Sub NamedRange_Loop()
‘PURPOSE: Delete all Named Ranges in the Active Workbook
‘SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name

‘Loop through each named range in workbook
  For Each nm In ActiveWorkbook.Names
    Debug.Print nm.Name, nm.RefersTo
  Next nm

  ‘Loop through each named range scoped to a specific worksheet
  For Each nm In Worksheets(«Sheet1»).Names
    Debug.Print nm.Name, nm.RefersTo
  Next nm

End Sub

Delete All Named Ranges

If you need to clean up a bunch of junk named ranges, this VBA code will let you do it.

Sub NamedRange_DeleteAll()
‘PURPOSE: Delete all Named Ranges in the ActiveWorkbook (Print Areas optional)
‘SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name
Dim DeleteCount As Long

‘Delete PrintAreas as well?
  UserAnswer = MsgBox(«Do you want to skip over Print Areas?», vbYesNoCancel)
    If UserAnswer = vbYes Then SkipPrintAreas = True
    If UserAnswer = vbCancel Then Exit Sub

‘Error Handler in case Delete Function Errors out
  On Error GoTo Skip

‘Loop through each name and delete
  For Each nm In ActiveWorkbook.Names
    If SkipPrintAreas = True And Right(nm.Name, 10) = «Print_Area» Then GoTo Skip

        ‘Error Handler in case Delete Function Errors out
      On Error GoTo Skip

        ‘Delete Named Range
      nm.Delete
      DeleteCount = DeleteCount + 1

    Skip:
   ‘Reset Error Handler
      On Error GoTo 0
  Next

     ‘Report Result
  If DeleteCount = 1 Then
    MsgBox «[1] name was removed from this workbook.»
  Else
    MsgBox «[» & DeleteCount & «] names were removed from this workbook.»
  End If

End Sub

Delete Named Ranges with Error References

This VBA code will delete only Named Ranges with errors in them. These errors can be caused by worksheets being deleted or rows/columns being deleted.

Sub NamedRange_DeleteErrors()
‘PURPOSE: Delete all Named Ranges with #REF error in the ActiveWorkbook
‘SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name
Dim DeleteCount As Long

‘Loop through each name and delete
  For Each nm In ActiveWorkbook.Names
    If InStr(1, nm.RefersTo, «#REF!») > 0 Then
      ‘Error Handler in case Delete Function Errors out
        On Error GoTo Skip

            ‘Delete Named Range
        nm.Delete
        DeleteCount = DeleteCount + 1
    End If
Skip:
  ‘Reset Error Handler
    On Error GoTo 0
  Next

    ‘Report Result
  If DeleteCount = 1 Then
    MsgBox «[1] errorant name was removed from this workbook.»
  Else
    MsgBox «[» & DeleteCount & «] errorant names were removed from this workbook.»
  End If

  End Sub

Anything Missing From This Guide?

Let me know if you have any ideas for other useful VBA macros concerning Named Ranges. Or better yet, share with me your own macros and I can add them to the article for everyone else to see! I look forward to reading your comments below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

Named ranges are one of these crusty old features in Excel that few users understand. New users may find them weird and scary, and even old hands may avoid them because they seem pointless and complex.

But named ranges are actually a pretty cool feature. They can make formulas *a lot* easier to create, read, and maintain. And as a bonus, they make formulas easier to reuse (more portable).

In fact, I use named ranges all the time when testing and prototyping formulas. They help me get formulas working faster. I also use named ranges because I’m lazy, and don’t like typing in complex references :)

The basics of named ranges in Excel

What is a named range?

A named range is just a human-readable name for a range of cells in Excel. For example, if I name the range A1:A100 «data», I can use MAX to get the maximum value with a simple formula:

 =MAX(data) // max value

Simple named range called "data"

The beauty of named ranges is that you can use meaningful names in your formulas without thinking about cell references. Once you have a named range, just use it just like a cell reference. All of these formulas are valid with the named range «data»:

=MAX(data) // max value
=MIN(data) // min value
=COUNT(data) // total values
=AVERAGE(data) // min value

Video: How to create a named range

Creating a named range is easy

Creating a named range is fast and easy. Just select a range of cells, and type a name into the name box. When you press return, the name is created:

Create a named range fast with name box

To quickly test the new range, choose the new name in the dropdown next to the name box. Excel will select the range on the worksheet.

Excel can create names automatically (ctrl + shift + F3)

If you have well structured data with labels, you can have Excel create named ranges for you. Just select the data, along with the labels, and use the «Create from Selection» command on the Formulas tab of the ribbon:

Create names from selection command on ribbon

You can also use the keyboard shortcut control + shift + F3.

Using this feature, we can create named ranges for the population of 12 states in one step:

Create names from selection with data and labels selected

When you click OK, the names are created. You’ll find all newly created names in the drop down menu next to the name box:

New names also appear in the name box drop down menu

With names created, you can use them in formulas like this

=SUM(MN,WI,MI)

Update named ranges in the Name Manager (Control + F3)

Once you create a named range, use the Name Manager (Control + F3) to update as needed. Select the name you want to work with, then change the reference directly (i.e. edit «refers to»), or click the button at right and select a new range.

Updated named ranges with the Name Manager

There’s no need to click the Edit button to update a reference. When you click Close, the range name will be updated.

Note: if you select an entire named range on a worksheet, you can drag to a new location and the reference will be updated automatically. However, I don’t know a way to adjust range references by clicking and dragging directly on the worksheet. If you know a way to do this, chime in below!

See all named ranges (control + F3)

To quickly see all named ranges in a workbook, use the dropdown menu next to the name box.

If you want to see more detail, open the Name Manager (Control + F3), which lists all names with references, and provides a filter as well:

The name manager shows all newly created names

Note: in older versions of Excel on the Mac, there is no Name Manager, and you’ll see the Define Name dialog instead.

Copy and paste all named ranges (F3)

If you want a more persistent record of named ranges in a workbook, you can paste the full list of names anywhere you like. Go to Formulas > Use in Formula (or use the shortcut F3), then choose Paste names > Paste List:

Paste names dialog box

When you click the Paste List button, you’ll see the names and references pasted into the worksheet:

After pasting named ranges into worksheet

See names directly on the worksheet

If you set the zoom level to less than 40%, Excel will show range names directly on the worksheet:

At zoom level <40%, Excel will show range names

Thanks for this tip, Felipe!

Names have rules

When creating named ranges, follow these rules:

  1. Names must begin with a letter, an underscore (_), or a backslash ()
  2. Names can’t contain spaces and most punctuation characters.
  3. Names can’t conflict with cell references – you can’t name a range «A1» or «Z100».
  4. Single letters are OK for names («a», «b», «x», etc.), but the letters «r» and «c» are reserved.
  5. Names are not case-sensitive – «home», «HOME», and «HoMe» are all the same to Excel.

Named ranges in formulas

Named ranges are easy to use in formulas

For example, lets say you name a cell in your workbook «updated». The idea is you can put the current date in the cell (Ctrl + ;) and refer to the date elsewhere in the workbook.

Using a named range inside a text formula

The formula in B8 looks like this:

="Updated: "& TEXT(updated, "ddd, mmmm d, yyyy")

You can paste this formula anywhere in the workbook and it will display correctly. Whenever you change the date in «updated», the message will update wherever the formula is used. See this page for more examples.

Named ranges appear when typing a formula

Once you’ve created a named range, it will appear automatically in formulas when you type the first letter of the name. Press the tab key to enter the name when you have a match and want Excel to enter the name.

Named ranges appear when entering formulas

Named ranges can work like constants

Because named ranges are created in a central location, you can use them like constants without a cell reference. For example, you can create names like «MPG» (miles per gallon) and «CPG» (cost per gallon) with and assign fixed values:

Named ranges can work like constants, with no cell reference

Then you can use these names anywhere you like in formulas, and update their value in one central location.

Using a named range like a constant in a formula

Named ranges are absolute by default

By default, named ranges behave like absolute references. For example, in this worksheet, the formula to calculate fuel would be:

=C5/$D$2

Standard formula with absolute address

The reference to D2 is absolute (locked) so the formula can be copied down without D2 changing.

If we name D2 «MPG» the formula becomes:

=C5/MPG

Using a named range like a constant in a formula

Since MPG is absolute by default, the formula can be copied down column D as-is.

Named ranges can also be relative

Although named ranges are absolute by default, they can also be relative.  A relative named range refers to a range that is relative to the position of the active cell at the time the range is created. As a result, relative named ranges are useful building generic formulas that work wherever they are moved.

For example, you can create a generic «CellAbove» named range like this:

  1. Select cell A2
  2. Control + F3 to open Name Manager
  3. Tab into ‘Refers to’ section, then type: =A1

CellAbove will now retrieve the value from the cell above wherever it is it used.

Important: make sure the active cell is at the correct location before creating the name.

Apply named ranges to existing formulas

If you have existing formulas that don’t use named ranges, you can ask Excel to apply the named ranges in the formulas for you. Start by selecting the cells that contain formulas you want to update. Then run Formulas > Define Names > Apply Names.

The Apply Names dialog box

Excel will then replace references that have a corresponding named range with the name itself.

You can also apply names with find and replace:

Applying names ranges with find and replace

Important: Save a backup of your worksheet, and select just the cells you want to change before using find and replace on formulas.

Key benefits of named ranges

Named ranges make formulas easier to read

The biggest single benefit to named ranges is they make formulas easier to read and maintain. This is because they replace cryptic references with meaningful names. For example, consider this worksheet with data on planets in our solar system.  Without named ranges, a VLOOKUP formula to fetch «Position» from the table is quite cryptic:

=VLOOKUP($H$4,$B$3:$E$11,2,0)

Without named ranges formulas can be cryptic

However, with B3:E11 named «data», and H4 named «planet», we can write formulas like this:

=VLOOKUP(planet,data,2,0) // position
=VLOOKUP(planet,data,3,0) // diameter
=VLOOKUP(planet,data,4,0) // satellites

With named ranges, formulas can be simple

At a glance, you can see the only difference in these formulas in the column index.

Named ranges make formulas portable and reusable

Named ranges can make it much easier to reuse a formula in a different worksheet. If you define names ahead of time in a worksheet, you can paste in a formula that uses these names and it will «just work». This is a great way to quickly get a formula working.

For example, this formula counts unique values in a range of numeric data:

=SUM(--(FREQUENCY(data,data)>0))

To quickly «port» this formula to your own worksheet, name a range «data» and paste the formula into the worksheet. As long as «data» contains numeric values, the formula will work straightway.

Tip: I recommend that you create the needed range names *first* in the destination workbook, then copy in the formula as text only (i.e. don’t copy the cell that contains the formula in another worksheet, just copy the text of the formula). This stops Excel from creating names on-the-fly and lets you to fully control the name creation process. To copy only formula text, copy text from the formula bar, or copy via another application (i.e. browser, text editor, etc.).

Named ranges can be used for navigation

Named ranges are great for quick navigation. Just select the dropdown menu next to the name box, and choose a name. When you release the mouse, the range will be selected. When a named range exists on another sheet, you’ll be taken to that sheet automatically.

Named ranges allow for simple navigation

Named ranges work well with hyperlinks

Named ranges make hyperlinks easy. For example, if you name A1 in Sheet1 «home», you can create a hyperlink somewhere else that takes you back there.

Creating a hyperlink to a named range

Example of named range hyperlink on the worksheet

To use a named range inside the HYPERLINK function, add a hash (#) in front of the named range:

=HYPERLINK("#home","take me home")

You can use this same syntax to create a hyperlink to a table:

=HYPERLINK("#Table1","Go to Table1")

Note: in older versions of Excel you can’t link to a table like this. However, you can define a name equal to a table (i.e. =Table1) and hyperlink to that.

Named ranges for data validation

Names ranges work well for data validation, since they let you use a logically named reference to validate input with a drop down menu. Below, the range G4:G8 is named «statuslist», then apply data validation with a List linked like this:

Using a named range for data validation with list

The result is a dropdown menu in column E that only allows values in the named range:

Data validation with named range example

Dynamic Named Ranges

Names ranges are extremely useful when they automatically adjust to new data in a worksheet. A range set up this way is referred to as a «dynamic named range». There are two ways to make a range dynamic: formulas and tables.

Dynamic named range with a Table

A Table is the easiest way to create a dynamic named range. Select any cell in the data, then use the shortcut Control + T:

Creating am Excel Table

When you create an Excel Table, a name is automatically created (e.g. Table1), but you can rename the table as you like. Once you have created a table, it will expand automatically when data is added.

Tables will expand automatically and can be renamed

Dynamic named range with a formula

You can also create a dynamic named range with formulas, using functions like OFFSET and INDEX. Although these formulas are moderately complex, they provide a lightweight solution when you don’t want to use a table. The links below provide examples with full explanations:

  • Example of dynamic range formula with INDEX
  • Example of dynamic range formula with OFFSET

Table names in data validation

Since Excel Tables provide an automatic dynamic range, they would seem to be a natural fit for data validation rules, where the goal is to validate against a list that may be always changing. However, one problem with tables is that you can’t use structured references directly to create data validation or conditional formatting rules. In other words, you can’t use a table name in conditional formatting or data validation input areas.

However, as a workaround, you can define named a named range that points to a table, and then use the named range for data validation or conditional formatting. The video below runs through this approach in detail.

Video: How to use named ranges with tables

Deleting named ranges

Note: If you have formulas that refer to named ranges, you may want to update the formulas first before removing names. Otherwise, you’ll see #NAME? errors in formulas that still refer to deleted names. Always save your worksheet before removing named ranges in case you have problems and need to revert to the original.

Named ranges adjust when deleting and inserting cells 

When you delete *part* of a named range, or if  insert cells/rows/columns inside a named range, the range reference will adjust accordingly and remain valid. However, if you delete all of the cells that enclose a named range, the named range will lose the reference and display a #REF error. For example, if I name A1 «test», then delete column A, the name manager will show «refers to» as:

=Sheet1!#REF!

Delete names with Name Manager

To remove named ranges from a workbook manually, open the name manager, select a range, and click the Delete button. If you want to remove more than one name at the same time, you can Shift + Click or Ctrl + Click to select multiple names, then delete in one step.

Delete names with errors

If you have a lot of names with reference errors, you can use the filter button in the name manager to filter on names with errors:

Name Manager filter menu

Then shift+click to select all names and delete.

Named ranges and Scope

Named ranges in Excel have something called «scope», which determines whether a named range is local to a given worksheet, or global across the entire workbook. Global names have a scope of «workbook», and local names have a scope equal to the sheet name they exist on. For example, the scope for a local name might be «Sheet2». 

The purpose of scope

Named ranges with a global scope are useful when you want all sheets in a workbook to have access to certain data, variables, or constants. For example, you might use a global named range a tax rate assumption used in several worksheets.

Local scope

Local scope means a name is works only on the sheet it was created on. This means you can have multiple worksheets in the same workbook that all use the same name. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. This might allow you to reuse the same formulas in different sheets. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.

To refer to a name with a local scope, you can prefix the sheet name to the range name:

Sheet1!total_revenue
Sheet2!total_revenue
Sheet3!total_revenue

Range names created with the name box automatically have global scope. To override this behavior, add the sheet name when defining the name:

Sheet3!my_new_name

Global scope

Global scope means a name will work anywhere in a workbook. For example, you could name a cell «last_update», enter a date in the cell. Then you can use the formula below to display the date last updated in any worksheet.

=last_update

Global names must be unique within a workbook.

Local scope

Locally scoped named ranges make sense for worksheets that use named ranges for local assumptions only. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.

Managing named range scope

By default, new names created with the namebox are global, and you can’t edit the scope of a named range after it’s created. However, as a workaround, you can delete and recreate a name with the desired scope.

If you want to change several names at once from global to local, sometimes it makes sense to copy the sheet that contains the names. When you duplicate a worksheet that contains named ranges, Excel copies the named ranges to the second sheet, changing the scope to local at the same time. After you have the second sheet with locally scoped names, you can optionally delete the first sheet.

Jan Karel Pieterse and Charles Williams have developed a utility called the Name Manager that provides many useful operations for named ranges. You can download the Name Manager utility here.

Понравилась статья? Поделить с друзьями:
  • Named ranges excel как
  • Named range in word
  • Name yourself in one word
  • Name word search puzzles
  • Name word meaning dictionary