Find path of excel

When you are working on an Excel workbook, you may need to refer to the path of this file. In this article, we will show you 3 methods to get the path.

Getting the path of the current workbook seems to be very easy. However, if you close the folder and couldn’t remember the exact location, you will find it hard to get the path especially, especially when there are many files in your computer. You can certainly use the search feature in your computer.Search Feature in Computer

But if there are many files in your computer, you need to spend a lot of time on the search process. On the other hand, if there are many Excel files with the same name in different paths, you will still need to select them one by one. In order to get the path quickly, you can refer to the 3 methods below.

Method 1: Check Workbook Information

This method is very easy. Just click the tab “File” in the ribbon and you can get the information.Information

Here you will know the complete path of the current workbook. And then you can get access to the path easily.

Method 2: Use Excel Functions

You can only know the exact location of the path of current workbook. If you need to use the path in a worksheet, you can use Excel functions.

  1. Click the target cell in the worksheet.
  2. Now input the following formula into this cell”

=CELL(“filename”)

  1. And then press the button “Enter” on the keyboard.CELL Function

After that, you will see the path in the cell. Except for the path and the name of the current file, you can also know the active sheet.

On the other hand, when you don’t need the sheet name, you can also change the formula.

= LEFT(CELL(“filename”),FIND(“]”,CELL(“filename”)))

This formula will get the path to the name of the workbook.Second Formula

In addition, you can also get only the exact path without the name of the workbook. And the formula will be this:

