Имя книги формула excel

 

Юрец

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

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

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

 

Sanja

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

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

#2

13.03.2016 22:36:23

Здравствуйте. См. справку по =ЯЧЕЙКА()

Код
=ПСТР(ЯЧЕЙКА("имяфайла");ПОИСК("[";ЯЧЕЙКА("имяфайла"))+1;ПОИСК(".xls";ЯЧЕЙКА("имяфайла"))-ПОИСК("[";ЯЧЕЙКА("имяфайла"))-1)

Изменено: Sanja13.03.2016 22:49:52

Согласие есть продукт при полном непротивлении сторон.

 

Юрец

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

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

Посмотрел справку, подставил = ЯЧЕЙКА(«имяфайла») выдала весь путь.
хотел сказать спасибо, а тут формула, попробовал =песня(!);Спасибо(!)

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Небольшой нюанс — лучше указывать ссылку на ячейку в этой книге — иначе будет возвращать путь всегда к активной книге.
Чуть подробнее работу функции ЯЧЕЙКА в данном случае здесь описывал:

Как получить имя листа формулой

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Юрец

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

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

Включил запись макроса, сделал пару действий и возник вопрос: А как подтянуть формулу?
Остановил макрос, открыл vba вижу записаный код, понимаю что надо разместить формулу, но как  и где? Что надо сделать?

 

vikttur

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

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

 

kuklp

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

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

E-mail и реквизиты в профиле.

#7

14.03.2016 00:12:44

Так формулой, или ВБА?

Код
Function BookName$()
    BookName = Left$(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".") - 1)
End Function

Я сам — дурнее всякого примера! …

 

Юрий М

Модератор

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

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

#8

14.03.2016 00:15:12

А так не проще?

Код
ActiveCell = Split(ThisWorkbook.Name, ".")(0)
 

kuklp

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

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

E-mail и реквизиты в профиле.

#9

14.03.2016 01:14:52

Не проще, Юр. В имени может быть сколько угодно точек. Это не ДОС :) Вот кстати, моя лиса так с форума качает: Суточний звіт.xlsm.xls, Щотижневий звіт.xlsm.xls

Изменено: kuklp14.03.2016 01:18:05

Я сам — дурнее всякого примера! …


Имени текущей книги можно получить с помощью функции

ЯЧЕЙКА()

.

Функция

ЯЧЕЙКА()

возвращает

имя текущей книги

(файла) в двух случаях:


  • =ЯЧЕЙКА(«имяфайла»)

    Типичный результат:

    С:XLSПримерыТекст[Переводчик.xlsx]Лист1

  • =ЯЧЕЙКА(«адрес»;Лист2!A1)

    , где второй аргумент – ссылка на ячейку на другом листе. Типичный результат:

    [Переводчик.xlsx]Лист2!$A$1

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

F

9

(Вкладка

Формулы

, Группа

Вычисление

,

Пересчет

).

Если в ячейке

А1

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

файл примера

):

=ПСТР(A1;ПОИСК(«[«;A1)+1;ПОИСК(«]»;A1)-ПОИСК(«[«;A1)-1)

Формула предполагает, что название файла заключено в скобках [  ], находит позиции этих символов и извлекает все что между ними.

Если имя файла содержит символы [ и ], то функция

ЯЧЕЙКА()

заменит эти символы на скобки ( ). Поэтому, с помощью этой функции имена файлов

Перево[дчи]к.xlsx и Перево(дчи)к.xlsx

различить нельзя.

Excel для Microsoft 365 Excel 2021 Excel 2019 Excel 2016 Excel 2013 Excel 2010 Еще…Меньше

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

Вставка текущего имени файла, его полного пути и имени активного листа

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

=ЯЧЕЙКА(«filename»)

Вставка текущего имени файла и имени активного листа

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

=ПРАВСИМВ(ЯЧЕЙКА(«filename»);ДЛСТР(ЯЧЕЙКА(«filename»))- МАКС(ЕСЛИ(НЕ(ЕОШ(ПОИСК(«»;ЯЧЕЙКА(«filename»); СТРОКА(1:255))));ПОИСК(«»;ЯЧЕЙКА(«filename»);СТРОКА(1:255)))))

Примечания: 

  • Чтобы ввести формулу в виде формулы массива, нажмите клавиши CTRL+SHIFT+ВВОД.

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

Вставка только текущего имени файла

Введите или вставьте следующую формулу, чтобы вставить имя текущего файла в ячейку.

=ПСТР(ЯЧЕЙКА(«filename»);ПОИСК(«[«;ЯЧЕЙКА(«filename»))+1; ПОИСК(«]»;ЯЧЕЙКА(«filename»))-ПОИСК(«[«;ЯЧЕЙКА(«filename»))-1)

Примечание: Если вы используете эту формулу на несохраненном листе, вы увидите сообщение об ошибке #ЗНАЧ! в ячейке. После сохранения листа ошибка заменяется именем файла.

Дополнительные сведения

Вы всегда можете задать вопрос специалисту Excel Tech Community или попросить помощи в сообществе Answers community.

Нужна дополнительная помощь?

@liverlarson 

Does Office 365 Excel support VBA?

All versions of Windows desktop Excel from Excel 5 through Excel 2019 support VBA.

This includes the version of Excel installed by Office 365. …

There is no version of Excel Online, iOS Excel or Android Excel that supports VBA.

Nor does any version of Excel that runs on Windows RT support VBA.

In my humble opinion, it would be good to always have the possibility of VBA in Excel.

All new options such as editing PDF and cloud options, in all future versions, will be require VBA.

Unless someone has already adjusted to Java script … which I don’t hope.

What I don’t know is, if you maybe can open from the Developer tab in Visual Basic editor, I don’t have Office 365 yet. You can try it, maybe…maybe it will work.

The sequence is in Excel 2016

     Click File

     Click Options

     Click Customize Ribbon

     Under the list of Main Tabs, select Developer

     Click OK

The Developer tab will now appear on the Ribbon and from it you can open the Visual Basic Editor.

 If opening the Developer tab and clicking a button is a little too much work, you can also open the editor with the keyboard shortcut Alt+F11, which works whether the Developer tab is enabled or not.

As I told you before, with the logic of Excel 2016.

Nikolino

I know I don’t know anything (Socrates)

In this example, the goal is to return the name of the current workbook with a formula. This is a fairly simple problem in the latest version of Excel, which provides the TEXTAFTER function and the TEXTBEFORE function. In older versions of Excel, you can use a more complicated formula based on the MID and FIND functions. Both options rely on the CELL function to get a full path to the current workbook. Read below for details.

Get workbook path

The first step in this problem is to get the workbook path, which includes the workbook and worksheet name. This can be done with the CELL function like this:

CELL("filename",A1)

With the info_type argument set to «filename», and reference set to cell A1 in the current worksheet, the result from CELL will be a full path as a text string like this:

"C:pathtofolder[workbook.xlsx]sheetname"

Notice the workbook name is enclosed in square brackets («[name]»). The challenge then becomes how best to extract just the text between the square brackets from the path? The best way to do this depends on what Excel version you have. If you have the latest version of Excel, you should use TEXTAFTER and TEXTBEFORE functions. Otherwise, you can use the MID and FIND functions as explained below.

TEXTAFTER with TEXTBEFORE

In Excel 365, the easiest option is to use the TEXTAFTER function with the TEXTAFTER function like this:

=TEXTAFTER(TEXTBEFORE(CELL("filename",A1),"]"),"[")

This is an example of nesting — the TEXTBEFORE function is nested inside of the TEXTAFTER function, and the CELL function is nested inside of TEXTBEFORE. Working from the inside out CELL returns the full path to the workbook as explained above, and the result is delivered to the TEXTBEFORE function, which extracts all text before the closing square bracket («]»):

TEXTBEFORE(CELL("filename",A1),"]")

Delimiter is set to «]» in order to retrieve only text that occurs before the closing square bracket («]»). The result looks like this:

