Excel index of all sheets

Create an Index of Sheets

We all deal with multiple sheets in a single workbook, don’t we? Here is a smart way to create an Index of all your Sheets. You can click on the sheet name to navigate to that sheet.

Here is how we do it

Assume that we have 5 Sheets

Create an Index of Sheets 1

And we would like to have an Index placed (in a new sheet) with the sheet names hyperlinked to the respective sheet.

It can be done with a simple VBA Code

Here comes a Code

Sub CreateIndex()
Dim sheetnum As Integer
Sheets.Add before:=Sheets(1)
For sheetnum = 2 To Worksheets.Count
 ActiveSheet.Hyperlinks.Add _
 Anchor:=Cells(sheetnum - 1, 1), _
 Address:='', _
 SubAddress:=''' & Worksheets(sheetnum).Name & ''!A1', _
 TextToDisplay:=Worksheets(sheetnum).Name
Next sheetnum
ActiveWindow.DisplayGridlines = False
End Sub

Follow the steps

  1. Copy this Code
  2. Open the excel workbook where you want to create a Sheet Index
  3. Press the shortcut Alt + F11 to open the Visual Basic Window
  4. In the Insert Menu, click on Module or use the shortcut Alt i m to add a Module. Module is the place where the code is written
  5. In the blank module paste the code and close the Visual Basic Editor
  6. Then use the shortcut Alt + F8 to open the Macro Box. You would have the list of all the macros here
  7. You would see the Macro that you have just pasted in the Module as ‘CreateIndex’
  8. Run it. You would see an Index with all the sheet names hyperlinked to the respective sheet.

Create an Index of Sheets 2

Other Useful Macros

  1. Automated Filter with Macro
  2. Unhiding Multiple Sheets at Once
  3. Covert Numbers into Indian Currency Words

Topics that I write about…


goodly


Содержание

  1. Create an Index of Sheets in Your Workbook
  2. INDEX function
  3. Array form
  4. Description
  5. Syntax
  6. Remarks
  7. Examples
  8. Example 1
  9. Example 2
  10. Reference form
  11. Description
  12. Syntax
  13. Remarks
  14. Examples
  15. Функция INDEX (ИНДЕКС) в Excel. Как использовать?
  16. Что возвращает функция
  17. Синтаксис
  18. Аргументы функции
  19. Дополнительная информация
  20. Примеры использования функции ИНДЕКС в Excel
  21. Пример 1. Ищем результаты экзамена по физике для Алексея
  22. Пример 2. Создаем динамический поиск значений с использованием функций ИНДЕКС и ПОИСКПОЗ
  23. Пример 3. Создаем динамический поиск значений с использованием функций INDEX (ИНДЕКС) и MATCH (ПОИСКПОЗ) и выпадающего списка
  24. Пример 4. Использование трехстороннего поиска с помощью INDEX (ИНДЕКС) / MATCH (ПОИСКПОЗ)

Create an Index of Sheets in Your Workbook

If you’ve spent much time in a workbook with many worksheets, you know how painful it can be to find a particular worksheet. An index sheet available to every worksheet is a navigational must-have.

Using an index sheet will enable you to quickly and easily navigate throughout your workbook so that with one click of the mouse, you will be taken exactly where you want to go, without fuss. You can create an index in a couple of ways.

You might be tempted to simply create the index by hand. Create a new worksheet, call it Index or the like, enter a list of all your worksheet’s names, and hyperlink each to the appropriate sheet by selecting Insert » Hyperlink. or by pressing Ctrl/-K. Although this method is probably sufficient for limited instances in which you don’t have too many sheets and they won’t change often, you’ll be stuck maintaining your index by hand.

The following code will automatically create a clickable, hyperlinked index of all the sheets you have in the workbook. The index is re-created each time the sheet that houses the code is activated.

This code should live in the private module for the Sheet object. Insert a new worksheet into your workbook and name it something appropriate- Index , for instance. Right-click the index sheet’s tab and select View Code from the context menu. Enter the following Visual Basic code (Tools » Macro » Visual Basic Editor or Alt/Option-F11):

Press Alt/-Q to get back to your workbook and then save your changes. Notice that the code names (such as when you name a cell or range of cells in Excel) cell A1 on each sheet Start , plus a unique whole number representing the index number of the sheet . This ensures that A1 on each sheet has a different name. If A1 on your worksheet already has a name, you should consider changing any mention of A1 in the code to something more suitable-an unused cell anywhere on the sheet, for instance.

You should be aware that if you select File » Properties » Summary and enter a URL as a hyperlink base, the index created from the preceding code possibly will not work. A hyperlink base is a path or URL that you want to use for all hyperlinks with the same base address that are inserted in the current document.

Another, more user-friendly, way of constructing an index is to add a link to the list of sheets as a context-menu item, keeping it just a right-click away. We’ll have that link open the standard workbook tabs command bar. You generally get to this command bar by right-clicking any of the sheet tab scroll arrows on the bottom left of any worksheet, as shown in figure.

Figure. Tabs command bar displayed by right-clicking the sheet scroll tabs

To link that tab’s command bar to a right-click in any cell, enter the following code in the VBE:

Next, you’ll need to insert a standard module to house the IndexCode macro, called by the preceding code whenever the user right-clicks in a cell. It is vital that you use a standard module next, as placing the code in the same module as Workbook_SheetBeforeRightClick will mean Excel will not know where to find the macro called IndexCode .

Select Insert » Module and enter the following code:

Press Alt/-Q to get back to the Excel interface.

Now, right-click within any cell on any worksheet and you should see a new menu item called Sheet Index that will take you right to a list of sheets in the workbook.

Источник

INDEX function

The INDEX function returns a value or the reference to a value from within a table or range.

There are two ways to use the INDEX function:

If you want to return the value of a specified cell or array of cells, see Array form.

If you want to return a reference to specified cells, see Reference form.

Array form

Description

Returns the value of an element in a table or an array, selected by the row and column number indexes.

Use the array form if the first argument to INDEX is an array constant.

Syntax

INDEX(array, row_num, [column_num])

The array form of the INDEX function has the following arguments:

array Required. A range of cells or an array constant.

If array contains only one row or column, the corresponding row_num or column_num argument is optional.

If array has more than one row and more than one column, and only row_num or column_num is used, INDEX returns an array of the entire row or column in array.

row_num Required, unless column_num is present. Selects the row in array from which to return a value. If row_num is omitted, column_num is required.

column_num Optional. Selects the column in array from which to return a value. If column_num is omitted, row_num is required.

If both the row_num and column_num arguments are used, INDEX returns the value in the cell at the intersection of row_num and column_num.

row_num and column_num must point to a cell within array; otherwise, INDEX returns a #REF! error.

If you set row_num or column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula.

Note: If you have a current version of Microsoft 365, then you can input the formula in the top-left-cell of the output range, then press ENTER to confirm the formula as a dynamic array formula. Otherwise, the formula must be entered as a legacy array formula by first selecting the output range, input the formula in the top-left-cell of the output range, then press CTRL+SHIFT+ENTER to confirm it. Excel inserts curly brackets at the beginning and end of the formula for you. For more information on array formulas, see Guidelines and examples of array formulas.

Examples

Example 1

These examples use the INDEX function to find the value in the intersecting cell where a row and a column meet.

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter.

Value at the intersection of the second row and second column in the range A2:B3.

Value at the intersection of the second row and first column in the range A2:B3.

Example 2

This example uses the INDEX function in an array formula to find the values in two cells specified in a 2×2 array.

Note: If you have a current version of Microsoft 365, then you can input the formula in the top-left-cell of the output range, then press ENTER to confirm the formula as a dynamic array formula. Otherwise, the formula must be entered as a legacy array formula by first selecting two blank cells, input the formula in the top-left-cell of the output range, then press CTRL+SHIFT+ENTER to confirm it. Excel inserts curly brackets at the beginning and end of the formula for you. For more information on array formulas, see Guidelines and examples of array formulas.

Value found in the first row, second column in the array. The array contains 1 and 2 in the first row and 3 and 4 in the second row.

Value found in the second row, second column in the array (same array as above).

Reference form

Description

Returns the reference of the cell at the intersection of a particular row and column. If the reference is made up of non-adjacent selections, you can pick the selection to look in.

Syntax

INDEX(reference, row_num, [column_num], [area_num])

The reference form of the INDEX function has the following arguments:

reference Required. A reference to one or more cell ranges.

If you are entering a non-adjacent range for the reference, enclose reference in parentheses.

If each area in reference contains only one row or column, the row_num or column_num argument, respectively, is optional. For example, for a single row reference, use INDEX(reference,,column_num).

row_num Required. The number of the row in reference from which to return a reference.

column_num Optional. The number of the column in reference from which to return a reference.

area_num Optional. Selects a range in reference from which to return the intersection of row_num and column_num. The first area selected or entered is numbered 1, the second is 2, and so on. If area_num is omitted, INDEX uses area 1. The areas listed here must all be located on one sheet. If you specify areas that are not on the same sheet as each other, it will cause a #VALUE! error. If you need to use ranges that are located on different sheets from each other, it is recommended that you use the array form of the INDEX function, and use another function to calculate the range that makes up the array. For example, you could use the CHOOSE function to calculate which range will be used.

For example, if Reference describes the cells (A1:B4,D1:E4,G1:H4), area_num 1 is the range A1:B4, area_num 2 is the range D1:E4, and area_num 3 is the range G1:H4.

After reference and area_num have selected a particular range, row_num and column_num select a particular cell: row_num 1 is the first row in the range, column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of row_num and column_num.

If you set row_num or column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively.

row_num, column_num, and area_num must point to a cell within reference; otherwise, INDEX returns a #REF! error. If row_num and column_num are omitted, INDEX returns the area in reference specified by area_num.

The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL(«width»,INDEX(A1:B2,1,2)) is equivalent to CELL(«width»,B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1.

Examples

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter.

Источник

Функция INDEX (ИНДЕКС) в Excel. Как использовать?

Функция INDEX (ИНДЕКС) в Excel используется для получения данных из таблицы, при условии что вы знаете номер строки и столбца, в котором эти данные находятся.

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

Что возвращает функция

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

Синтаксис

=INDEX (array, row_num, [col_num]) — английская версия

=INDEX (array, row_num, [col_num], [area_num]) — английская версия

=ИНДЕКС(массив; номер_строки; [номер_столбца]) — русская версия

=ИНДЕКС(ссылка; номер_строки; [номер_столбца]; [номер_области]) — русская версия

Аргументы функции

  • array (массив) — диапазон ячеек или массив данных для поиска;
  • row_num (номер_строки) — номер строки, в которой находятся искомые данные;
  • [col_num] ([номер_столбца])(необязательный аргумент) — номер колонки, в которой находятся искомые данные. Этот аргумент необязательный. Но если в аргументах функции не указаны критерии для row_num (номер_строки), необходимо указать аргумент col_num (номер_столбца);
  • [area_num] ([номер_области]) — (необязательный аргумент) — если аргумент массива состоит из нескольких диапазонов, то это число будет использоваться для выбора всех диапазонов.

Дополнительная информация

  • Если номер строки или колонки равен “0”, то функция возвращает данные всей строки или колонки;
  • Если функция используется перед ссылкой на ячейку (например, A1), она возвращает ссылку на ячейку вместо значения (см. примеры ниже);
  • Чаще всего INDEX (ИНДЕКС) используется совместно с функцией MATCH (ПОИСКПОЗ);
  • В отличие от функции VLOOKUP (ВПР), функция INDEX (ИНДЕКС) может возвращать данные как справа от искомого значения, так и слева;
  • Функция используется в двух формах — Массива данных и Формы ссылки на данные:

— Форма «Массива» используется когда вы хотите найти значения, основанные на конкретных номерах строк и столбцов таблицы;

— Форма «Ссылок на данные» используется при поиске значений в нескольких таблицах (используете аргумент [area_num] ([номер_области]) для выбора таблицы и только потом сориентируете функцию по номеру строки и столбца.

Примеры использования функции ИНДЕКС в Excel

Пример 1. Ищем результаты экзамена по физике для Алексея

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

Для того, чтобы найти результаты экзамена по физике для Андрея нам нужна формула:

=INDEX($B$3:$E$9,3,2) — английская версия

=ИНДЕКС($B$3:$E$9;3;2) — русская версия

В формуле мы определили аргумент диапазона данных, где мы будем искать данные $B$3:$E$9. Затем, указали номер строки “3”, в которой находятся результаты экзамена для Андрея, и номер колонки “2”, где находятся результаты экзамена именно по физике.

Пример 2. Создаем динамический поиск значений с использованием функций ИНДЕКС и ПОИСКПОЗ

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

Пример динамического отображения данных ниже:

Для динамического отображения данных мы используем комбинацию функций INDEX (ИНДЕКС) и MATCH (ПОИСКПОЗ).

Вот такая формула поможет нам добиться результата:

=INDEX($B$3:$E$9,MATCH($G$4,$A$3:$A$9,0),MATCH($H$3,$B$2:$E$2,0)) — английская версия

=ИНДЕКС($B$3:$E$9;ПОИСКПОЗ($G$4;$A$3:$A$9;0);ПОИСКПОЗ($H$3;$B$2:$E$2;0)) — русская версия

В формуле выше, не используя сложного программирования, мы с помощью функции MATCH (ПОИСКПОЗ) сделали отображение данных динамическим.

Динамический отображение строки задается следующей частью формулы —

MATCH($G$4,$A$3:$A$9,0) — английская версия

ПОИСКПОЗ($G$4;$A$3:$A$9;0) — русская версия

Она сканирует имена студентов и определяет значение поиска ($G$4 в нашем случае). Затем она возвращает номер строки для поиска в наборе данных. Например, если значение поиска равно Алексей, функция вернет “1”, если это Максим, оно вернет “4” и так далее.

Динамическое отображение данных столбца задается следующей частью формулы —

MATCH($H$3,$B$2:$E$2,0) — английская версия

ПОИСКПОЗ($H$3;$B$2:$E$2;0) — русская версия

Она сканирует имена объектов и определяет значение поиска ($H$3 в нашем случае). Затем она возвращает номер столбца для поиска в наборе данных. Например, если значение поиска Математика, функция вернет “1”, если это Физика, функция вернет “2” и так далее.

Пример 3. Создаем динамический поиск значений с использованием функций INDEX (ИНДЕКС) и MATCH (ПОИСКПОЗ) и выпадающего списка

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

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

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

Для того, чтобы осуществить динамическую подстановку данных с использованием функций INDEX (ИНДЕКС) и MATCH (ПОИСКПОЗ) и выпадающего списка, мы используем ту же формулу, что в Примере 2:

=INDEX($B$3:$E$9,MATCH($G$4,$A$3:$A$9,0),MATCH($H$3,$B$2:$E$2,0)) — английская версия

=ИНДЕКС($B$3:$E$9;ПОИСКПОЗ($G$4;$A$3:$A$9;0);ПОИСКПОЗ($H$3;$B$2:$E$2;0)) — русская версия

Единственное отличие, от Примера 2, мы на месте ввода имени и предмета создадим выпадающие списки:

  • Выбираем ячейку, в которой мы хотим отобразить выпадающий список с именами студентов;
  • Кликаем на вкладку “Data” => Data Tools => Data Validation;
  • В окне Data Validation на вкладке “Settings” в подразделе Allow выбираем “List”;
  • В качестве Source нам нужно выбрать диапазон ячеек, в котором указаны имена студентов;
  • Кликаем ОК

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

Пример 4. Использование трехстороннего поиска с помощью INDEX (ИНДЕКС) / MATCH (ПОИСКПОЗ)

Функция INDEX (ИНДЕКС) может быть использована для обработки трехсторонних запросов.

Что такое трехсторонний поиск?

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

Теперь предположим, что к концу года студент прошел три уровня экзаменов: «Вступительный», «Полугодовой» и «Итоговый экзамен».

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

Вот пример трехстороннего поиска:

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

Для таких расчетов нам поможет формула:

=INDEX(($B$3:$E$7,$B$11:$E$15,$B$19:$E$23),MATCH($G$4,$A$3:$A$7,0),MATCH($H$3,$B$2:$E$2,0),IF($H$2=»Вступительный»,1,IF($H$2=»Полугодовой»,2,3))) — английская версия

=ИНДЕКС(($B$3:$E$7;$B$11:$E$15;$B$19:$E$23);ПОИСКПОЗ($G$4;$A$3:$A$7;0);ПОИСКПОЗ($H$3;$B$2:$E$2;0); ЕСЛИ($H$2=»Вступительный»;1;ЕСЛИ($H$2=»Полугодовой»;2;3))) — русская версия

Давайте разберем эту формулу, чтобы понять, как она работает.

Эта формула принимает четыре аргумента. Функция INDEX (ИНДЕКС) — одна из тех функций в Excel, которая имеет более одного синтаксиса.

=INDEX (array, row_num, [col_num]) — английская версия

=INDEX (array, row_num, [col_num], [area_num]) — английская версия

=ИНДЕКС(массив; номер_строки; [номер_столбца]) — русская версия

=ИНДЕКС(ссылка; номер_строки; [номер_столбца]; [номер_области]) — русская версия

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

Рассмотрим каждую часть формулы на основе второго синтаксиса.

  • array(массив) – ($B$3:$E$7,$B$11:$E$15,$B$19:$E$23):Вместо использования одного массива, в данном случае мы использовали три массива в круглых скобках.
  • row_num (номер_строки) – MATCH($G$4,$A$3:$A$7,0): функция MATCH (ПОИСКПОЗ) используется для поиска имени студента для ячейки $G$4 из списка всех студентов.
  • col_num (номер_столбца) – MATCH($H$3,$B$2:$E$2,0): функция MATCH (ПОИСКПОЗ) используется для поиска названия предмета для ячейки $H$3 из списка всех предметов.
  • [area_num] ([номер_области]) – IF($H$2=”Вступительный”,1,IF($H$2=”Полугодовой”,2,3)): Значение номера области сообщает функции INDEX (ИНДЕКС) , какой массив с данными выбрать. В этом примере у нас есть три массива в первом аргументе. Если вы выберете «Вступительный» из раскрывающегося меню, функция IF (ЕСЛИ) вернет значение “1”, а функция INDEX (ИНДЕКС) выберут 1-й массив из трех массивов ($B$3:$E$7).

Уверен, что теперь вы подробно изучили работу функции INDEX (ИНДЕКС) в Excel!

Источник

Summary

To list the index numbers of sheets in an Excel workbook, you can enter the sheet names, then use a formula based on the SHEET and INDIRECT functions. In the example shown, the formula in C5 is:

=SHEET(INDIRECT(B5&"!A1"))

Generic formula

=SHEET(INDIRECT(name&"!A1"))

Explanation 

The INDIRECT function tries to evaluate text as a valid reference. In this case, the sheet name is pulled from column B and concatenated with an exclamation point and the text A1:

=B5&"!A1"
="Sheet1"&"!A1"
="Sheet1!A1"

The INDIRECT function then coerces the text «Sheet1!A1» into a valid reference, which is passed into the SHEET function.

The SHEET function then returns the current index for each sheet as listed.

Dave Bruns Profile Picture

AuthorMicrosoft Most Valuable Professional Award

Dave Bruns

Hi — I’m Dave Bruns, and I run Exceljet with my wife, Lisa. Our goal is to help you work faster in Excel. We create short videos, and clear examples of formulas, functions, pivot tables, conditional formatting, and charts.

Related Information

There are hundreds and hundreds of Excel sites out there. I’ve been to many and most are an exercise in frustration. Found yours today and wanted to let you know that it might be the simplest and easiest site that will get me where I want to go.

Get Training

Quick, clean, and to the point training

Learn Excel with high quality video training. Our videos are quick, clean, and to the point, so you can learn Excel in less time, and easily review key topics when needed. Each video comes with its own practice worksheet.

View Paid Training & Bundles

Help us improve Exceljet

If you’ve spent much time in a workbook with many worksheets, you know how painful it can be to find a particular worksheet. An index sheet available to every worksheet is a navigational must-have.

Using an index sheet will enable you to quickly and easily navigate throughout your workbook so that with one click of the mouse, you will be taken exactly where you want to go, without fuss. You can create an index in a couple of ways.

You might be tempted to simply create the index by hand. Create a new worksheet, call it Index or the like, enter a list of all your worksheet’s names, and hyperlink each to the appropriate sheet by selecting Insert » Hyperlink… or by pressing Ctrl/figs/command.gif-K. Although this method is probably sufficient for limited instances in which you don’t have too many sheets and they won’t change often, you’ll be stuck maintaining your index by hand.

The following code will automatically create a clickable, hyperlinked index of all the sheets you have in the workbook. The index is re-created each time the sheet that houses the code is activated.

This code should live in the private module for the Sheet object. Insert a new worksheet into your workbook and name it something appropriate-Index, for instance. Right-click the index sheet’s tab and select View Code from the context menu. Enter the following Visual Basic code (Tools » Macro » Visual Basic Editor or Alt/Option-F11):

Private Sub Worksheet_Activate( )
Dim wSheet As Worksheet
Dim l As Long
l = 1
    With Me
        .Columns(1).ClearContents
        .Cells(1, 1) = "INDEX"
        .Cells(1, 1).Name = "Index"
    End With
    For Each wSheet In Worksheets
     If wSheet.Name <> Me.Name Then
      l = l + 1
      With wSheet
          .Range("A1").Name = "Start" & wSheet.Index
          .Hyperlinks.Add Anchor:=.Range("A1"), Address:="", SubAddress:= _
            "Index", TextToDisplay:="Back to Index"
      End With
         Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="",_
            SubAddress:="Start" & wSheet.Index, TextToDisplay:=wSheet.Name
     End If
    Next wSheet
End Sub

Press Alt/figs/command.gif-Q to get back to your workbook and then save your changes. Notice that the code names (such as when you name a cell or range of cells in Excel) cell A1 on each sheet Start, plus a unique whole number representing the index number of the sheet . This ensures that A1 on each sheet has a different name. If A1 on your worksheet already has a name, you should consider changing any mention of A1 in the code to something more suitable-an unused cell anywhere on the sheet, for instance.

You should be aware that if you select File » Properties » Summary and enter a URL as a hyperlink base, the index created from the preceding code possibly will not work. A hyperlink base is a path or URL that you want to use for all hyperlinks with the same base address that are inserted in the current document.

Another, more user-friendly, way of constructing an index is to add a link to the list of sheets as a context-menu item, keeping it just a right-click away. We’ll have that link open the standard workbook tabs command bar. You generally get to this command bar by right-clicking any of the sheet tab scroll arrows on the bottom left of any worksheet, as shown in figure.

Figure. Tabs command bar displayed by right-clicking the sheet scroll tabs

figs/exhk_0111.gif

To link that tab’s command bar to a right-click in any cell, enter the following code in the VBE:

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target
As Range, Cancel As Boolean)
Dim cCont As CommandBarButton
    On Error Resume Next
    Application.CommandBars("Cell").Controls("Sheet Index").Delete
    On Error GoTo 0
        Set cCont = Application.CommandBars("Cell").Controls.Add _
                        (Type:=msoControlButton, Temporary:=True)
        With cCont
                  .Caption = "Sheet Index"
             .OnAction = "IndexCode"
            End With
End Sub

Next, you’ll need to insert a standard module to house the IndexCode macro, called by the preceding code whenever the user right-clicks in a cell. It is vital that you use a standard module next, as placing the code in the same module as Workbook_SheetBeforeRightClick will mean Excel will not know where to find the macro called IndexCode.

Select Insert » Module and enter the following code:

Sub IndexCode( )
 Application.CommandBars("workbook Tabs").ShowPopup
End Sub

Press Alt/figs/command.gif-Q to get back to the Excel interface.

Now, right-click within any cell on any worksheet and you should see a new menu item called Sheet Index that will take you right to a list of sheets in the workbook.

by updated Aug 01, 2016

Is there a way to find the names of all the sheets as a list?

I can find the sheet name of the sheet where the formula is placed in via the following formula:

=RIGHT(CELL("filename";A1);LEN(CELL("filename";A1))-SEARCH("]";CELL("filename";A1);1))

This works for the sheet the formula is placed in. How can I get a list of all the sheets that are in a file on one sheet (let’s say in cell A1:A5 if I have 5 sheets)?

I would like to make it so when someone changes a sheet name the macro keeps working.

Community's user avatar

asked Dec 10, 2018 at 9:18

Mischa Urlings's user avatar

btw, in vba you can refer to worksheets by name or by object. See below, if you use the first method of referencing your worksheets it will always work with any name.
enter image description here

answered Dec 10, 2018 at 9:51

SNicolaou's user avatar

SNicolaouSNicolaou

5501 gold badge3 silver badges15 bronze badges

2

I would keep a very hidden sheet with the formula you used referencing each sheet.

When the Workbook_NewSheet event fires a formula pointing to the new sheet is created:

  • Create a sheet and give it the Code Name of shtNames.
    • Give the sheet a tab name of SheetNames.
    • In cell A1 of shtNames add a heading (I just used «Sheet List»).
    • In Properties for the sheet change Visible to 2 — xlSheetVeryHidden.
      You can only do this if there at least one visible sheet left.
  • Add this code to the ThisWorkbook module:

Private Sub Workbook_NewSheet(ByVal Sh As Object)

    With shtNames
        .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Formula = _
            "=RIGHT(CELL(""filename"",'" & Sh.Name & "'!$A$1), " & _
            "LEN(CELL(""filename"",'" & Sh.Name & "'!$A$1))-" & _
            "FIND(""]"",CELL(""filename"",'" & Sh.Name & "'!$A$1),1))"
    End With

End Sub  

Create a named range in the Name Manager:

  • I called it SheetList.
  • Use this formula:
    =SheetNames!$A$2:INDEX(SheetNames!$A:$A,COUNTA(SheetNames!$A:$A))

You can then use SheetList as the source for Data Validation lists and list controls.

Two potential problems I haven’t looked at yet are rearranging the sheets and deleting the sheets.

so when someone changes a sheetname the macro keeps working

As @SNicolaou said though — use the sheet code name which the user can’t change and your code will carry on working no matter the sheet tab name.

answered Dec 10, 2018 at 10:43

Darren Bartrup-Cook's user avatar

@Mischa Urlings with the below code you get as a message in message box the following:

  1. Sheet Name
  2. Sheet Position

    Option Explicit
    
    Sub test()
    
    Dim ws As Worksheet
    Dim str As String
    
    For Each ws In ThisWorkbook.Worksheets
        str = str & vbNewLine & "Sheet named " & ws.Name & " located in position " & ws.Index & "."
    Next
    
    'Get the names in a list in message box
    MsgBox str
    
    End Sub
    

answered Dec 10, 2018 at 10:19

Error 1004's user avatar

Error 1004Error 1004

7,8253 gold badges21 silver badges46 bronze badges

a VBA function like:

Function SheetName(ByVal Index As Long, Optional ByVal Book as Range) as String
    Application.Volatile
    If Book Is Nothing Then Set Book = Application.Caller
    SheetName=Book.Worksheet.Parent.Sheets(Index).Name
End Function

would return sheet names by index, like an Excel formula. Example:

=SheetName(1) 'returns "Sheet1"
=SheetName(3) 'returns "Sheet3"

Using optional range in another book, you can get other book sheet names:

=SheetName(1, [Some other book.xls]Sheet1!A1) 'returns "Sheet1"
=SheetName(2, [Some other book.xls]Sheet1!A1) 'returns "Sheet2"

answered Dec 10, 2018 at 9:32

LS_ᴅᴇᴠ's user avatar

LS_ᴅᴇᴠLS_ᴅᴇᴠ

10.8k1 gold badge22 silver badges46 bronze badges

3

Make a defined name(formulas, name manager) : named: YourSheetNames
in the field refersto you place:

=IF(NOW()>0,REPLACE(GET.WORKBOOK(1),1;FIND("]",GET.WORKBOOK(1)),""))

In your sheet you place in A1:A5:

=INDEX(YourSheetNames,ROW())

this wil give you (as long as calculation is set to xlautomatic) an actual list

answered Dec 10, 2018 at 9:28

EvR's user avatar

EvREvR

3,3882 gold badges12 silver badges23 bronze badges

2

The following VBA macro function returns all worksheets names as an array:

Function GetWorksheets() As Variant
    
    Dim ws As Worksheet
    Dim x As Integer
    Dim WSArray As Variant
    ReDim WSArray(1 To Worksheets.Count)

    x = 1
    For Each ws In Worksheets
        'Sheets("Sheet1").Cells(x, 1) = ws.Name
        WSArray(x) = ws.Name
        x = x + 1
    Next ws
    
    'Output Array
    GetWorksheets = WSArray
End Function

After added to VBA Module, you can call it anywhere in a Workbook the same way you call a regular Excel Formula.

enter image description here
enter image description here

This VBA Function can be used as a more secure alternative to the following Excel 4.0 (XLM) macro:

=REPLACE(GET.WORKBOOK(1);1;FIND("]";GET.WORKBOOK(1));"")

answered Dec 8, 2022 at 6:03

Néstor Waldyd's user avatar


Download Article


Download Article

If your Excel workbook contains numerous worksheets, you can add a table of contents that indexes all of your sheets with clickable hyperlinks. This tutorial will teach you how to make an index of sheet names with page numbers in your Excel workbook without complicated VBA scripting, and how to add helpful «back to index» buttons to each sheet to improve navigation.

  1. Image titled Create an Index in Excel Step 1

    1

    Create an index sheet in your workbook. This sheet can be anywhere in your workbook, but you’ll usually want to place the tab at the beginning like a traditional table of contents.

    • To create a new sheet, click the + at the bottom of the active worksheet. Then, right-click the new tab, select Rename, and type a name for your sheet like Index or Worksheets.
    • You can rearrange sheets by dragging their tabs left or right at the bottom of your workbook.
  2. Image titled Create an Index in Excel Step 2

    2

    Type Page Number into cell A1 of your index sheet. Column A is where you’ll be placing the page numbers for each sheet.

    Advertisement

  3. Image titled Create an Index in Excel Step 3

    3

    Type Sheet Name into cell B1 of your index sheet. This will be the column header above your list of worksheets.

  4. Image titled Create an Index in Excel Step 4

    4

    Type Link into cell C1 of your index sheet. This is the column header that will appear above hyperlinks to each worksheet.

  5. Image titled Create an Index in Excel Step 5

    5

    Click the Formulas tab. It’s at the top of Excel.

  6. Image titled Create an Index in Excel Step 6

    6

    Click Define Name. It’s on the «Defined Names» tab at the top of Excel.

  7. Image titled Create an Index in Excel Step 7

    7

    Type SheetList into the «Name» field. This names the formula you’ll be using with the INDEX function.[1]

  8. Image titled Create an Index in Excel Step 8

    8

    Type the formula into the «Refers to» field and click OK. The formula is =REPLACE(GET.WORKBOOK(1),1,FIND("]",GET.WORKBOOK(1)),"").

  9. Image titled Create an Index in Excel Step 9

    9

    Enter page numbers in column A. This is the only part you’ll have to do manually. For example, if your workbook has 20 pages, you’ll type 1 into A2, 2 into A3, etc., and continue numbering down until you’ve entered all 20 page numbers.

    • To quickly populate the page numbers, type the first two page numbers into A2 and A3, click A3 to select it, and then drag the square at A3’s bottom-right corner down until you’ve reached the number of pages in your workbook. Then, click the small icon with a + that appears at the bottom-right corner of the column and select Fill Series.
  10. Image titled Create an Index in Excel Step 10

    10

    Type this formula into cell B2 of your index sheet. The formula is =INDEX(SheetList,A2). When you press Enter or Return, you’ll see the name of the first sheet in your workbook.

  11. Image titled Create an Index in Excel Step 11

    11

    Fill the rest of column B with the formula. To do this, just click B2 to select it, and then double-click the square at its bottom-right corner. This adds the name of each worksheet corresponding to the page numbers you typed into column A.

  12. Image titled Create an Index in Excel Step 12

    12

    Type this formula into C2 of your worksheet. The formula is =HYPERLINK("#'"&B2&"'!A1","Go to Sheet"). When you press Enter or Return, you’ll see a hyperlink to the first page in your index called «Go to Sheet.»

  13. Image titled Create an Index in Excel Step 13

    13

    Fill the rest of column C with the formula. To do this, click C2 to select it, and then double-click the square at its bottom-right corner. Now each sheet in your workbook has a clickable hyperlink that takes you right to that page.

  14. Image titled Create an Index in Excel Step 14

    14

    Save your workbook in the macro-enabled format. Because you created a named range, you’ll need to save your workbook in this format.[2]
    Here’s how:

    • Go to File > Save.
    • On the pop-up message that warns you about saving a macro-free workbook, click No.
    • In the «Save as type» or file format menu, select Excel Macro-Enabled Workbook (*.xlsm) and click Save.
  15. Advertisement

  1. Image titled Create an Index in Excel Step 15

    1

    Click your index or table of contents sheet. If you have a lot of pages in your workbook, it’ll be helpful to readers to add quick «Back to Index» or «Back to Table of Contents» links to each sheet so they don’t have to scroll through lots of worksheet tabs after clicking to that page. Start by opening your index sheet.

  2. Image titled Create an Index in Excel Step 16

    2

    Name the index. To do this, just click the field directly above cell A1, type Index, and then press Enter or Return.

    • Don’t worry if the field already contains a cell address.
  3. Image titled Create an Index in Excel Step 17

    3

    Click any of the sheets in your workbook. Now you’ll create your back button. Once you create a back button on one sheet, you can just copy and paste it onto other sheets.

  4. Image titled Create an Index in Excel Step 18

    4

    Click the Insert tab. It’s at the top of the screen.

  5. Image titled Create an Index in Excel Step 19

    5

    Click the Illustrations menu and select Shapes. This option will be in the upper-left area of Excel.

  6. Image titled Create an Index in Excel Step 20

    6

    Click a shape for your button. For example, if you want to create a back-arrow icon sort of like your web browser’s back button, you can click the left-pointing arrow under the «Block Arrows» header.

  7. Image titled Create an Index in Excel Step 21

    7

    Click the location where you want to place the button. Once you click, the shape will appear. If you want, you can change the color and look using the options at the top, and/or resize the shape by dragging any of its corners.

  8. Image titled Create an Index in Excel Step 22

    8

    Type some text onto the shape. The text you type should be something like «Back to Index.» You can double-click the shape to place the cursor and start typing right onto the actual shape

    • You might need to drag the corner of the shape to resize it so the text fits.
    • To place a text box on or near the shape before typing, just click the Shape Format menu at the top (while the shape is selected), click Text Box in the toolbar, and then click and drag a text box.
    • You can stylize the text using the options in Text on the toolbar while the shape is selected.
  9. Image titled Create an Index in Excel Step 23

    9

    Right-click the shape and select Link. This opens the Insert Hyperlink dialog.[3]

  10. Image titled Create an Index in Excel Step 24

    10

    Click the Place in This Document icon. It’s in the left panel.

  11. Image titled Create an Index in Excel Step 25

    11

    Select your index under «Defined Names» and click OK. You might have to click the + next to the column header to see the Index option. This makes the text in the shape a clickable hyperlink that takes you right to the index.

  12. Image titled Create an Index in Excel Step 26

    12

    Copy and paste the hyperlink to other sheets. To do this, just right-click the shape and select Copy. Then, you can paste it onto any other page by right-clicking the desired location and selecting the first icon under «Paste Options» (the one that says «Use Destination Theme» when you hover the mouse over it).

  13. Advertisement

Ask a Question

200 characters left

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

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Article SummaryX

To create a table of contents in Excel, you can use the «Defined Name» option to create a formula that indexes all sheet names on a single page. Then, you can use the INDEX function to list the sheet names, as well as the HYPERLINK function to create quick links to each sheet.

Did this summary help you?

Thanks to all authors for creating a page that has been read 55,649 times.

Is this article up to date?

Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

The INDEX function returns a value or the reference to a value from within a table or range.

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

There are two ways to use the INDEX function:

  • If you want to return the value of a specified cell or array of cells, see Array form.

  • If you want to return a reference to specified cells, see Reference form.

Array form

Description

Returns the value of an element in a table or an array, selected by the row and column number indexes.

Use the array form if the first argument to INDEX is an array constant.

Syntax

INDEX(array, row_num, [column_num])

The array form of the INDEX function has the following arguments:

  • array    Required. A range of cells or an array constant.

    • If array contains only one row or column, the corresponding row_num or column_num argument is optional.

    • If array has more than one row and more than one column, and only row_num or column_num is used, INDEX returns an array of the entire row or column in array.

  • row_num    Required, unless column_num is present. Selects the row in array from which to return a value. If row_num is omitted, column_num is required.

  • column_num    Optional. Selects the column in array from which to return a value. If column_num is omitted, row_num is required.

Remarks

  • If both the row_num and column_num arguments are used, INDEX returns the value in the cell at the intersection of row_num and column_num.

  • row_num and column_num must point to a cell within array; otherwise, INDEX returns a #REF! error.

  • If you set row_num or column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula.

    Note: If you have a current version of Microsoft 365, then you can input the formula in the top-left-cell of the output range, then press ENTER to confirm the formula as a dynamic array formula. Otherwise, the formula must be entered as a legacy array formula by first selecting the output range, input the formula in the top-left-cell of the output range, then press CTRL+SHIFT+ENTER to confirm it. Excel inserts curly brackets at the beginning and end of the formula for you. For more information on array formulas, see Guidelines and examples of array formulas.

Examples

Example 1

These examples use the INDEX function to find the value in the intersecting cell where a row and a column meet.

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter.

Data

Data

Apples

Lemons

Bananas

Pears

Formula

Description

Result

=INDEX(A2:B3,2,2)

Value at the intersection of the second row and second column in the range A2:B3.

Pears

=INDEX(A2:B3,2,1)

Value at the intersection of the second row and first column in the range A2:B3.

Bananas

Example 2

This example uses the INDEX function in an array formula to find the values in two cells specified in a 2×2 array.  

Note: If you have a current version of Microsoft 365, then you can input the formula in the top-left-cell of the output range, then press ENTER to confirm the formula as a dynamic array formula. Otherwise, the formula must be entered as a legacy array formula by first selecting two blank cells, input the formula in the top-left-cell of the output range, then press CTRL+SHIFT+ENTER to confirm it. Excel inserts curly brackets at the beginning and end of the formula for you. For more information on array formulas, see Guidelines and examples of array formulas.

Formula

Description

Result

=INDEX({1,2;3,4},0,2)

Value found in the first row, second column in the array. The array contains 1 and 2 in the first row and 3 and 4 in the second row.

2

Value found in the second row, second column in the array (same array as above).

4

Top of Page


Reference form

Description

Returns the reference of the cell at the intersection of a particular row and column. If the reference is made up of non-adjacent selections, you can pick the selection to look in.

Syntax

INDEX(reference, row_num, [column_num], [area_num])

The reference form of the INDEX function has the following arguments:

  • reference    Required. A reference to one or more cell ranges.

    • If you are entering a non-adjacent range for the reference, enclose reference in parentheses.

    • If each area in reference contains only one row or column, the row_num or column_num argument, respectively, is optional. For example, for a single row reference, use INDEX(reference,,column_num).

  • row_num    Required. The number of the row in reference from which to return a reference.

  • column_num    Optional. The number of the column in reference from which to return a reference.

  • area_num    Optional. Selects a range in reference from which to return the intersection of row_num and column_num. The first area selected or entered is numbered 1, the second is 2, and so on. If area_num is omitted, INDEX uses area 1.  The areas listed here must all be located on one sheet.  If you specify areas that are not on the same sheet as each other, it will cause a #VALUE! error.  If you need to use ranges that are located on different sheets from each other, it is recommended that you use the array form of the INDEX function, and use another function to calculate the range that makes up the array.  For example, you could use the CHOOSE function to calculate which range will be used.

For example, if Reference describes the cells (A1:B4,D1:E4,G1:H4), area_num 1 is the range A1:B4, area_num 2 is the range D1:E4, and area_num 3 is the range G1:H4.

Remarks

  • After reference and area_num have selected a particular range, row_num and column_num select a particular cell: row_num 1 is the first row in the range, column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of row_num and column_num.

  • If you set row_num or column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively.

  • row_num, column_num, and area_num must point to a cell within reference; otherwise, INDEX returns a #REF! error. If row_num and column_num are omitted, INDEX returns the area in reference specified by area_num.

  • The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL(«width»,INDEX(A1:B2,1,2)) is equivalent to CELL(«width»,B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1.

Examples

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter.

Fruit

Price

Count

Apples

$0.69

40

Bananas

$0.34

38

Lemons

$0.55

15

Oranges

$0.25

25

Pears

$0.59

40

Almonds

$2.80

10

Cashews

$3.55

16

Peanuts

$1.25

20

Walnuts

$1.75

12

Formula

Description

Result

=INDEX(A2:C6, 2, 3)

The intersection of the second row and third column in the range A2:C6, which is the contents of cell C3.

38

=INDEX((A1:C6, A8:C11), 2, 2, 2)

The intersection of the second row and second column in the second area of A8:C11, which is the contents of cell B9.

1.25

=SUM(INDEX(A1:C11, 0, 3, 1))

The sum of the third column in the first area of the range A1:C11, which is the sum of C1:C11.

216

=SUM(B2:INDEX(A2:C6, 5, 2))

The sum of the range starting at B2, and ending at the intersection of the fifth row and the second column of the range A2:A6, which is the sum of B2:B6.

2.42

Top of Page

See Also

VLOOKUP function

MATCH function

INDIRECT function

Guidelines and examples of array formulas

Lookup and reference functions (reference)

Like this post? Please share to your friends:
  • Excel index match all matches
  • Excel index by column name
  • Excel index and match formula
  • Excel include personal information
  • Excel in words formula