=LEFT(CELL(“filename”),FIND(“[“,CELL(“filename”))-2)

When you press “Enter” on the keyboard, you will see the result immediately.Third Formula

You can choose one of the formulas according to your actual need. When you need to use the path, you can copy it and paste as values. Therefore, only the path will leave in the target cell.

Method 3: Use VBA Macros

Except for the above two methods, you can also use VBA macros to finish this task.

  1. Press the shortcut keys “Alt +F11” on the keyboard to open the Visual Basic editor.
  2. And then click the tab “Insert” in the toolbar.
  3. After that, choose the option “Module” in the sub menu.Insert Module
  4. In this step, inputting the following codes into the new module:
'get only the path
Sub GetPath1()
  Range("B1") = ActiveWorkbook.Path
End Sub

'get the path with the file name
Sub GetPath2()
  Range("B2") = ActiveWorkbook.FullName
End Sub

'get the path with the file name and the sheet name
Sub GetPath3()
  Range("B3") = ActiveWorkbook.FullName & "," & ActiveSheet.Name
End Sub

There are three different macros in the codes. And for different purpose, the codes will be a little different. The first one will only get the path. The second one will get the path with the file name. And the last one will also get the worksheet name. You may also change the target cell in the codes according to your need.

  1. When you need to get the path, you can run the macro by clicking the button “Run Sub” or press the button “F5” on the keyboard. Thus, the result will appear in the designated cell.

Use VBA

A Comparison between Those Methods

In this table below, we have input the result of the comparison of the three methods.

Comparison

Check Workbook Information Use Excel Functions

Use VBA Macros

Advantages

This method will now change the current workbook. You can get 3 different types of the path by the different formulas. With just one click, you can get the result in your worksheet.

Disadvantages

If you need to use the path in a cell, you need to spending time inputting the path manually. When you need to use the path itself instead of the result of formulas, you need to paste values only. If you have no idea about VBA, this method will is not suitable for you.

Now you must have a comprehensive understanding of the three methods. And the next time, you can choose the most suitable methods according to your need.

Avoid Data Disaster is Next to Impossible

If you need to use Excel to finish your work, you will certainly deal with a lot of data and information. Therefore, you will sometimes meet with data disaster. And it is impossible that anyone can fully avoid the occurrence of data disaster. When Excel corruption happens, the only thing you can do is to repair it immediately. And in order to repair Excel xlsx file, you can use a third-party tool. This tool is capable of repairing most of the problems in Excel. Therefore, even though you cannot avoid data disaster, you will never lose your data.

Author Introduction:

Anna Ma is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including repair Word document damage and outlook repair software products. For more information visit www.datanumen.com

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

Получение местоположения книги с помощью формул

Получить расположение книги с помощью VBA

Получить местоположение книги с помощью Kutools for Excel хорошая идея3

Откройте содержащую папку с Kutools for Excelхорошая идея3


Получение местоположения книги с помощью формул

В Excel вы можете получить местоположение книги с помощью формулы.

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

Чтобы получить местоположение книги

= ЛЕВЫЙ (ЯЧЕЙКА («имя файла»; A1); НАЙТИ («[«; ЯЧЕЙКА («имя файла»; A1)) — 1)

Чтобы получить расположение книги и имя книги

= ПОДСТАВИТЬ (ЛЕВЫЙ (ЯЧЕЙКА («имя файла»; A1); НАЙТИ («]», ЯЧЕЙКА («имя файла»; A1)) — 1), «[«, «»)

Чтобы получить расположение книги, имя книги и имя активного листа

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

Ноты: Если вы никогда раньше не сохраняли активную книгу, первые две формулы вернут #VALUE! ошибок, а формула = ЯЧЕЙКА («имя файла», A1) вернет пустое значение.


Получить расположение книги с помощью VBA

Если вы хотите попытаться получить местоположение книги с помощью VBA, вы можете сделать следующее:

1. Включите книгу и нажмите Alt + F11 ключи для включения Microsoft Visual Basic для приложений окно, затем щелкните Вставить > Модули для отображения окна модуля.

2. Вставьте ниже код VBA в Модули окно.

VBA: Показать расположение книги

Sub DisplayWorkbookPath()
    MsgBox ActiveWorkbook.Path, vbInformation, "Workbook Path"
End Sub

3. Нажмите Run кнопку, затем появится диалоговое окно, в котором будет показан путь к книге.

документ получить расположение книги 1

Примечание: Если вы никогда раньше не сохраняли активную книгу, этот VBA выведет пустое диалоговое окно. Смотрите скриншот:

документ получить расположение книги 2

Если вы хотите показать расположение книги и имя книги, вы можете использовать ниже VBA:

VBA: Показать расположение книги и имя книги

Sub DisplayWorkbookFullName()

    MsgBox ActiveWorkbook.FullName, vbInformation, "Workbook Complete Path"

End Sub

Получить местоположение книги с помощью Kutools for Excel

Работы С Нами Kutools for ExcelАвтора Вставить информацию о книге вы можете получить расположение книги и затем вставить его в нужную ячейку.

После бесплатная установка Kutools for Excel, пожалуйста, сделайте следующее:

1. Выберите ячейку, в которую нужно вставить расположение книги, и нажмите Кутулс Плюс > Workbook > Вставить информацию о книге. Смотрите скриншот:

документ получить расположение книги 7

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

документ вставить информацию из книги

3. Нажмите Ok. Теперь выбранная вами информация вставлена.

документ получить расположение книги 5

Примечание: Если активная книга никогда ранее не сохранялась, эта утилита вернет текст «Эта книга никогда не сохранялась».

Щелкните здесь, чтобы узнать больше о вставке информации из книги.


Откройте содержащую папку с Kutools for Excel

Если вы хотите открыть папку, содержащую текущую книгу, вы также можете применить Откройте папку содержащие of Kutools for Excel.

После бесплатная установка Kutools for Excel, пожалуйста, сделайте следующее:

Активируйте книгу, в которой хотите открыть папку, и нажмите Кутулс Плюс > Workbook > Откройте папку содержащие. Смотрите скриншот:

документ получить расположение книги 8

Затем открывается папка, содержащая активную книгу.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Generally Excel.Exe will be located in C:Program Files (x86)Microsoft OfficeOffice15 in case of Excel 2013 / Windows 7. During installation, if another path is chosen, Excel.Exe’s location changes. Default Path is also dependent upon Office and Windows combinations. Sometimes, it may not be locatable at all.

To find the location of Excel.Exe –

1. Start Excel
2. Right click on Windows Task Bar > Start Task Manager > Processes tab (Task Manager can also be opened by pressing CTRL+SHIFT+ESC)
3. Locate Excel.Exe > Right Click > Open File Location to reach to Excel.Exe

1

1

VBA Approach – Immediate Window

1. Open any workbook and ALT+F11
2. If Immediate Window is not visible, CTRL+G
3. Put following in Immediate Window and Enter to display the path of Excel.Exe
? Application.Path

VBA Approach – Coding Approach (May be needed to access this location from another application)

1. Open any workbook and ALT+F11
2. Locate your Workbook name in Project Explorer Window
3. Right click on your workbook name > Insert > Module
4. Copy paste the Macro code given (Either of the Macro Code will work)
5. Go back to your Workbook and ALT+F8 to display Macro Window
6. Run your Macro from here

Sub GetExcelExePath()
    Dim Path As String
    Path = Application.Path
    MsgBox Path
End Sub
' By Jim Cone
' http://www.excelforum.com/excel-programming-vba-macros/524074-how-to-find-out-the-path-to-excel-exe-thru-vb.html
Sub GetExcelPathFromVB()
    Dim appXL As Object
    Dim s As String
    Set appXL = CreateObject("Excel.Application")
    s = appXL.Path
    MsgBox s
    appXL.Quit
    Set appXL = Nothing
End Sub

In my application after export excel or csv file then show the file in excel or notepad.
In this case am use

Excel:

  Dim xExcelFilePath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "Microsoft Office"
            xDir = New DirectoryInfo(xExcelFilePath)
            For Each xDirectory As DirectoryInfo In xDir.GetDirectories ' it use for find any version of excel is installed or not
                If xDirectory.Name.Count < 6 Then Continue For
                If xDirectory.Name.Trim.Substring(0, 6).ToUpper = "OFFICE" Then
                    If System.IO.File.Exists(xExcelFilePath & "" & xDirectory.Name & "EXCEL.EXE") Then
                        xExcelFilePath = xExcelFilePath & "" & xDirectory.Name & "EXCEL.EXE"
                        Exit For
                    End If
                End If
            Next
            If System.IO.File.Exists(xExcelFilePath) Then
                Dim p As New Process() ' xExcelFilePath means start and stop the local system process
                p.StartInfo.UseShellExecute = True
                p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
                p.StartInfo.FileName = xExcelFilePath ' Assaign the file name
                p.StartInfo.Arguments = """" + xDestinationPath + """"
                Grid1.SaveExcel(xDestinationPath, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly) ' Export the Excel File
                p.Start()

            Else
                Msg.Err("Could not find Excel installed on this system; file saved to:" + xExcelFilePath + ".")
            End If

Notepad:

 Dim p As New Process() ' xExcelFilePath means start and stop the local system process
            p.StartInfo.UseShellExecute = True
            p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
            p.StartInfo.FileName = "C:windowsnotepad.exe"
            p.StartInfo.Arguments = """" + Application.StartupPath & Grid1.ActiveSheet.SheetName & ".csv" + """"
            xCSVSheet.SaveTextFile(Application.StartupPath & Grid1.ActiveSheet.SheetName & ".csv", TextFileFlags.None, Model.IncludeHeaders.BothCustomOnly, "", ",", "")
            p.Start()

In above code in some system excel file path not in this order so its throw exception and Notepad exe is staticly added here. How can i get the exe file path in sysem?

In this example, the goal is to get a normal path to the current workbook, without a sheet name, and without the square brackets («[ ]») that normally enclose the workbook name. This is a pretty simple problem in the latest version of Excel, which provides the TEXTBEFORE function. In older versions of Excel, you can use a more complicated formula based on the LEFT and FIND functions. Both options use the CELL function to get a full path to the current workbook. Read below for a full explanation.

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]»). This is close to what we want, but there are still two tasks that remain:

  1. Remove the sheet name
  2. Remove the square brackets («[ ]»)