"C:pathtofolder[workbook.xlsx"

This value is then delivered to the TEXTAFTER function, which is configured to return text after the opening square bracket («[«):

=TEXTAFTER("C:pathtofolder[workbook.xlsx","[")

The final result from TEXTAFTER is the workbook name only:

"workbook.xlsx"

Assuming a path like «C:pathtofolder[workbook.xlsx]sheetname», the final result is «workbook.xlsx». 

MID + FIND function

In older versions of Excel you can get the workbook name with a more complicated formula based on the MID and FIND function:

=MID(CELL("filename",A1),FIND("[",CELL("filename",A1))+1,FIND("]", CELL("filename",A1))-FIND("[",CELL("filename",A1))-1)

This formula is annoyingly complex, mostly because older versions of Excel do not have good text parsing functions, and this means the formula needs to work in small, redundant steps. Notice the CELL function is called 4 times! 

To extract the workbook name, the formula works in 5 steps:

  1. Get the full path and filename.
  2. Locate the opening square bracket («[«).
  3. Locate the closing square bracket («]»).
  4. Calculate the length of the workbook name in characters.
  5. Extract the text between square brackets with the MID function.

Get path and filename

To get the path and file name, we use the CELL function like this:

CELL("filename",A1) // get path and filename

The info_type argument is «filename» and reference is A1. The cell reference is arbitrary and can be any cell in the worksheet. The result is a full path like this as text:

"C:pathtofolder[workbook.xlsx]sheetname"

The path starts with the drive and includes both the workbook name and the Sheet name. Notice the workbook name appears enclosed in square brackets.

Locate opening square bracket

The location of the opening square bracket («[«) is determined like this

FIND("[",CELL("filename",A1)) // returns 19

The FIND function returns the location of «[» (19) . We then add 1 because we want to extract text starting one character after the «[«. We can now rewrite the formula like this:

=MID(CELL("filename",A1),20,FIND("]", CELL("filename",A1))-FIND("[",CELL("filename",A1))-1)

Locate closing square bracket

Next, we locate the closing square bracket «]» in the same way with the FIND function:

FIND("]", CELL("filename",A1)) // returns 33

The FIND function returns 33, from which we subtract 1, in order to extract text up through character 32.

Calculate the length of the workbook name

The final step is to extract the text between the square brackets, and this is done with the MID function. We know where we want to start (20) and where to end (32). However, while the MID function takes start_num as the starting position, there is no equivalent end_num. Instead, MID takes num_chars, the number of characters to extract. Therefore, we need to calculate num_chars by subtracting the opening bracket «[» location from closing bracket «]» location. All of the code below simply calculates the number of characters to extract:

=FIND("]", CELL("filename",A1))-FIND("[",CELL("filename",A1))-1

Using our test path above, the result is 13. This is the length of the workbook name in characters.

Extract the text between the brackets

We can now rewrite the formula like this:

=MID(CELL("filename",A1),20,13)
=MID("C:pathtofolder[workbook.xlsx]sheetname",20,13)
="workbook.xlsx"

The final result is «workbook.xlsx». 

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