The best way to do this depends on what Excel version you have. If you have the latest version of Excel, you should use a formula based on the TEXTBEFORE function. Otherwise, you can use the LEFT and FIND functions as explained below.

TEXTBEFORE option

In the worksheet shown above, the formula in E5 is:

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

This is an example of nesting. The CELL function is nested inside the TEXTBEFORE function, which is nested inside the SUBSTITUTE function. Working from the inside out:

  1. The CELL function returns the full path as a text string, as explained above.
  2. The TEXTBEFORE function returns all text before the closing square bracket («]»).
  3. The SUBSTITUTE function replaces the opening square bracket («[«) with an empty string («»).

The final result is a path to the workbook like this:

C:pathtofolderworkbook.xlsx

Legacy Excel

In older versions of Excel without the TEXTBEFORE function, you can use a formula based on LEFT, CELL, FIND, and SUBSTITUTE:

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

At a high level, this formula works in 4 steps:

  1. Get the full path and filename
  2. Locate the closing square bracket («]»)
  3. Remove sheet name and «]»
  4. Remove the opening square bracket («]»)

Note: the CELL function is called twice in the formula because we need the path twice, once for the FIND function to locate the «]», and once for the SUBSTITUTE function to remove the «]». CELL is a volatile function and can cause performance problems in larger or more complicated worksheets. 

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:examples[workbook.xlsx]Sheet1

Note the sheet name(«Sheet1») appears at the end.

Locate the closing square bracket

The location of the closing square bracket («]») is calculated like this

FIND("]",CELL("filename",A1))-1 // returns 26

The FIND function returns the location of «]» (27) from which 1 is subtracted to get 26. We subtract 1 because we want to remove text starting with the «]» that follows the filename. 

Remove sheet name

In the previous step, we located the «]» at character 27, then stepped back to 26. This number is returned directly to the LEFT function as the num_chars argument. The text argument is again provided by the CELL function:

LEFT("C:examples[workbook.xlsx]Sheet1",26)

The LEFT function returns the first 26 characters of text.

C:examples[workbook.xlsx

At this point, LEFT has removed the sheet name, but notice the opening square bracket «[» remains.

Remove opening square bracket

The result from LEFT is returned to the SUBSTITUTE function as the text argument:

=SUBSTITUTE("C:examples[workbook.xlsx","[","")

SUBSTITUTE is configured to remove the opening square bracket by setting old_text to «[» and new_text to an empty string («»). The final result returned by SUBSTITUTE is:

C:examplesworkbook.xlsx

Понравилась статья? Поделить с друзьями:
  • Find parts of speech of a word
  • Find out word games
  • Find out what word describes you
  • Find out the word with meaning
  • Find out the word with a mistake